SIMPL Archives Part 3 - monsonite/SIMPL GitHub Wiki
The SIMPL Archives Part 3 Friday, January 15, 2016 A Review of Tiny Languages Part 1 Tiny Languages
This week I have been looking at bygone computers and some of the languages they used - tailored to work within the framework of their resource limited hardware.
My recent dealings with the "Forth-like" SIMPL language has led me to look for other examples of minimalist programming languages. Many of these were devised in the 1970s and 1980s - when home microcomputers were very short of memory resources.
In this post I look at some very small computer languages - often less than 4Kbytes in size.
My recent search has unearthed the following:
VTL Very Tiny Language - a BASIC like language for resource limited microcontrollers
VTL-2 An updated VTL with more features - yet assembles in 768 bytes
Mouse - developed in the late 1970s for electronic music applications on a PDP8
TinyForth - A cut down Forth, written in C or assembler
Txtzyme - an I/O oriented minimal control script with some Forth-like features
SIMPL - an extended version of Txtzyme to run on several platforms.
TinyBasic - various offerings available. TinyBasicPlus
Bitlash - a control oriented, Programmable Command Shell to run on Arduino
VTL
VTL is an interpreter designed in 1977 by Frank McCoy for the 6800 and 8080 machines of that era. The complete 6800 version of his interpreter is ROMable, IN 768 BYTES!
VTL was originally devised for the Altair 680 - an early 6800 microcomputer, with a strong similarity to it's stablemate the MITS Altair 8800 but much smaller in size. It had 1K of RAM and sockets to accept 1K of ROM. ROM chips at this time were likely to be only 256 bytes - so 4 sockets required!
There appears to be a following for VTL and its derivatives in Japan - so many of the references are Japanese websites - but easily translates with Google Translate.
Summary of VTL languages over the years - translate from Japanese
"Creating a VTL Language" Some description of VTL for 6800, 8080/Z80 and AVR - source code in assembler and C - Translate from Japanese. This site and source code provided by T. Nakagawa.
The author, T. Nakagawa, has provided source code (about 370 lines - see this Github Gist) that will run on an Arduino with a bit of fiddling. You will need to add the serial putchr and getchr routines to drive the UAR - and include the UART code from AVR-Lib.
Once these are added, it compiles to about 2.6K under the Arduino IDE. It should be noted that the AVR uses a 16 bit instruction word - so the byte count for AVR Flash code is generally about twice that of other 8 bit microcontrollers.
If you want to try out VTL - this is a packaged exe that runs on a PC in a command prompt window.
VTL remains of interest because it has some very compact C code for the various building blocks of a simple interpreter - and is relatively easy to understand its operation.
VTL-2
In 2007, some thirty years after his original VTL offering, Frank McCoy revisited his VTL and produced an extended and improved version of VTL - which still fits into 768 bytes (on 6800) The User Manual and some example programs are here.
Mouse
Mouse is a very small language that was written in the late 1970s - early 1980s by Peter Grogono.
It was a further development of his early 1970s system/language MUSYS - that was written to aid his work with early computer generated electronic music on resource limited PDP-8 machines.
Mouse took aspects of MUSYS and updated them to suit the late 1970s emerging microprocessor scene.
Here are some links:
The Mouse Programming Language
The Great Mouse Programming Language Revival
Wikipedia has further links that may be of interest.
Tiny Forth
This site and source code is again provided by T. Nakagawa, a Japanese enthusiast of Tiny languages.
He has written TinyForth both in well commented AVR assembly language (1964 bytes) and also in C that closely follows the assembly language. This not only gives a good illustration of how the language has been constructed but also how closely AVR assembly is matched to C.
I have created a Github Gist for this TinyForth - complete with UART getchr and putchr routines. The code compiles to 4854 bytes - I used Arduino 1.04 IDE - as I had some difficulty with later versions with getting the UART code to compile.
It appears to be a subset of Forth - but with sufficient keywords currently available to do simple tasks - but like any Forth is easily extended.
Input and Output is via a serial UART interface only - it would need further extensions to the dictionary to build up a vocabulary of I/O and timing functions for the Arduino/AVR.
The AVR assembly language version is much more compact - I have added a fully commented version to this Github Gist
If you want to write a Tiny Forth for an AVR or even an ARM - then this is a good place to study the basic language structure.
In conclusion - TinyForth looks like it could provide a useful kernel for a larger project. It would be worth compiling this source for an ATmega1284 - the extra RAM (16K) and additional I/O port would make a very capable Forth Computer.
As a newcomer to AVR assembly (but having done a lot of Z80 years ago) it is rewarding to see how readily C code can be translated to assembly language. A lot of the Forth primitive wordss are of immediate use for the Txtzyme/SIMPL interpreter (see below) - and having the C and assembler code together is a useful crib on how one might take the project forwards further.
Txtzyme
Txtzyme was created around 2010-2012 by Ward Cunningham. Txtzyme has the advantage that it is specifically oriented to I/O control and interaction - yet surprisingly simple.
The Arduino version allows simple control of the Arduino I/O and allows timing functions and loops. LED sequences, musical tone generation and printing serial output of analogue sensors are easily performed.
It is simple in nature - essentially just a single character interpreter contained within a loop. It uses a single stack variable x to control some parameter of the operation. It is fairly simple to understand and easily extendable to include further "words" such as arithmetical and logical functions.
The Arduino version is just 90 lines of code and compiles to 3518 bytes. The codesize can be much reduced by replacing some of the Arduino C functions with more compact code, possibly even resorting to AVR assembly language in order to make a more compact kernel.
The beauty of Txtzyme is it's simplicity and the fact that it can be easily tailored to suit a particular application.
Reducing the Code Size:
Removal and replacement of the Arduino Serial code and using a custom function to print a long number can bring this down to 1884 bytes.
Removal of the Setup() and loop() functions and replacing with a main() and a while(1) will reduce it to 1782 bytes - but at a loss of the timing delays and millis() functions
Removal and replacement of the Arduino delay and delay_microseconds code will bring it down to 1484 bytes.
Replacing digitalWrite with a simplified function - reduces it to 1040 bytes
Removal of analogRead and digitalRead reduces it by a further 92 bytes to 948 bytes.
digitalRead alone is 272 bytes!
If you want to try a cut down version of Txtzyme - I have paired out most of the bloat and put a 658 byte minimum kernel here. It doesn't do much - you have to add your own functionality in the form of case statements.
Txtzyme appears to indicate that a I/O oriented micro language is possible on the AVR (Arduino) in about 1024 bytes. This makes it possible to include it with a bootloader plus some extensions in under 2K.
The code-shrunk version of Txtzyme is available on this Github Gist You may wish to re-instate digitalRead (line 110) and analogRead (line 150) depending on your requirements.
Next Time
In the next post I look at SIMPL and how it has evolved from Txtzyme.
Sunday, January 31, 2016 A Review of Tiny Languages - Part 2
Tiny Languages - for Tiny Boards! It's a couple of weeks since the first part of this thread reviewing some Tiny Languages where I looked at some minimal BASIC and Forth-like languages.
Inspired by these examples, I wish to show how Ward Cunningham's Txtzyme interpreted language can be easily modified adding more features and functionality.
The aim is to have a tiny, generic language that can be embedded into the bootloader of any common microcontroller - providing a minimal operating environment from start-up.
What will such a Tiny Language require in terms of features and functionality?
Wish List
Any small language must provide a minimum vocabulary to be useful. Here are some thoughts on the bare essentials:
Arithmetic and Logical Operations + - * / AND, OR , XOR, INV Memory Operations - including loading, storing, saving to disk, and bootloading the flash or EEprom Program flow control - decision making - branching (IF, THEN, ELSE, SWITCH-CASE etc) Looping (DO WHILE, FOR- NEXT etc) I/O commands (digital read/write analogue read, pwm, etc). Timing, delays, and scheduling operations (mS_delay, uS_delay, millis() etc) Peripheral support - eg UART, SRAM, uSD, keyboard, mouse, graphics etc.
We also need as a minimum of system support for the language kernel:
Keyboard for text entry, Terminal output (serial UART routines) Text Editing (line editor) Hex Dump Screen listing of code in RAM
With these facilities we can at least enter, edit and run code using a serial terminal application and get output text to screen.
At a higher level - for a stand alone computing environment we need permanent storage to disk and some tools to make life easier:
Assembler Compiler Disk operations, File Handling (on microSD card) Graphical output to monitor.
SIMPL
Txtzyme offers a small, understandable, elegant and flexible core with UART communications, analog and digital input and output and delays and timing functions. It is almost the ideal platform on which to base other code. I have prepared a stripped down version of the Txtzyme interpreter kernel - which compiles to just 658 bytes. It is available here.
At the moment the cut down kernel doesn't do very much apart from allow a decimal number to be printed out using the "p" command. However, it represents about the minimum needed to support a UART interface, scan a text buffer and execute commands. Additional commands are added in the switch-case statement within the textEval() function.
This led me to a series of experiments in which the features of Txtzyme were extended - which resulted in SIMPL (Serial Interpreted Minimal Programming Language).
SIMPL has been ported to several microcontrollers - including MSP430, STM32F103, STM32F373, ' 407 and '746 - as well as an FPGA softcore processor called "ZPUino".
SIMPL offers an easy way to interact with hardware, to compose new functions and to schedule functions to be triggered either sequentially or at regular intervals. It is based on the Txtzyme core functionality - about 1Kbytes which gives a basic communications channel, text entry and display and the means to exercise common microcontroller hardware peripherals.
Adding Maths and Logic Operations
Txtzyme only used a single 16 bit integer variable x, as a control parameter for the coded functions. Whilst this was OK for running loops, reading the ADC channels and toggling I/O it was a little restrictive.
The first extension to Txtzyme was to create the means to have a second variable y. This immediately allows simple mathematical and logic operations to be performed.
Arithmetical + - * / %
Logical AND OR XOR NOT
Comparison < >
In Txtzyme, typing a number at the keyboard, with a serial terminal application causes the interpreter to decode the number's ascii string and place the number into the single parameter variable x. x can then be used to access I/0, set up loops and delays and other functions.
In SIMPL, there is a second parameter variable y, and this is used to hold a second operand.
Typing
456 123+p (note the space between 456 and 123)
This pushes 456 into x and then the space is SIMPLs method of moving x into y, so that the interpreter is free to accept the second number 123 into x. In the above example 123 is added to 456 in x and the result printed with p.
This arrangement is a kind of pseudo-stack of just 2 levels x and y, and note that unlike a true stack, y does not move up to occupy x when x is printed out. Perhaps it should be thought of a s a machine with 2 registers x and y, and "space" is equivalent to mov x,y.
Additional registers could be added but there is the complication of naming them.
With 2 registers we can now do simple maths, memory addressing and logical and comparison operations.
The addition of these arithmetical and logical operators adds a further 360 bytes to the kernel. This seems quite a lot for just 9 functions - and so at this point I began wondering whether the extensions to the kernel might be best done in AVR assembly language. You may recall that an AVR instruction takes up 2 bytes of flash memory - so my C code case statement selection structure is using on average 20 instructions (40 bytes) per command. (MUL, DIV and MOD will be more).
Whilst Txtzyme was purely a 16bit implementation, if x and y are cast as long integers, then all operations are extended to 32 bit. This however increases the code size by around 625 bytes (as the 32 bit mats operations all take up more code to implement in C).
It would be possible to make a more compact version of SIMPL by coding up the routines in AVR assembly language rather than C. Having studied the TinyForth code structure - the primitive execution structure is coded such that the commands occupy an average of 24 bytes (for 29 commands). This would result in a 40% reduction in codesize - so is well worth considering. The topic of coding SIMPL for assembly language plus an analysis of the SIMPL virtual machine will be covered in a later post. It might just be time to fire up Atmel Studio and start writing some AVR assembly code!
Memory Operations
In keeping with Forth parlance the basic memory operations are Fetch @ and Store ! These effectively are the equivalent of Peek and Poke - and operate on a 16 bit wordsize. With fetch and store there is now the means to take a number off the stack and place it anywhere in RAM, or conversely take a word from RAM and place it on the top of the stack. The exact location of the storage could be derived from a variable's name, or it could be in a set of easily accessed named registers, eg. R0, R1, R2.....
Text Input and Output
Txtzyme offered a very simple mechanism of loading up a character buffer with the inputted text from the UART serial communications. It would carry on filling the input buffer until a newline character was found, or the end of the buffer was reached. The input buffer essentially held the whole Txtzyme phrase, and on detecting the newline character would begin to interpret each character in turn, decoding it and calling the various functions associated with each character.
When I wrote the first draft of SIMPL, I realised that I could store the inputted characters into any buffer I wished, by redirecting the input characters to a new named buffer. I used uppercase ASCII letters for these buffers, named A through to Z. When I wanted to redirect the input characters to a new named buffer, all I had to do was use a colon : at the start of the line, followed by the naming character - eg M.
:M - the start of a new buffer called M
I chose for convenience to make all of these buffers the same fixed length (48 bytes), so that the start address of the buffer could easily be calculated from the ASCII code of the letter.
In this example M is code 77 in ASCII, and A is 65, so it's easy to allocate 48 byte buffers, just by multiplying up the ASCII value by the 48 byte length of the buffer, (plus an offset).
It becomes clear that these named buffers are in their own right small snippets of code - in effect subroutines, and in order to execute the subroutine it's just a case of typing it's naming letter.
Txtzyme subroutines are by their very nature quite short, and it was easy to fit almost everything that might conceivably wish to be done into a few tens of characters - hence it was found that 48 was a good size for the buffer - especially when the Arduino only has 2K of RAM to play in.
Forth readers will recognise this as a very crude means of creating a colon definition, storing the definitions executable code at a fixed address in memory - based on the ASCII name of the routine, and being able to effect a simple jump of the interpreter to that routine. It's a little like the restart RSTxx instructions on the Z80/8080. A few restart addresses that the program counter could be set to, in order to quickly call the most commonly used subroutines. In our case we have 26 to make full use of!
A "line printing" command to print out a string of the stored text from memory is the underscore character _ This is used as a pair surrounding the text message to be output for example
This is a message
We could include this with the previously defined "M" as follows
:M_This is a message_
The text handler would save this in the buffer associate with M, and every time the interpreter encountered the letter M it would print out the message
This is a message
Displaying and Editing Text
In a microcontroller system with only 2Kbytes of RAM, much of this can be taken up with the screen buffer - after all a 25 line x 80 column screen is 2000 bytes!
In a language such as Txtzyme and SIMPL, the source code has been tailored to consist of printable ASCII characters, with some degree of human readability. The system can easily perform a memory dump to the screen - which is effectively a program listing.
As the program consists of short subroutines threaded together, it would be possible to have a single stepping mode, where a cursor is highlighted as it steps through the current code. With a 115200 baud serial connection, the whole screen of text could be refreshed 5 times per second, more if only the active code is displayed.
Editing text is probably best done on a line by line basis. A line that requires editing can be brought up using the ? command and then copied into the input buffer, changes made and then pasted back to memory.
Some Forth systems use 1Kbyte blocks for storing and presenting their source code. A similar approach could be employed with SIMPL, with a block command to bring up a numbered block to the screen.
SIMPL is expressed as a series of tokens for compactness in memory and convenience of not having to scan for whole words - however there is no reason why it could be expanded to a more verbose format for screen listings - for example each lower case ASCII character could be expanded to a more easily read format. The table to do this would be retained in flash ROM - something that there is no real shortage of. For example:
a ANALOG b BLOCK c CALL d DIGITAL e END f FOR g GOTO h HIGH i INPUT j JUMP k COUNT l LOW m mS_DELAY n NUMBER o OUTPUT p PRINT q QUIT r RETURN s SAVE t TIME u uS_DELAY v VARIABLE w WHILE x 1st operand y 2nd operand z SLEEP
All of these will fit into 8 characters - so the additional space needed for the verbose form is 26x8 = 208 bytes
In Summary - So Far
So we have a language largely represented by single character instructions which when decoded by the interpreter cause a jump to a subroutine that defines the program's action. These character command words may then be assembled into sequences or phrases and stored into named buffer spaces for execution. New phrases may be compiled and stored at fixed addresses for later interpretation and execution. There is the means to enter and retrieve text from the RAM either by loading and storing single characters or numbers, or by using the text handler and the string printing command.
In Part 3 we look at the program flow control structures like LOOPS, SWITCH-CASE and constructs made up from conditional jumps.
Monday, February 01, 2016 A Review of Tiny Languages - Part 3 Last time I explained how to add more functionality to Txtzyme to build up a more versatile language that I call SIMPL.
In this post I look at a couple of ways to perform program flow control.
The latest version of SIMPL is located at this Github Gist - and includes the code below.
The 16 bit maths version compilese to 2268 bytes, whilst the 32 bit version, with it's more complicated 32bit maths routines adds a further 624 bytes.
Program Flow Control
So far, SIMPL lacks many of the usual program flow control constructs:
IF-THEN-ELSE
FOR-NEXT
DO-WHILE
SWITCH - CASE
- Simple Loop
SIMPL has a simple loop construct - where a block of code can be repeated k times before exiting the loop.
10{kp_ Green Bottles_}
This initialises the loop counter k to 10, and prints it out along with the text Green Bottles, decrementing k each time it goes around the loop.
This is similar to C's while(k) // k>0 { some task; k-- ; }
When executed, you will get this screen output:
9 Green Bottles 8 Green Bottles 7 Green Bottles 6 Green Bottles 5 Green Bottles 4 Green Bottles 3 Green Bottles 2 Green Bottles 1 Green Bottles 0 Green Bottles
ok
It is also reminiscent of the old Z80 instruction DJNZ, in which the B register was decremented and a relative jump to a label if it was non-zero. In SIMPL we effectively have 26 labels - the capital letters A to Z so this could be quite a useful feature. Loop can be used for any repetitive output task - such as flashing LEDs or playing musical tones.
The next construct required is the conditional jump. Here the number on the top of the stack, x should be compared against a constant y and a call to a block of code executed whilst the comparison remains true.
We have the means to perform logical and comparison operations on the top value of the stack.
AND & OR | XOR ^
These perform bitwise logic on the x and y operands.
AND may be used to check if x != 0 as it returns 1 for any value of x other than zero OR can check if x = 0 XOR can check if x != y
Greater Than > if x > y return 1 Less Than < if x < y return 1
Any of these operations may combined with a skip operation - skipping over the next operation if the result is true.
Here's the C implementation of the SIMPL comparison and jump operators:
// Comparison Test and conditional Group
case '<':
if(x break;
case '>':
if(x > y){x=1;} // If x > y x= 1 - can be combined with jump j
else x=0;
break;
case 'j': // test if x = 1 and jump next instruction
if(x==1){*buf++;}
break;
So we want to turn these simple comparisons into a more familiar IF-THEN construct.
The block of code to conditionally execute will be enclosed within square brackets [ ]
If the result if the comparison is true - then the code withing the brackets is executed, if false, the interpreter skips the words until it finds the last bracket and then resumes execution there.
Example If x > 10 then print "x greater than 10 "
11 10 >[x greater than 10]
11 assigns 11 to x "space" moves x to y 10 assigns 10 to x
performs x >y [ tests x for true x greater than 10 prints the message ] marks the end of the conditional execution block
Case Selection
The switch-case statement is a powerful mechanism in C, can it be easily implement in SIMPL?
We could restrict the number of cases to 26, allowing any of the capital letter words to be accessed directly.
Alternatively, we could select a phrase of code from a list of options - based on the value of x. This second methods is more general and is a lot more flexible, as it can incorporate the first method.
We need a pair of balanced characters to instruct the interpreter that we are looking at a list - so we could use simple parentheses and comma separated elements as follows (, , ,)
We then do a selection of the elements based on the numerical value of x. The interpreter then jumps into the array, skipping over the entries until the correct one is found.
As an example, the word M is code for This is a test Message
5(0p,1p,2p,3p,4p,M,6p) should select M and print the associated message
A second example adds two integers and prints the message if the result is 3
1 2+(0p,1p,2p,M,4p,5p,6p)
The mechanism to do the skipping can be quite elegant using some simple rules:
First, the value of x is copied into the loop-counter variable k. If k > 0 the interpreter checks each character in turn incrementing the buffer pointer. If a comma is detected, signifying the end of the first list entry , k is decremented. If k is zero, the interpreter executes the following table entries until the next comma is detected, this also subtracts one from k forcing it to be less than zero, this condition then forces a break out of the list. If the final ) is found - this also forces a break out of the selection statement.
This construct is derived from the SIMPL Loop method. We provide C code for two new case statements "(" and ","
// Select the xth member from the list // Example 5(0p,1p,2p,3p,4p,5p,6p) should select 5 and print it
case '(':
k = x; // copy x to use as the "phrase counter"
while (k)
{
ch = *buf++;
if (ch == ',') // decrement k to see whether to interpret or not
{ k--;}
}
break;
case ',':
k--;
while (k<0 nbsp="" y="">
{
ch = *buf++; // skip the remaining characters
if (ch == ')') {break;}
}
break;
This technique could also be used as a look up table, where a given x is converted into a different value according to a list of numbers.
10(1,2,3,4,5,6,7,8,100,200,300,400)p
This will select element 10 (300) and print it. Note that the first element is zero!
Friday, February 26, 2016 The Great MSP430 Bootloader Swindle Bootloading Blues.
The MSP430 is a great little micro, and with some proper marketing, it could easily have provided an alternative to the AVR and PIC. However unclear, obfuscating, archaic documentation, spread very thinly over the web has made this little micro the poor relation of the microcontroller world.
I write this having just spend a considerable amount of time in February trying to provide an effective solution for programming one of our products, an MSP430 based force gauge, which is being produced by a new supplier.
Unfortunately the original programmer from Gessler is no longer available, and so an alternative was needed.
The solution was actually staring in me in the face - so simple, that it's elegance seems to have been lost in the mists of time, and the desire to make everything a lot more complicated than it needs to be.
Here I summarise my findings in an attempt to provide a reference that will allow others to benefit from my 3 weeks of frustrating work and false starts.
AS a prologue to the main post - here is an unpublished post from 3 weeks ago - when I first started on this mission
(Previously unpublished - from Feb 9th 2016)
We have an on-going project at work, which needs an MSP430 bootloading over it's serial port with a hex file. So we went out and bought the cheap open source, Rocket BSL programmer from Olimex.
I then found that I needed the drivers and other software from TI, which I had to register for and then declare to the US Government that I wasn't going to use it against America in any way, shape or form. So far, so good.
North Korean? No, just Bulgarian. The MSP430-BSL is described as a joint project between Olimex and Texas Instruments. The reality is that no-one really wants to take ownership of it, and there is no one specific site that you can go to that gives you everything you need to get this programmer to work. It's like the code has been fragmented and spread to the four corners of the known cyber world - lest anyone dares try put the fragments together again and unleash the awesomeness of this great force on mankind. What I'm trying to say is that both Olimex and the Mighty TI have this time shot themselves in both feet, and it's no surprise that the MSP430 is languishing in some stagnant microcontroller cul-de-sac.
After mulling this over for a while, I began to think that proprietary bootloaders often really suck. There should be a simple, low cost universal tool which allows you to squirt code from a hex file into any microcontroller, from any platform. And that got me thinking about the humble USB-serial programming cable - such as those by FTDI, SiLabs or our Chinese friends who make the CH340.
It also appears that others have had this thought. In my search for an alternative MSP430 programmer, I found this interesting approach from Flying Camp Design - a programmer that is literally not much more complicated than an FTDI cable - just an FT232R on a small pcb.
Bootloaders are usually designed to be small, and not particularly human-friendly, because they are normally talking to some proprietary application running on the pc. But this doesn't need to be the case, there is sufficient flash space in the boot block of most micros to put a more sophisticated bootloader program - one which is actually capable of running some interpreted commands and presenting a more human friendly face to the user.
Getting Started
The MSP may be programmed by one or more of the following interfaces:
- A Serial Boot Loader - resident on all MSP430 devices - known as BSL
- A JTAG interface/programmer
- SpyByWire - a 2 wire serialised version of JTAG.
The Electrical Interface
Our force gauge product has a 6 pin connector on board intended for a BSL programmer. This has the following signals present - wired to pins on the IC:
TX RX TEST RESET 0V VCC
A combination of signals on the test and reset pins puts the device into bootloader mode. The data is then sent by the PC and received by the Rx pin and acknowledged by the Tx pin.
The Spec Document
The bootloader is fairly well specified in TI's document SLAU319 - and for anyone wishing to understand the bootloader, this should be the starting place.
When the MSP430 was first designed, the engineers made available a small bootloader program, residing in protected ROM, which allowed serial communication directly to a PC via a couple of pins. The BSL interface also allows you to read the contents of the Flash, erase it, verify and a range of other commands - some protected by a password mechanism - so as to avoid illegal copying of protected IP.
Towards the middle of the SLAU319 document, a circuit for a programming interface is provided:
This circuit dates from the early 2000's - when all PCs and laptops came with 9 pin serial COM ports.
In essence, there are three, level shifted outputs from the COM port to the target device, and one level shifted input back to the PC. Modern RS232 generally puts out +/-6V - and we need 0-3V TTL levels for the MSP430. The circuit is powered by harvesting spare energy from the output lines through diodes and pumping up a capacitor. The raw supply feeds the TL062 op-amp and is then regulated to 3V to provide a stable supply for the 74AHC14 Schmitt inverters.
This really is a very simple circuit - but sadly off-putting because it uses about 25 components and uses the now obsolete 9 way D-type and COM port.
What is really needed is a modern equivalent that works with USB and modern software drivers.
USB Implementation.
There are several low cost USB to serial converter chips to choose from, including FTDI, CP2102 (SiLabs) and the newer Chinese CH340G. All of them have the potential to work in this circuit.
I covered the CH340G in a recent post and the datasheet is here. The CH340 is low cost and easy to use. I have subsequently used the CH340G on some of my other projects.
For my experimentation, however, I used a SiLabs CP2102 device mounted on a small pcb - solely because I had it lying about. It breaks out all of the common RS232 signals - including RTS and DTR which we need. These modular devices are available from ebay for a couple of dollars - and a variety to choose from.
CP2102 module by Baite Electronics The one above comes with a set of double ended leads - so you can easily make up your own custom cable.
So to make this work we need to access Tx, Rx, RTS and DTR. RTS and DTR are often available on the 4 way headers down the side of the module.
The module also conveniently supplies a 3V3 supply from an internal voltage regulator(see datasheet) - this can supply a maximum of 100mA - more than enough for powering most MSP430 dev-boards.
Programming Application Software
I tried a couple of programming applications, with very little success - until I stumbledMSPFET - from a Russian gentleman Kurt. This did exactly what was needed - allowing a hex file to be loaded into the MSP430.
Programming the MSP430 really is that cheap and easy - using free software and a USB to serial module costing under $2 - finding out how to do it - from the information spread over the web it - was so very much harder.
Common Myths - Busted
You don't need a $300 JTAG Programmer. In desperation I found a FET-Pro 430 reduced to $50 on ebay.
You don't need an $11 Olimex MSP-BSP "Rocket" Programmer. I bought two of these from Mouser - I am still trying to find the correct software to make them work.
In conclusion
The BSL feature that comes with almost all MSP430 devices is great at doing what it was intended for - a very simple means of getting your hex file into the MSP430's flash.
The resources needed to make this work are trivial, and it could make a great addition to any application that needs the ability to modify the flash memory.
Unfortunately, the documentation has been obfuscated and made more compex than needs-be by JTAG and SpyByWire (for debugging) - and so few people are aware what a simple facility BSL is to use. The hardware needed in the form of a USB - Serial converter should be part of every hobbyist's or Engineer's toolkit.
The resources needed to make this work are trivial, and it could make a great addition to any application that needs the ability to modify the flash memory.
The protocol is simple, as is the 2 signal start-up sequence - and at a pinch, if you didn't have a serial converter that supports DTR (eg FTDI cable) you could hack an Arduino or Launchpad to generate the start-up sequence. You could even make a standalone programmer for repeat programming of boards out in the field using a Launchpad.
Energia has made the MSP430 more accessible - providing an Arduino like development environment. However, it is still nice to know how the simple low-level bootloader scheme works. Wednesday, February 17, 2016 Experimenting with New Devices - Part 1 If you were to summarise the developments in microcontrollers over the last few years, you might suggest the movement to 32-bit, mainly through ARM devices, and the rise in open source hardware and software.
Another less well known development is the incorporation of Ferroelectric RAM or FRAM as an alternative to flash memory in the Texas Instruments (TI) range of MSP430 microcontrollers.
Using FRAM instead of Flash memory opens up some interesting possibilities:
FRAM is non-volatile - it retains it's content after power down It is low power - it can be programmed at low voltages It has a fast write speed - up to 8Mbytes per second - about 100 times faster than flash It can be used repeatedly like RAM - it does not wear out after some 10,000 cycles like Flash
Whilst I did gain some experience of the MSP430 some 12 years ago, the introduction of FRAM and modernised peripherals makes them an attractive proposition.
So I decided to invest a little time and money in exploring the new architecture and the new opportunities presented by FRAM technology.
This post and subsequent posts will look at these topics and make a comparison between the more familiar AVR and ARM based devices.
MSP430 Family.
The MSP430 is a 16-bit RISC type microcontroller, with a Von Neuman architecture. This is unusual for microcontrollers (most are Harvard architecture), as it combines both the instruction store and the data store into one unified memory area.
It arose from an early 1990's devices, which was an 8 bit processor, the TSS400-S2, for interfacing to sensors. This early datasheet gives some insight into the heritage from 25 years ago.
The memory architecture is further simplified, as the FRAM and SRAM blocks can essentially be treated as the same codespace for program execution, although execution from RAM is at up to 24MHz, whereas executing from FRAM is limited to 8MHz.
Energia - "Arduino" for the MSP430
The MSP430 range has been supported with low cost "Launch Pad" development boards since 2010, providing an alternative to the AVR or ARM based Arduino or mbed boards. This support extends to the open source Energia IDE project - which is essentially an Arduino compatible IDE (and lookalike) aimed at the various TI microcontroller families. With Energia you can take an existing Arduino sketch and run it directly on MSP430 hardware, with no or few changes. Arduino is certainly becoming a lingua-franca of these small dev-boards.
A look at the MSP430 FRAM devices
The two devices I wanted to explore are the MSP430FR57xx series and the MSP430FR59xx series. The MSP430FR5739 is available as as an Experimenter board - below.
The FR57xx series is the smaller of the two with 16Kbytes of FRAM and 1Kbytes of RAM and a maximum clock of 24MHz. It costs about £1.50 in 1off from Farnell and has the potential as being an alternative to Arduino (Nano beater) - with very few other system components required. It has 30 GPIO lines which makes it a very good fit for the WiNode 5 format pcb with the extended Arduino headers. Available in a 38pin TSSOP package, which makes it a little easier for home construction.
The FR5969 has 64kB of FRAM, 2K of RAM and a 16MHz clock.
It offers 40 GPIO pins, plus the ability to use both high frequency (16MHz) and low frequency (32768Hz) crystals.
It comes in 40 pin QFN and 48pin QFN packages. A slightly smaller device- with marginally less I/O, the '5959 is available in a 38 pin TSSOP, making it compatible with the '57xx parts but with the beneffit of 64K FRAM and 2K RAM
The MSP430FR5969 is available as the MSP-EXP430FR5969 as a Launch Pad board - for about £12 from Mouser. This is exceptionally good value, and it has a number of accessory shields available.
Basic Features.
16 bit Von Neuman RISC architecture with 16Kbytes / 64Kbytes FRAM 16MHz (24MHz *) clock frequency 1.8V to 3.6V operation 100uA/MHz low power operation. 0.25uA RTC Multiple low power modes of operation 32 bit hardware multiplier Choice of 10 bit or 12 multichannel ADC 2 UARTS, SPI, I2C 5 Timers Low power oscillator Optional external 32kHz crystal Optional HF Crystal 16 bit CRC 128 bit/256 bit AES Encryption/decryption processor 31, 33 or 40 GPIO lines depending on package. Available in 38 pin TSSOP, 40QFN, 48QFN packages.
- Whilst the data sheet says 16MHz, it is perfectly possible to get the digitally controlled oscillator DCO to run at 24MHz. This might be good for a "Turbo-Boost" mode - when power is available.
Datasheet is here.
Tools & Equipment
The Launch Pad and Experimenter boards come with an on-board programmer section, which allows a hex file to be programmed into memory and allows debugging.
The TI Code Composer compiler and tool chain is distributed free of charge for working with these small boards.
If you want to try an open source compiler there is MSPGCC, and if you are seriously into command line hardcore development , you could try Michael Kohn's naken_asm which is a cross assembler for a wide variety of microcontrollers.
There are several free tools for loading the hex file into the MSP430. One that I tried is Elprotronics FET Pro-430 Lite which worked well with the on-board eZ-FET programmer on the launch pad board.
With the above tools I managed to flash a LED using assembly language and also drive a port line at about 2.5MHz square wave.
In Summary & Conclusion
The MSP430 are a fascinating family of microcontrollers. They have utilised every trick to achieve flexibility and very low power operation. The clocking and low power modes are a study in their own right - but TI through their Launch Pad series of dev boards have made a feature of low power operation - and encourage users to measure the operational current under various modes of working.
Not only is it a 16 bit machine, but it has a universal storage space - both code and data in one memory - which is all the more interesting for being non-volatile, high speed FRAM.
Although a RISC machine, the ISA is surprisingly versatile with a rich set of instructions and addressing modes.
Just exploring a new instruction set is fun in itself.
The 16 bit architecture is an ideal platform for developing Forth like languages - as these are often based on a 16 bit virtual machine. Jean-Michel Thooren's "Fast Forth" written in assembly language for the MSP430FR5969 may be of interest to Forth Fans.
Here is a very interesting device - it has a 16 bit architecture, 12 bit A to D and a Von Neuman architecture. It reminds me a bit of the PDP-8. More exploration needed.
In Part 2 I'll be looking at porting some existing code to the MSP430 and leveraging some Arduino sketches using Energia.
Wednesday, February 17, 2016 Experimenting With New Devices - Part 2
The '5969 Launch Pad - an ideal experimenting platform for FRAM
In this post I look at ways in which to get the most performance out of a small computer system based around the MSP430FR5xxx with external serial RAM and FRAM.
MSP430 Performance
The MSP430 being a 16 bit architecture is pitched performance-wise somewhere between AVR and ARM.
If you are doing a lot of 16 bit maths operations, then it will be quicker than the AVR as these are single cycle operations on registers, rather than having to combine two 8 bit operations.
This report compares execution time and code size for a number of common microcontrollers, in particular comparing MSP430 with ARM and AVR.
The speed up factor over an ATmega328 Arduino is as follows:
Simple Maths 1.27 FIR Analysis 3.29 Dhrystone 1.83 Whetstone 2.56
Average 2.24
When this is combined with a 24MHz clock - rather than the normal 16MHz clock on the Arduino the average speed improvement is approximately 3.35.
Code execution is fastest from RAM, so an important speed improvement will be achieved by copying all commonly used code from FRAM to SRAM at initialisation time. This copying process is extremely fast with 1Kbytes of FRAM memory contents copied to SRAM in approximately 128uS.
SIMPL on the MSP430
I tried SIMPL back in 2014 on a very low spec MSP430 value line device in a 20 pin DIL package with only 512 bytes of memory. The C code for SIMPL was compiled using the Energia IDE. There was no difficulty porting what had been an Arduino sketch to Energia - what runs under Arduino runs on an MSP430 under Energia, with zero or very little modification to the sketch. Only the lack of RAM on the MSP430G2553 device was a little problem.
Porting SIMPL to a FRAM Device.
Boosted by the initial success with the MSP430 Launchpad, in getting a basic version of SIMPL to run, I decided to invest in a couple of FRAM based devices.
First, I tried identical sketches on the ATmega328 and the MSP430FR5969. This was purely so that I could prove that they both ran as expected, and so I could compare the codesize and execution time for each implementation.
For the same clock frequency of 16MHz, the MSP version used about 80% of the codesize and executed simple loops containing integer maths at about 25% improved time.
It was now time to reduce the Arduino supplied UART routines (Serial.xxx) to self coded putchar, getchar and printlong. This process removed 2200 bytes of code from the implementation - down to 3720 bytes from a starting point of 5920.
The other large chunk of code is the array allocated to holding the initial word definitions. This is a 26 x 48 character array (1248 bytes) - which when removed brings SIMPL down to about 2472 bytes.
The other thing I noticed was that whilst the UART routines take just less than 300 bytes to implement, when they are combined with setup(), the whole thing bloats out to about 640 bytes. This needs further investigation because without this bloating, SIMPL could reside in just 2Kbytes of memory.
Making Use of the FRAM.
The question now is what new features can SIMPL leverage off the back of the MSP430's FRAM?
The write speed of FRAM is well matched to the higher baudrates of the USB to serial converter. Instead of 9600, we can now upload source code at 921600 baud or higher. Using a hex file format, a full 16Kbytes of code could be sent over the serial link in about 0.25 seconds.
The FRAM may be written to at 125nS per 16 bit word, so the whole FRAM storage space could be updated in about 1 milisecond.
The 10 bit ADC could send data back to the PC at almost 100ksps.
Execution from RAM is 3 times faster, so the primitives and the SIMPL kernel are loaded from flash into RAM during initialisation.
The MSP430 has a 20 bit address space, so up to 64 blocks of code could be swapped into FRAM when required.
Off chip storage could be uSD card or even serial FRAM - such as the Cypress 25LV20 which is a 256Kx8 SPI FRAM device in an 8 pin SOIC package. The SPI bus runs at a maximum of 10Mbit/s - so a "block load" of 1Kbytes is approximately 1mS or the time to load a full 16K block from external FRAM via SPI is 14mS. This is effectively 1uS access time to a large non-volatile solid state drive.
For faster access either dual SPI or Quad SPI would need to be employed. This can be done using bit-banging techniques using quite elementary code.
See the Microchip App Note AN1791 for details. A datarate of 8Mbyte/s should be achievable. This would allow the 23LC1024 to be fully read in about 16mS.
To be continued...... soon
Thursday, March 03, 2016 More MSP430 Machinations In the last few weeks I have been acquainting myself with the MSP430 - as a possible low cost candidate for future projects.
There are literally hundreds of different variations of the MSP430 - and to the newcomer the range of devices can appear to be quite daunting.
However, for my initial experiments I have been looking at some of the low end devices - which are particularly accessible in terms of very low cost and ease of use - and available for the MSP430G2XX Launchpad dev-board.
The low-end devices are interesting because of their low cost and flexibility of peripherals, and the combination of a 16 bit ADC and a high speed universal serial peripheral makes for some novel sensor applications - particularly when applied to strain gauge, loadcell and barometric sensors.
Low Cost Hardware - and Free CCS Compiler
This entry level Launchpad is available for about £7 (US$11). It comes with integrated programmer/debugger and will accept most of the DIL packaged MSP430 ICs. The free to use Code Composer Studio IDE, consisting of compiler, debugger and other workbench tools may be downloaded from the TI website - after a registration process has been completed. TI has produced dozens of useful code examples - which are a great way to learn the programming techniques of these devices.
The all round work-horse shipped with the Launchpad is the MSP430G2553 which comes in a 20 pin DIL package and has 16K of program space, but only 512 bytes of RAM. There is also, included with the Launchpad kit an MSP430F2542 with 8K of codespace but only 256 bytes of RAM. The MSP430G2553 does have a proper uart - but for BSL purposes Rx is on Port 1.5 and Tx is on Port 1.1.
The other device of current interest is the 14 pin DIL MSP430F2013 - which is a very low cost device but it's unique point of interest is that it is one of the few devices that has a 16 bit SD_16 A ADC and is ideal for sensor applications. However it has even less Flash (2K) and only 128 bytes of RAM! There is however 256 bytes of "Information RAM" - which is handy for storing device identity, calibration factors etc.
According to TI literature, the MSP430F2013 comes with a uart based bootloader (BSL). This is curious, and yet to be fully confirmed, as the uart is one hardware peripheral missing from the '2013!
There is a RAM based software BSL described in application note SLAA450
These small devices are all resource limited, but as such inspire ingenuity. Programming code for these is not-dissimilar to what programming the first generation microprocessors was like 40 years ago, but with moderately fast 16-bit, very low power processor plus uart or universal serial interface built in.
SIMPL Revisted
On small devices with perhaps only 2K bytes of flash memory available, I have revisited my implementation of SIMPL on the MSP430, as until now, I have focussed on AVR and ARM implementations. With a bit of help from online code examples - I have managed to eliminate much of the code intensive remnants of "Arduino" and shoehorned a full featured version of SIMPL into just 1868 bytes, putting it well within my self-imposed 2Kbyte limit. This makes it applicable to the '2013, '2452 and '2553 devices.
With additional functionality and further code optimisation then a 2K limit seems a reasonable size for the SIMPL kernel, especially if there is bootloader support included.
The code for the MSP430G2553 version is here on this Github Gist
I have implemented a 10 bit ADC on P1.3 which is read using the s (sample) command. To read 1000 consecutive ADC samples at 100mS intervals, the following code snippet of a sampling loop with delay can be used
1000{sq100m}
q prints the output of the ADC followed by a crlf.
With a bit of ingenuity it's possible to build up a horizontal bar graph display - of line length proportional to the input on the ADC.
:B s{[}q
Sample the ADC using s and print the corresponding number of brackets along a line. The final q prints the ADC value followed by a crlf.
SIMPLy Short of RAM
The smaller MSP430 parts are really quite short of memory with some only 256 or 512 bytes available. This really is a limitation when it comes to writing sketches in an interpreted language, so one possible solution is to add a serially accessed SRAM (or FRAM) on the SPI bus. This will extend the available memory to 32Kx8, 128K x 8 or even 256K x 8 in fast access non-volatile FRAM - (if your budget permits).
MSP enthusiast, Rick Kimball has written a library to access the 23K256. A single byte can be accessed in 98uS, but the full 32Kbytes can be streamed in 100mS.
The beauty of the SPI addressed memory devices is that they interface using just 4 pins - ideal for low pinout devices such as the '2013 and '2553.
A Historical Note on Memory.
Ever since the Manchester "Baby" the 1948 small scale experimental computer, the operation of the cpu has been intimately tied to the operating characteristics of the memory. The computer has essentially been designed around the best memory solution available at the time, be it Williams CRT Tubes, mercury delay lines, dekatron tubes or magnetic core memory. The PDP-5 and PDP-8 were designed specifically around the most economical core memory available in the mid-1960s - even though it took half a rack of circuit modules to interface to the core.
In some ways, the little computer that I am proposing, is the modern day equivalent of the PDP-8 (or possibly the 16 bit PDP-11). It is a compact 16 bit von Neuman architecture cpu with limited on chip storage, tied to a serial RAM, which can be efficiently accessed in pages or blocks of 32 bytes.
Within SIMPL it should be possible to write some User words to access the off chip serial RAM in an efficient manner - perhaps treating it like a virtual disk.
Next time - serial communications.
Friday, March 04, 2016 MSP430 Serial Communications Fun with the MSP430F2013.
I have been playing about with the MSP430F2013 for a couple of days now - and finding out what a wonderful little microcontroller it can be.
It really is short of both flash memory and RAM (2K and 128 bytes respectively) - so applications have to be very compact. However it makes up for these shortcomings with some very useful and flexible hardware.
My first application is to use it as a lower cost alternative to an AD7767 ADC which I currently use in a loadcell interface.
Although it does not have an on-chip 24 bit ADC, the output resolution of the SD_16 ADC should be sufficient for my immediate needs. This little $1.50 mcu already saves me $10 on not having to buy an AD7767 then service it with another mcu.
The second useful peripheral is the Universal Serial Interface (USI) - this is a flexible device used for both I2C and SPI communications, and as will be seen below later can also be used for high speed asynchronous uart communications too.
Using the USI
The universal serial interface is a flexible peripheral that is primarily intended to automate the processing of SPI and I2C communications. With a bit of bit-banging trickery - to add start and stop bits, it can also be used as a Transmit UART. Rick Kimball has also experimented with high speed asynchronous serial from the USI - which is capable of a massive 16Mbaud - but I doubt anything much over 3Mbaud will be accepted over a FTDI cable!
By way of a test, I hacked together a quick routing to read the ADC and send its 16 bit sample to the USI. At it's heart it has a variable length shift register which can shift a maximum of 16 bits. By adding in a start and stop bit, and setting the shift register length to 10 bits, the USI has no problem sending asynchronous serial data at up to 2Mbaud.
With potential serial at the processor full speed - SPI transfer at 16MHz should be possible - and it's definitely worth trying.
This will allow word length transfers to be made with the serial SRAM, and will be more efficient it setting up longer addresses.
The SRAM needs a 32 bit control packet to be sent prior to any transfer. This consists of an 8 bit instruction followed by a 24 bit address. The RAM handler code should be able to efficiently set this up and clock it out to the SRAM as two consecutive 16 bit transfers. From there on it just emits clocks (dummy bytes) to accept the data bytes from the RAM. On long sequential transfers about 300Kbytes per second transfers should be possible.
MSPEZIO
This is a collection of useful I/O functions to make your programming life a whole lot easier. Written for physics students at the University of East Carolina. I quote:
This guide is intended to serve as a fast introduction to the use of the msp430x2xx embedded microcontroller for use by students in Electronics and Advanced Laboratory environments. The intent is to allow an easy access to calls for I/O applications and serial communications transmitting data to external computers. It is assumed that the student has some understanding of c-programming and has been through the introduction to using the Code Composer Studio or IAR Embedded Workbench Kickstart, IDE’s.
16 Bit ADC
With code based on one of the mspezio examples, I was quickly able to get the SD16 ADC working and sending data out of a bit banged uart. MSPEZIO offers several examples that can be tried with CCS on the basic LaunchPad hardware.
The SD16 ADC is quite comprehensive - and the mspezio set-up made the initialisation of this peripheral a lot easier. I was able to set it up to read a strain-gauge based loadcell and send readings to the PC terminal application. The MSP430F2013 really only has just enough pins to allow a simple loadcell interface with serial comms. The output of the ADC values can be triggered by sending any character over the serial comms - using the mspezio WaitForSerial() function.
Much of the progress I have made with the MSP430 has been the result of evenings and weekends looking online at other code examples and good old experimentation. By modern standards the MSP430 is not a complex microcontroller, requiring significantly less initialisation code to get the basics working. I would recommend buying a Launch Pad to anyone who wants to tinker with something a bit different. As stated in a previous post, the board is low cost and there is free access to the CCS Code Composer Studio compiler and also the Arduino like Energia IDE. CCS offers multiple file projects to be built and debugged whilst Energia allows easy entry level to simple sketches.
SIMPL on MSP430F2013
The plan now is to get Energia working with the MSP430F2013 so as to allow a cut down version of SIMPL to be run on it.
Energia allows the SIMPL application to be built up a routine at a time - so that every last byte of precious code space can be efficiently used. This is very important on the '2013 - which only has 2K codespace and 128 bytes of RAM!
The biggest problem with the MSP430F2013 is that it does not have a proper uart peripheral and whilst uart transmit is possible using the USI module with a bit of trickery, the uart receive function becomes a major challenge - involving either a timer controlled sampling of the incoming bit stream or something as yet unknown.
The porting of SIMPL and the MSPEZIO helper functions to the '2013 will be the subject of a forthcoming post.
Saturday, March 05, 2016 Interfacing SPI SRAM & FRAM to the MSP430 This week I have mostly been experimenting with the low end MSP430 series of microcontrollers using the standard entry level LaunchPad.
So far, I have looked at serial communications, ADC interfacing and running small applications, written either on Code Composer Studio or using the Energia IDE.
In this post I look at the SPI interface with a view to accessing SPI memory - including SRAM and non-volatile ferroelectric RAM (FRAM).
The low cost MSP430 parts are often very limited in their RAM capacity. For most of this week I have been experimenting with the 2553 and 2013 parts which have 512 and 128 bytes respectively. Whilst this has been for sufficient for the smallest of applications to test the various on-chip peripherals, it's not enough for serious tasks.
I've used serial SRAM in the past, so decided that it would be a good exercise to interface it to the MSP430. I came across Rick Kimball's github gist a couple of days ago - where he had successfully interfaced a 32Kx8 23K256 device to the MSP430F2013 - using it's universal serial interface USI peripheral.
With this proven and working correctly on a breadboard, I chose to use Rick's code as a guide and make the necessary modifications so that the USCI on the MSP430G2553 could be used too. The '2553 part has two USCIs - one I am already using as a uart for PC communications, leaving USCIB free to work in SPI mode to talk to the SRAM and other devices.
Whilst I had good success with the '2013 part in my loadcell application, the lack of a proper uart peripheral made it too restrictive for any serious application that needs bi-directional serial communications with the PC, so I have parked '2013 developments for the moment, until I have time to look into implementing some form of software uart or some advanced trickery with the USI.
Here's the pinout of the MSP430G2553 - this is the most common part used in the entry level Launch Pad
+------U------+
3V3 |VCC GND | OV LED |P1.0 XIN | 32768Hz RXD |P1.1 XOUT| 32768Hz TXD |P1.2 TEST| ADC |P1.3 /RST| /CE |P1.4 P1.7| MOSI SCK |P1.5 P1.6| MISO (LED) D0 |P2.0 P2.5| D5 D1 |P2.1 P2.4| D4 D2 |P2.2 P2.3| D3 +-------------+
+------U------+
/CE | 23K256 | 3V3 MISO | | HOLD NC | | SCK 0V | | MOSI +-------------+
The 23K256 is very simple to interface - requiring just 4 wires to the SPI port. The Hold pin shoould be tied to 3V3 as it is not being used in this application.
The MSP430G2553 benefits from the 20 pin DIL package providing 6 additional port lines from Port 2. I have labelled these D0 - D5 - purely for familiarity with the Arduino way of naming pins, but they may also be used as additional inputs to the 10 bit ADC.
The firmware to exercise the SPI bus and access the SRAM has been based on Rick Kimballs code - but with changes made so that the USCI can be used. The code was written within Energia - but can easily be adapted for CCS or IAR Kickstart etc.
I have included the memory test sketch on this Github Gist.
In the next part of this MSP430 series I will attempt to make use of the SRAM within SIMPL, and make further use of the SPI bus for driving other hardware. Sunday, March 06, 2016 SIMPL for Beginners - Part 1 It's almost 3 years since I started on the SIMPL project, it has come a long way since it's early beginnings.
This first post, in a series, is a "catch-up" for those that have come late to the party.
Introduction to SIMPL
- SIMPL stands for Serial Interpreted Minimal Programming Language. It is intended as a common, interactive hardware exercising language that will run on almost any low-end, resource limited, microcontroller.
So far it has been implemented on the following microcontroller platforms
Arduino ATmega328 ATmega1284P
Nucleo RFDuino nRF51822 Cortex M0 STM32F103 Cortex M3 STM32F373 Cortex M4F STM32F407 Cortex M4F STM32F746 CCortex M7
LaunchPad MSP430G2553 MSP430FR5969 MSP430FR5739
Teensy 3.0, 3.1, 3.2 MK20DX256
Future development will include PIC16Fxxxx and PIC32MX devices too - made accessible using Pinguino - an Arduino-like IDE for PICs.
-
SIMPL is based, unashamedly on Ward Cunningham's excellent Txtzyme "Nano-Interpreter". You can find his work on his Txtzyme Github This should be the starting point of any SIMPL development. First you port the C code of Txtzyme across to whatever microcontroller you wish to use. Once you have Txtzyme working on your mcu, you can then start to extend it's functionality to include the whole SIMPL featureset.
-
SIMPL is a text-based interpretive tiny language, which interacts with the onchip hardware allowing simple applications to be developed for a variety of very low cost microcontrollers. It fits into about 2Kbytes of Flash and requires a minimum of 512bytes of RAM - so it will work on the smallest of RAM limited microcontrollers. It needs a uart connection to a PC terminal program - for text input and output. It is primarily aimed at 14 -28 pin low end microcontrollers - but of course, will run on larger parts.
-
SIMPL originally ran on Arduino. It makes use of the Arduino "Wiring" functions - such as digitalRead, digitalWrite, analogRead, analogWrite, millis, micros, delay, delayMicroseconds and Serial. Provided that your microcontroller can offer similar functions to these, SIMPL will work. SIMPL also runs on the Teensy series of mcu boards.
-
SIMPL can be developed for other microcontrollers - including ARM, MSP430, RFDuino, ESP8266 etc using the "Arduino-like" IDEs such as STM32Duino or Energiafor MSP430 and Pinguino for PIC devices. These alternative IDEs will help you with the various "Wiring" functions.
-
SIMPL has been written in C, to make it portable between various microcontrollers. It uses standard Arduino functions to interact with the hardware - which are perhaps not always the smallest or fastest. These functions can be rewritten for a particular microcontroller to make them both smaler in codesize, more efficient and faster.
-
SIMPL is not a polished final product, but it offers a framework for experimentation and education. As new hardware or ideas come along, SIMPL can be extended to incorporate them. The core ideas of SIMPL are easy to understand, and it gives a good insight into how computer languages are written to interact with the hardware.
-
SIMPL has been developed with the same methodology as some of the tiny languages from the mid-1970s - when computing resources were very limited. Tiny BASIC, and FORTH grew out of this period.
-
SIMPL can be easily extended to allow for external SPI or I2C peripherals - such as SRAM, sensors.
-
SIMPL needs almost no tools to develop code. Just IDE with serial terminal.
-
Enjoy SIMPL, extend and modify it if you wish - most of all, have fun!
The Command Set
SIMPL uses single ASCII characters for its commands and integer numbers for arithmetic - this makes the command interpreter a lot easier to write.
Lower Case characters are used for the core primitive functions which are generally built into Flash, and should be present for every implementation of SIMPL.
Punctuation characters and arithmetical symbols are also used as part of the kernel of primitives.
The choice of primitives was made to make the language memorable and more human readable.
Upper Case characters are "User Words" - these you can write yourself, test interactively, modify and store in RAM. On some microcontrollers - they may be stored in non-volatile ferro-electric memory FRAM (MSP430FR series) or in non-volatile EEprom.
Originally Txtzyme offered just these commands - see Ward Cunningham's Read Me:
a-f Select an I/O port h help - a summary of commands i input k a loop counter - which decrements each time around the loop see {} m millisecond delay o output p print the value of variable x followed by carriage return/line feed s sample an ADC channel u microsecond delay x a 16 bit integer variable {} code between these braces is repeated as a loop _ _ characters between the underscores are printed to the terminal
Once you have got Txtzyme ported across to your microcontroller, and have experimented with it, you are well on your way to working with SIMPL.
In the next part I look at how Txtzyme is extended to include the SIMPL framework.
It is likely that this series will be included on a SIMPL wiki - so that all the information is accessible in one place. Sunday, March 06, 2016 SIMPL meet SIMPLEX - Part 1 - Putting it Together
SIMPLEX - the EXtended Version Of SIMPL
So I took SIMPL running on a LaunchPad, and added a 23K256 RAM chip with 6 jumper wires and a 10K resistor:
Overall View
I'm probably infringing a whole bunch of trademarks but the EXtended version of SIMPL which uses the EXternal SPI RAM will be called SIMPLEX.
Now that's what I call subtle! With a touch of irony.
With the RAM expansion comes the need to examine and modify its contents, and so I have written a bit of code to allow the contends of the RAM to be dumped to the screen in both decimal and hexadecimal formats, with ASCII equivalent in a separate column.
Whilst the SIMPL kernel code fits into 2Kbytes - and as such may be considered as a smart interactive bootloader, the high level routines to manipulate the RAM extend this limit quite considerably.
The code I have produced is "quick and dirty" C, and I am sure it could be written more succinctly at a later date.
The decimal-dump D and hex-dump H commands are the start of a new group of high level commands to handle external memory, editing etc.
30 or so years ago, "monitor" programs were common place on the early 8-bit micros. They allowed for the direct editing of data within the RAM space of the memory map - and were a means of entering programs - one hex byte at a time. It was a welcome step up from toggle switches!
The "Editor" will use the first 8 commands of the User Words, signified by letters A through to H, each representing a high level operation. One allocation of these is as follows:
A Assemble B Block C Compile D Decimal Dump E Edit F File G Go (execute from RAM) H Hex Dump
Several of these are really just place-holders for yet to be written command functionality.
The first task of being able to examine the RAM contents has been undertaken, now its time to start looking at the process of getting code into the RAM area and then executing it from RAM.
The 23K256 has a page size of 32 bytes, which is a useful size for a phrase of SIMPL code.
Looking at the Block B and File F commands above, the block command can be used to manipulate the memory 32 bytes at a time - effectively a line of SIMPL code, whilst the File command can be used for handling multiple blocks.
The hexadecimal conversion is used both for 2 digit (<= 255) and 4-digit (256 <= x <= 65535) conversions.
I have includes a SIMPL primitive $ which takes an integer x and converts it to either 2 digit or 4 digit hex.
The dump formats make use of the modern wider terminal screen. 1K of RAM can be dumped to a single screen - of 32 lines of 32 hex bytes.
The Hex -Dump as it appears on Termite Screen. 1K bytes of RAM data shown per screen
I have put the code for SIMPLEX_1 on this Github Gist Please note that the UART is running at a non-standard 100Kbaud instead of 115200. This is to be investigated later.
In the next post, I'll look at more RAM operations plus actually running SIMPL code out of the external SPI RAM.
Monday, March 07, 2016 SIMPLEX - Part 2 - Running SIMPL Code out of External RAM Running SIMPL Code out of External RAM
In part 1 I looked at the bulk access to the RAM chip using streaming mode - which takes about 3uS to access a byte. With single byte access, there is the significant overhead of setting up the read instruction and the 24 bit address - making an access about 100uS.
For this reason, I propose a block access mode which loads in a block of 32 bytes into the SIMPL input buffer and executes the code at full speed from there.
Reading in 32 bytes in streaming mode will take around 100uS and then the code will execute at full speed out of internal RAM.
Writing some Commands
A Assemble B Block Read C Compile D Decimal Dump E Execute (Read and Go combined) F File G Go H Hex Dump
We need a simple routine to load a block from RAM - based on the existing bulk read.
I use the B command to signify a Block Read - and it takes a integer block number and loads the block into a temporary internal RAM buffer called block_array[]
Once the data is in the block_array buffer, it's a simple case of pointing the interpreter at the start of that buffer and letting it execute the code.
To initiate this process, I use the G (Go) command.
The great thing about SIMPL is that the commands can be concatenated along a line so to load and run Block 0 you just need to type 0BG. You can then string these together so that multiple blocks are executed one after another 0BG1BG3BG2G etc
We could now dispense with the BG construct, and just call it E for Execute.
SIMPL has grown a lot today - and even as I author it, there's a lot of new information and excitement to take in. It's been a long but rewarding day getting the external RAM to work with SIMPL.
The latest code - with the ability to run code out of SRAM is on this github gist
In the next part, I look at data entry into the RAM and making a simple line editor.