Background
Forth is an interactive, low level language which shares a lot in common with machine code. It allows low level access to the processor and its resources and can therefore be quick and powerful - in the right hands.
It allows a degree of interaction which has now been lost in the higher level compiled languages, but for the right applications it provides all the flexibility needed.
The following videos illustrate some aspects of Forth when used for controlling hardware.
Open Firmware
It Was Twenty Years Ago Today.......
In the mid-1990s Chuck Moore, Jeff Fox and others worked towards forth computing engines that would achieve burst speeds of around 500MIPS.
Chuck Moore developed custom VLSI devices - a series of processors where the machine language instructions were essentially Forth primitives. These processors all used a minimal instruction set - and were known as MISC processors.
Dr C.H. Ting, had also shown with his eForth model, that a working Forth could be composed from just 31 Forth primitives, and that all other definitions could be assembled from this core set. Thus a processor with a 5 bit instruction length could potentially be used for Forth execution. Dr. Ting explored this further with a series of chip designs - where 5-bit instructions were packed into 16 bit or 32 bit words - allowing 3 or 6 instructions to be fetched from memory at a time, which better suited the slower RAM access.
Keeping the speed up...
When Forth is implemented on a register based load-store architecture- such as the ARM, the overheads of running the Forth inner interpreter - in particular NEXT, means that around 10 machine instructions need to be executed in order to execute a Forth primitive. This suggests that an ARM clocked at 100MHz will only achieve around 10MIPS.
Forth requires the right architecture in the processor in order to be able to execute the Forth primitives efficiently - preferably as single cycle instructions. The processor should have a stack-based architecture, and the machine instructions should be directly map-able to the Forth primitives for efficient executing. Using this approach allows a simple Forth processor to be designed as a soft-core cpu for a FPGA - and maintain a performance of around 50 to 100 million Forth instructions per second. (Forth MIPS).
Affordable FPGAs
Whilst much of this work was done about 20 years ago using custom VLSI chips, progressive improvements to FPGAs, falling memory prices and greater access to sophisticated design and simulation tools has allowed the creation of FPGA soft-core microcontrollers to be in the reach of the hobbyist. Low cost FPGA dev-boards are available for the $50 to $80 price range.
There have however been a number of stack machine cpu designs developed over recent years, several of which have been implemented on a low cost FPGA. Notably ZPUino - by Alvaro Lopez, and J1 - by James Bowman, although several others exist.
James Bowman's J1 design is of interest because it is close in architectural design to Chuck Moore's 1985 Novix NC4000, but much simpler because the data and return stacks are implemented in on-chip RAM. This gives it the potential for 100 Forth MIPS - when implemented in a Xilinx Spartan 3E - and described in under 200 (160) lines of Verilog code.
J1 is incorporated into the Gameduino Shield - a gaming - graphics and sound generator for Arduino. Versions are also available from Olimex - which include PS2 keyboard connector and additional 32MB SDRAM for extended resolution - although Olimex leave you high and dry when it comes to implementing firmware to make full use of the extra 32Mb!
https://www.olimex.com/Products/Modules/Video/MOD-VGA-32MB/open-source-hardware
The J1 Processor Model
The J1 processor is simple enough that it may be modelled in about 100 lines of C code. I used this model available from ddb's Github Repository
The J1 model is created from James Bowman's original documentation "J1: a small Forth CPU Core for FPGAs" and is very similar to the verilog code that defines the J1 implementation in hardware.
More documentation at James's J1 site . As can be seen, the J1 has been used in a variety of projects including the Gameduino shield - which is a graphics engine in the form of an Arduino shield.
The J1 has just 5 categories of instruction coded up into a 16 bit instruction word:
Literal a 15 bit literal pushed onto the data stack
Jump Jump to a 13 bit target address
Conditional Jump Jump if T is zero to a 13 bit target address
Call Call a subroutine at a 13 bit target address
ALU
The ALU uses a 4 bit field to determine the its action, and there are additional bit fields to control access to the stacks and memory.
T -> N Copy T to Next
R -> PC Put the return stack into the PC to get a free Return
N -> [T] Store Next at the location addressed by T
T -> R Copy T to Return stack
Additionally there are two, 2-bit, bit fields that allow for the increment and decrement of the data stack pointer, and the return stack pointer - this enables items placed further down the stack to be accessed.
Simulation
The instruction set of any proposed processor may be simulated in software. Once a model of the various stacks, registers and memory has been devised, it becomes a relatively straightforward task to create a C program, with text output, that simulates the operation of the cpu and instruction execution. Whilst the output of the simulator is either text or graphics, the process can be further developed to the point where any processor can emulate the instruction set of another - but with a vast speed penalty.
Fortunately the relatively simple J1 processor may be quite easily simulated in C - even using an Arduino.
The model consists of a 512 word memory (As an Arduino Uno only has 2K of on chip RAM)
Snippets of machine language are loaded into the RAM during the setup() function - for example
m[0] = 0x6000; // NOP
m[1] = 0x8020; // LIT 20
m[2] = 0x8010; // LIT 10
m[3] = 0x6400; // ADD
m[4] = 0x6700; // NEG
m[5] = 0x6000; // NOP
m[6] = 0x0001; // JMP 0001
In this trivial example two literals are loaded onto the stack, added together, negated and the whole process is repeated as an endless loop - by the unconditional jump back to the beginning. This is definitely not a particularly good example to illustrate Forth, but it's a good test case to show that the processor model is correctly fetching, decoding and executing code, and that the "alu" and pc are working properly together.
The information contained in the machine instructions contains the following
Numerical constants or literals. These are 15 bits packaged into a word that has bit 15 set - i.e. 0x8xxx in hexadecimal.
Target Addresses - there are signed 13 bit addresses, which are used to force the processor to branch to a new subroutine address or jump to a new address. The jump in unconditional, but the branch may be conditional - in that the top of the stack needs to equal zero for the branch to be executed. This gives the processor a branch range of +/- 8192 addresses.
ALU Instructions.
The ALU has 16 possible instructions as controlled by a 4-bit field. Instructions of the type 0x6X00 are alu - where the X is the 4 bit instruction.
Code is Code
It might be worth stating that the entire operation of the processor is controlled by the various fields coded within the instruction. This is what makes machine language very powerful, and yet very easy to make mistakes. A single mistake in a field might send your processor off into an unintended area of RAM, where it can misinterpret your stored data as a program, and then start indiscriminately writing to RAM. Invariable this ends up as a system crash.
As writing in machine code has always been a thankless task and prone to mistakes, it is best to spend time writing an assembler to help "assemble" programs from the processor's instruction set.
Assemblers use human readable mnemonics such as ADD, OR, JMP and allow numbers to be entered in decimal or hex. The assembler will use a text file which contains the source code, and which can be edited using a text editor. This can then be processed by the assembler to produce a binary or hex file that may then be loaded into the RAM of the processor.
Assembly language is the first layer of abstraction above the processor's own machine language. As a tool it makes programming simpler, faster and less prone to mistakes.
These tools first stared becoming available in the early-1980s. Early 8-bit home-micros often had an assembler/disassembler available as part of it's toolkit.
An excellent reference book on Assemblers by David Salomon.
Forth as an Assembly Language
In the early 1960's, Charles Moore - the creator of Forth, realised that there may be a better way of writing programs, than the traditional assembler or high level language compiler method.
He knew that any program consisted of small snippets of code, each performing some small function within the program. These functions and routines would be stitched together with calls and jumps to form the structure of the program.
He came up with the concept of the Forth word, where the word is the name of such a function - for example SQUARE.
Running on the processor was a small interpreter program, which could take the text input and compile it into executable machine code.
The word SQUARE could be written at the keyboard, or typed into a text file, and every time it was encountered it would perform the function of calculating the square of a number.
For this to work, SQUARE had to be created using the colon definition method of defining new words - which is written like this:
: SQUARE DUP * ;
: This colon is the word that tells the interpreter that this is a new definition
SQUARE this is the name of our new word, and that will be put into the dictionary
DUP is a forth word that duplicates the top word on the stack
* multiplies the top two entries on the stack, leaving the product on the stack
; Semi-colon - this denotes the end of the definition and a return to the inner interpreter
For a much fuller explanation of how this works - have a Read of Brad Rodriguez' excellent article "Moving Forth"
Suffice to say, that the Forth system provides the assembly, compilation and run-time execution environment needed for a self contained system, and it does it in a user interactive manner.
This video shows a typical Forth work session.
N.I.G.E Machine
In another post, I describe my project to combine a simulation of the J1 Processor with a set of simple graphical tools to allow assembly, disassembly and memory viewing.
---------------Getting along in the 21st Century with half the baggage you carried in the last.------------ /*************************Low cost electronic solutions for a low impact lifestyle.************************/
Sunday, September 06, 2015
A Graphical User Interface for Low Level Hacking
![]() |
| Disassember Window |
So far, this consists of a memory view, a register view, stacks and a disassembler window. The windows into memory are animated such that the actions of the instruction set on memory and registers may be viewed whilst single-stepping through the code.
The novel thing about this simple application, is that it has been written in Arduino C++ code, and once compiled, it runs on a ZPUino softcore processor hosted on a FPGA. Additionally, the hardware which generates the 800x600 VGA display is also hosted on the FPGA. So we have a complete computer system consisting of cpu, memory and video generation hardware supplied on the Papilio Duo FPGA board.
The first part of this exercise was to get the graphical parts of the user interface working. These consist of the hex memory dump window and the various stack, registers and disassemnler windows.
Now, whilst the ZPUino is itself a stack based processor, and these tools will eventually be used to examine it's operation, it was decided that initially I would use the ZPUino to emulate an even simpler stack processor. The candidate is James Bowman's J1 Forth Processor (also available as a softcore for FPGA use) - which has the advantage of a very small instruction set, and a processor behaviour that is easily modelled in C code.
This may appear a somewhat round-about route but was chosen for the following reasons:
1. The ZPUino can be programmed in "Arduino code" using DesignLab - the Papilio Duo IDE
2. The ZPUino interfaces in hardware to the 800x600 VGA engine
3. Adafruit's GFX graphics library has been ported to ZPUino
4. A compact C model, and sufficient documentation exist for the J1 processor
5. I wanted to understand how the J1 works, and what it's limitations are
6. This is a programming project that meets my elementary coding skills
So my approach is to make use of the tools available. James Bowman is working on an implementation of the J1 to run specifically on the Papillio Duo board, and make use of its 2Mbyte of SRAM. Whether he will develop it to the point where a VGA engine is supported is unknown - so for the moment I have to be content emulating the J1 with the ZPUino in C, with the heavy burden of the GFX library calls.
If we can develop sufficient momentum, then there might be a srong case to put a fast Forth soft core on a FPGA with VGA. This however is beyond my coding skills - but on my wish list for the future.
Disassembler Window
This does a very simple disassembly on the instructions in memory. The jump, branch, call and ALU instructions are decode to their mnemonics for easier reading. The animated display shows the instructions highlighted in cyan as they are executed by the processor emulator.
More Interaction
So far only the graphical code has been prototyped - just enough to see the animation of the J1 processor emulation. For complete user interaction, it will require more code, in particular that to support keyboard, mouse and a text editor window.
I have ordered a Classic Computing shield for the Papilio Duo from Gadget Factory in Denver. This includes sockets for PS2 keyboard and mouse, VGA output, microSD card and a pair of Atari style joystick connectors. This will allow keyboard and mouse interaction to be developed, plus program and data storage on the microSD card. The thought had occurred to me that the Atari ports might be useful to accept switch presses from some form of custom keypad - a bit like Chuck Moore uses with his OKAD and colorForth environment.
Text Editor
The existing graphical layout allows for a text window of about 90 character columns by 75 rows. This should be sufficient for 80 column mode plus a few clickable buttons. The mouse will be used extensively for click and drag type operations - so a routine that links mouse position to the position of objects on the screen will be central to the user interaction.
As most coding languages are text based - the efficient manipulation of text leads to high productivity whilst programming. The use of colour text and highlighting of selected areas will enhance the user experience. The text window will additionally be used for serial output and command line input, and the use of the microSD card will allow source code to be saved and retrieved from "disk".
Assembler and Compiler
The J1 is a "Forth" processor, in as much that it is stack based, and almost all of it's instructions are Forth primitives. This allows it to execute the Forth language efficiently. However, a modern Forth consists of about 200 definitions, and these have to be encoded in the native instruction set of the processor. Fortunately, this is something that Bowman, and others have already done.
Extending SIMPL
In the earlier post "Building form the ground up" I wrote about how Forth could be used to provide a low level development environment for an unfamiliar processor for which a C compiler was either not available, or not desirable to use.
The first task is to write a simple virtual machine for the target processor, and then use this VM to run your application code. This is similar to what Java bytecode does.
The virtual machine need only have a handful of instructions, including basic arithmetic, logical operations and the ability to access and manipulate memory. From these primitive instructions, all subsequent instructions may be synthesised.
This is the approach described in "The Elements of Computer Systems" (TECS) which is also known as "From Nand to Tetris". The simple machine described, consists of little more than an ALU, a program counter, two registers and a memory interface capable of accessing a 64K x 16 bit address space.
Designing a Virtual Machine
If it is possible to code up a simple virtual machine, on any choice of microcontroller, or softcore CPU FPGA - then it becomes practical to program the virtual machine using the same machine language.
The virtual machine will be a stack machine, and will support a data stack and a return stack. These stack structures will probably be created in RAM on the virtual machine. If this was then implemented in FPGA hardware, the stacks would be separate RAM blocks, with a means of fast access, without having to go through main memory.
The ALU has access to the top and second items of the stack, and will conduct arithmetic and logical operations on these elements, leaving the result on the top of the stack. If operands are required from memory, they will first have to be loaded into the top and 2nd stack locations.
Assume that the virtual machine ALU can perform the following operations. The arithmetic and logical operations are performed on the top 2 members of the data stack, returning the result to the top.
ADD
SUB
MUL
DIV
Multiply and Divide can be synthesised from shift and add/sub - but are time consuming without additional specialist hardware.
AND Bitwise AND
OR
XOR
NEG
SLL Shift Left Logical
SRL Shift Right Logical
@ Fetch a word from memory and place on the top of stack
! Store a word from the top of stack to memory
BRZ Branch if zero
JMP Unconditional Jump
CALL Call subroutine
RET Return from subroutine
LIT Put a literal number onto the stack
So with approximately 20 instructions, we have the basis of a stack machine that can do useful work.
The virtual machine to perform these operations can be written in a high level language - such as C, or actually implemented as a soft core on a FPGA. One such stack processor that lends itself to this is James Bowman's J1 Forth CPU. This compact, no thrills CPU can be defined in under 100 lines of C, or synthesised in FPGA hardware using under 200 lines of Verilog code.
The J1 is a practical CPU, designed for simplicity and optimised for high speed execution of stack based languages. It offers most of the instructions outlined above and forms the basis of an exploration into stack based CPUs. Initially it can be simulated on any processor in C code for experimentation and later blown into real high speed FPGA logic.
Even though the instruction set is very small, the 16 bit instruction word length does not lend itself to easy or memorable coding in machine language. It has several instruction fields, and these have to be populated with the correct bit pattern if we are to make any progress off the starting blocks. The instructions to however map very well onto the Forth language, but there are other alternatives which could be explored.
At the bare minimum, we need an assembler to synthesise the instruction words from the various fields, and once we have a list of 16bit hex instructions we need to load them into RAM and have the simulator step through them.
An assembler typically scans through a text file containing instruction mnemonics, such as ADD, JMP, CALL etc and converts these into the instruction opcodes. It also looks for numerical constants, variables and addresses and assembles these into the instruction. Additionally, it looks for labels that identify subroutine addresses for jumps and includes these in the code.
A relatively simple program: Mnemonics in - machine language out
Another Option
However there might be a different way to do this - in a more interactive nature - and this is where Forth or one of it's near cousins will come in. For the purpose of my exploration, I want to see if the SIMPL interpreter can be used as a means to perform this assembly step.
As we know, the SIMPL interpreter will read a series of characters from a buffer, one at a time, and execute code associated with that character.
So to add 2 numbers (say 45 and 63) in SIMPL and print out their sum
45 63+p
45 is interpreted as a literal to be pushed onto the stack
The space is used in SIMPL to push the stack down
63 can then be pushed onto the stack
+ adds the top two members of the stack leaving the result on the top
p prints the result to the serial terminal
This is almost Forth, except in SIMPL there is only a limited stack structure and the space is needed to command the stack to push down to accept another number.
Instead of executing the SIMPL instructions directly, we can hijack the SIMPL interpreter to synthesise the assembly language and the machine language needed for the virtual machine.
So 45 63+p is translated to assembly language
LIT 45
LIT 63
ADD
CALL PRINT
Where PRINT is a subroutine that outputs the top of stack contents as a printed integer to the serial port
But the translation to standard traditional assembly language with 3 letter mnemonics is an un-required middle step. The SIMPL interpreter can easily produce the instruction fields and generate the machine language directly:
802D LIT 45
803F LIT 63
6200 ADD
5100 CALL 100 (PRINT is at 0x0100)
So by this process of translation, the SIMPL language is the Assembly Language - we can find enough of the SIMPL character set to map directly onto the J1 instruction set, and any of the other command characters (like p) will invoke calls to subroutines.
It might be remembered that SIMPL uses small letters and punctuation characters as primitives, numbers are enumerated as literals and capitals are reserved for the application words. This means that our little language can have approximately 60 primitive instructions, which is enough to do real work, yet takes up a fraction of the space used by the 170 words used in a typical Forth system. Less words, less typing, yet still more readable than assembly language or machine code.
So lets look at the primitive words and how it might map onto the assembly language
+ ADD
- SUB
* MUL
/ DIV
% MOD
& AND
| OR
^ XOR
~ INV
# LIT
@ FETCH
! STORE
: CALL
; RET
< LT
= EQ
> GT
j JMP
z JPZ
I find Stack manipulations are never easy to remember in Forth - words like DUP, OVER, SWAP, NIP, DROP etc but as these are an essential part of the language, they need to have a syntax to code them into the assembly language. Perhaps it might be possible to express the top two stack items as a two member array between parenthesis.
DUP (1,1)
OVER (2,1)
SWAP (2,1)
NIP (x,y)
DROP (2,3)
Text Editor and Assembler
In order to start writing code for our new processor, we need a few simple tools to help us. We need a means of entering and displaying text - usually a serial terminal interface, so that we can enter machine instructions into memory and have the virtual machine execute them.
In the early days of microprocessors development kits there was often a hexadecimal keypad, 7 segment display for address and data, and a monitor program. This allowed the machine instructions to be entered directly into memory, and then the means to run code from a certain address. It was quite primitive, frustrating and subject to a lot of human typing mistakes. Nowadays, we can use the power and resources of a laptop to help get new systems up and running.
The first tool we need is a simple text editor. This will take in text from the keyboard, display it in a terminal window and allow basic editing, listing and text file storage and retrieval.
Secondly, no-one wants to code in machine language, so a very basic assembler that converts text mnemonics and numbers - one a line by line basis - to machine language would also be an asset.
For this we need simple text parsing - and in traditional Forth this was done by looking for individual words or numbers separated by spaces.
Forth would take each new word and look it up in the dictionary for a match. The match was based on the first three characters of the word, and it's length. This is quick to do and suitable for most purposes.
Numerical input, which includes integers up to 65535 were generally not stored in the dictionary, and would be converted from ASCII to integer and then placed on the stack.
The text editor and assembler can exist as one program - as they share a lot of features. Principally we will need the means to parse through the entered text looking for keywords and numbers. As there are only 20 or so keywords required to implement the instruction set of the virtual machine, the task of programming these into the assembler is not too difficult.
I have chosen mnemonics that simplify this task - the first 2 characters are unique to each mnemonic, and no mnemonic is more than 4 characters long. We can combine the first two characters to produce a unique number, and then use this number in a series of Switch-Case statements to perform the action needed.
The 16 bit virtual machine can handle integer numbers up to 65535. We need a means of detecting a number within the entered text string, and converting the ASCII characters to an integer. In a similar way to how we uniquely defined the mnemonics by the first 2 characters, we can do a quick test on the string to see if it is a number.
The assembler will convert our inputed mnemonics on a one by one basis into the machine instructions of the virtual machine. More detail on how the assembler should operate is outlined in Chapter 6 of "TECS".
Sometimes it is easier working in binary or hexadecimal, so additional assembler directives, for example BIN, HEX and DEC, could be used to instruct the assembler which base to use to interpret the numerical strings.
Assemblers make use of other directives such as ORG, and labels, to refer to points in the listing. Assemblers can be single pass or two-pass. A single pass assembler will require you to keep track of your own labels, which can be quite difficult if the assembly listing is rich in subroutines. So this is possibly one reason why Forth evolved as a language, it has it's roots in assembly language programming, but the Forth system of "words", provided an efficient and automated means of keeping track of labels and subroutines - it had to, as Forth is composed almost entirely of subroutines.
Charles Moore, created Forth to be an efficient and automated way of creating a common programming environment on each of the wide variety of mainframe machines that he encountered during the 1960s-70s. His virtual machine had to be first coded in the native machine language of the processor, but with the availability of C compilers, the VM can be coded in C.
Moore realised that the tasks of text editor, assembler, compiler and interactive interpreter could be bundled up into one efficient package, which he called Forth. How exactly this was done was at first fairly obscure, and Moore initially kept much of it to himself, before branching out around 1970 and sharing the inner secrets of Forth within the Radio Astronomy community.
If the primitive assembler can only accept valid mnemonics and numbers, then any other unrecognised text string could be considered to be a new word. A word that cannot be found in the dictionary, is treated as a new definition and is composed from the primitive instructions.
This is similar to the use of a macro label within a (two pass) assembler listing. Once a macro has been encountered and given an address, it can be used again.
So the combination of a simple text editor and line assembler will help us to build up the various Forth word definitions from the primitives. Whilst this C program is not a complete Forth system, it is a tool that helps us create the Forth system.
Saturday, September 05, 2015
Building from the Ground Up
In my previous post which turned out to be a rant about the ever increasing complexity of software, I decided to dig out a draft post from earlier this year which describes my continuing investigation into how the lower levels of computing languages are implemented.
The purpose is to create a set of low level tools which allow application code to be developed easily and interactively on a microprocessor or soft CPU with limited memory resources.
The microprocessor may be an ARM or a softcore running on a FPGA - and with no C compiler available how do you start to bootstrap the processor from first principles?
Booting from Scratch
In bygone generations of computer hardware, there would be a set of toggle switches which could be set to represent the binary instruction words. These words would be individually deposited into memory and the program counter advanced. A very short routine, consisting of only a couple of dozen instructions would be manually toggled into memory, allowing a paper tape to be loaded. Great ingenuity was applied to the hardware architecture so that these loader routines were short.
Daniel Bailey has devised a fun project - his C88 computer is a home-brew CPU on a FPGA which takes one back to the very early methods of booting a cpu from scratch. This blogpost and video explains it nicely. Daniel will be presenting his C88 at the forthcoming OSHcamp- at the end of September in Hebden Bridge.
As technoogy progressed, and IC memories became available, interchangeable eproms were used to allow the program code to be quickly modified and re-run. However there might be a 20 minute delay between detecting a bug and reprogramming another eprom with the corrected code. To speed up the time needed to program and erase eproms - often a nonvolatile RAM,was used to emulate the eprom and hold the program code. I spent a summer in my late teens programming a Z80 dev board in this manner.
These days almost all microcontrollers have on chip flash memory, and some method for in circuit serial programming. (ICSP). As a PC or laptop is invariably used for program development and code compilation, virtually all of the development tools are hosted on the PC, and very few systems have the means to edit and recompile code on the target system itself.
There has to be another way
There is however another means of working, where a minimal interactive working environment can be loaded onto the target system, and this allows the development and debugging of programs on the target system itself. Very little additional support is needed other than a serial interface. The code can be developed in a text editor running on the microcontroller. This is no different to the way that interactive languages, such as BASIC were developed on home computers in the early to mid 1980s.
Interactive development is a completely different method of working compared to the usual edit, compile, load, test approach that has arisen out of the almost universal use of compiled languages - in particular C and its derivatives. It was only when PCs gained more RAM, disks and cpu speed that C compilation became practical.
Forth was one of the first interactive languages, - developed in the 1960s by Charles H. Moore, and it is Forth that influences my investigations here.
Forth might be compared to assembly language, as it deals with low level operations involving snippets of machine language that are threaded together to create some program function. However it is much more than just an assembly language, as it provides the means to edit, compile and assemble source code, in an extensible manner, using a very compact language.
Forth does away with much of the clutter of other languages, and gives the programmer direct access to the resources of the processor. Forth offers high speed execution, especially on FPGA hardware designed to specifically match the primitive instruction set of the Forth language. Modern, low cost FPGAs can run a Forth engine at a clock frequency of some 50 to 200MHz. At this speed the interactive nature of the language becomes extremely fast, and the time taken to go around the edit-compile-exexute process is slashed to just edit-execute. This is a significant saving in time, and ideas can be tested and rejected in the time otherwise spent compiling a large application.
Forth uses "words" to perform program functions. A Forth word ultimately causes a series of machine language subroutines to be executed. In some respect - a Forth word may be likened to a LEGO block, which can be used with other blocks to make a more complicated structure. These structures may be further combined to build up the entire object - in our analogy - the program application.
Forth words are threaded together, like beads on a string, with the end of execution of one word, rapidly jumping to the beginning of the next.
Brad Rodriguez has an excellent article "Moving Forth" which explains how this threading process is achieved. Although written over 20 years ago - the fundamentals have not changed.
SIMPL
In an attempt to understand the fundamentals of Forth, I studied another threaded, interpreted language, SIMPL - the Serial Interpreted Minimal Programming Language. I have blogged several times about SIMPL since May 2013 - when I first came across it. Refer back to previous posts for details.
SIMPL takes some aspects of Forth, and packages them in an easy to understand manner which may be adapted to run on a variety of microprocessor platforms. I first used SIMPL on a ATmega328 Arduino, but have subsequently ported it to ARM and FPGA soft core processor targets. SIMPL is written in more or less standard C, which makes it portable between, processors, without the complexity of dealing with the machine language of each target processor. It is a stepping stone towards a real Forth.
SIMPL provides an easy way of sequencing blocks of code functions, and doing it in an interactive manner from the serial keyboard interface. It's not so much a programming language - more a way of automating the access to routines - and done in an interactive manner.
As an example:
Suppose you have just written a function in C to plot a graphical character on the screen, and you wish see what it looks like - using a VGA graphics adaptor or a TFT LCD screen. In order to test this function, you need to supply it with parameters for the x,y position that you wish it to be plotted, and possibly the foreground and background colours. If you hardcoded these parameters, and got them wrong, then you would have to go back and edit and recompile until you got the effect you were looking for.
SIMPL provides the mechanism to enter these parameters and execute the function interactively. If you don't like the first result, you can change the parameters with a few key-strokes and test again. You have virtually eliminated the edit-recompile cycle from when you are developing new code functions.
The Mechanics of SIMPL
SIMPL exists as three short functions that provide a complete serial interpreter or shell, to accompany the rest of your program. By calling the SIMPL interpreter each time the main loop is executed provides the means to interact with the rest of the program.
The SIMPL interpreter consists of the following 3 functions executed sequentially within a loop.
txtRead() takes characters from the serial input and loads them into a buffer beginning at address buf - which has been allocated a length of 64 characters
txtChk() looks at the first character to see if it is a colon : If so it copies the input text string to a specific address - to form a "colon definition", an idea borrowed from Forth
txtEval(addr) This is the interpreter - It is pointed to the start address of the text string and evaluates the string a character at a time. The SIMPL interpreter has a few rules on how it treats each character
If it finds numerical characters, it enumerates them to a 16bit integer that it places on the stack.
If the characters are small letters or punctuation characters it will execute a given function each time that character is encountered. For example, you may have allocated the character "g" to plot out your new graphic symbol, each time g is encountered.
Uppercase characters are used as addressing pointers - to point to additional character strings, either in Flash or RAM. The colon definition allows you to compose a new sequence of characters, and access it every time the uppercase character is typed.
Because the text is always loaded into a buffer - it is executed at full speed - and not influenced by the serial baudrate.
In short, SIMPL provides an easy interactive means to call your code subroutines (functions) in a sequence from the keyboard, and provide serial printed output back to the serial terminal.
SIMPL is essentially providing a subroutine address lookup, and call to that subroutine, encoded into the ASCII value of a character. Sequences of characters provide sequences of function calls. Numerical parameters may be passed to those subroutines using an elementary stack based method.
Extending SIMPL
SIMPL is not a fully blown language, but a method of automating the calling of functions according to a stored sequence of characters or tokens. It treats every ASCII character as a new instruction, so you cannot use multiple character words such as ADD to convey a meaning - as this would be interpreted as sequence A followed by sequence D followed by sequence D and so on. This is where it deviates from Forth.
It's control structures are limited to simple loops - controlled by a single down counting loop counter.
SIMPL is the stringing together of subroutines in Flash, that have been created from compiled C code. A 16 bit ADD in SIMPL is going to be somewhat slower than the same operation in a directly executed subroutine.
SIMPL does provide some pointers to how a more Forth like version could be implemented.
It already has the means to interpret an integer number and place it on a stack.
It also has the means to take a sequence of tokens - in this case ASCII characters, look them up in a jump table and retrieve the start address of a code subroutine, which it then executes, before returning to the interpreter to decode the next token. Each 7-bit token provides an index into a jump table of addresses, whom where the next word is executed.
To extend SIMPL, it will be necessary to create some additional text handling code, so that typed words can be processed, added to a dictionary and have a codefield associated with them. How exactly this will be achieved will be the subject of a future post.
Simple Machines
This is a follow on from yesterday's post, where I described some of the cpu technology I currently deal with and how it would be great if there was a common language that would run on them all.
I am currently working with STM32Fxxx Cortex M3 M4 and M7 ARM devices, having designed half a dozen pcbs based around them in the last couple of years. I have also worked with ATmega parts - mostly derivatives of Arduino and now I am branching out into FPGA softcore CPUs.
I am not a natural or native software engineer, and I feel the need to simplify the processes to the point where I understand what is going on and I am in total control of the device. This low level approach rather constrains the scope of what I can achieve, but it gives me the satisfaction of understanding the whole picture. This approach has led me into the territory of baremetal programming - something that I am slowly starting to get a taste for.
To make life easier, we surround ourselves with familiar useful objects and tools. As we become accustomed to these new things, learn how to use them efficiently, they improve the quality of our output and enrich our (working) lives. It's been the same for the last 50 years, since when computers first started to appear in quantity.
But more computers doesn't always mean better, I have about 7 within arms reach, and one in my pocket. Fortunately 6 are switched off, and the one in my pocket has not disturbed me for at least 30 minutes. There's the laptop I am writing this on, that I bought about 5 years ago and takes 5 minutes to boot, and the Android in my pocket which I use for making calls and sending texts. Most of my interactions with modern operating systems is solely as a user of pre-packaged applications, the inner workings I know nothing about, and probably don't have the time to care.
I must confess I don't know how to drive a Linux machine through it's command line, I only powered a Raspberry Pi for the first time in April this year and I am totally lost on a MAC. To make things worse, I have no idea why my unbranded Android keeps popping up text box warnings in Chinese!
So - as a dinosaur of the digital age, I will stick to what I know and remain in my comfort zone - which is as close to the bare metal as possible.
Most microcontrollers are programmed in C or one of it's close cousins, with the language tools normally residing on a much more powerful machine, such as a laptop - with whatever flavour of operating system suits the user. As confessed above, I have grown up with Windows, as have most of the software tools I use in my day to day work and play. It's taken me several years to master one pcb design package, so why should I struggle like an infant, trying to learn another - just because it's the flavour of the month. My "muscle memories" are tuned to driving EagleCAD, so when out of interest I tried KiCAD, I found it one of the most frustrating, unproductive 2 hours of my adult life. I am beginning to think what they say about old dogs and new tricks, is not only true, but just a polite way of saying "move over, Grandad, you had your chance".
So this is increasingly why, tech people of my generation, cling to the foundations - and avoid climbing the towers of Babylon that have been built, every increasingly skyward, on top of them.
This is probably not what I intended to write this time - but I feel much better for getting it off my chest.
I am currently working with STM32Fxxx Cortex M3 M4 and M7 ARM devices, having designed half a dozen pcbs based around them in the last couple of years. I have also worked with ATmega parts - mostly derivatives of Arduino and now I am branching out into FPGA softcore CPUs.
I am not a natural or native software engineer, and I feel the need to simplify the processes to the point where I understand what is going on and I am in total control of the device. This low level approach rather constrains the scope of what I can achieve, but it gives me the satisfaction of understanding the whole picture. This approach has led me into the territory of baremetal programming - something that I am slowly starting to get a taste for.
To make life easier, we surround ourselves with familiar useful objects and tools. As we become accustomed to these new things, learn how to use them efficiently, they improve the quality of our output and enrich our (working) lives. It's been the same for the last 50 years, since when computers first started to appear in quantity.
But more computers doesn't always mean better, I have about 7 within arms reach, and one in my pocket. Fortunately 6 are switched off, and the one in my pocket has not disturbed me for at least 30 minutes. There's the laptop I am writing this on, that I bought about 5 years ago and takes 5 minutes to boot, and the Android in my pocket which I use for making calls and sending texts. Most of my interactions with modern operating systems is solely as a user of pre-packaged applications, the inner workings I know nothing about, and probably don't have the time to care.
I must confess I don't know how to drive a Linux machine through it's command line, I only powered a Raspberry Pi for the first time in April this year and I am totally lost on a MAC. To make things worse, I have no idea why my unbranded Android keeps popping up text box warnings in Chinese!
So - as a dinosaur of the digital age, I will stick to what I know and remain in my comfort zone - which is as close to the bare metal as possible.
Most microcontrollers are programmed in C or one of it's close cousins, with the language tools normally residing on a much more powerful machine, such as a laptop - with whatever flavour of operating system suits the user. As confessed above, I have grown up with Windows, as have most of the software tools I use in my day to day work and play. It's taken me several years to master one pcb design package, so why should I struggle like an infant, trying to learn another - just because it's the flavour of the month. My "muscle memories" are tuned to driving EagleCAD, so when out of interest I tried KiCAD, I found it one of the most frustrating, unproductive 2 hours of my adult life. I am beginning to think what they say about old dogs and new tricks, is not only true, but just a polite way of saying "move over, Grandad, you had your chance".
So this is increasingly why, tech people of my generation, cling to the foundations - and avoid climbing the towers of Babylon that have been built, every increasingly skyward, on top of them.
This is probably not what I intended to write this time - but I feel much better for getting it off my chest.
Friday, September 04, 2015
If you've got a problem .....
If you've got a problem, don't care what it is
If you need a hand, I can assure you this
I can help, I've got two strong arms, I can help
It would sure do me good to do you good
Let me help
Here is his unpublished book retyped some years ago into HTML, which again today I came across, this time on the Raspberry Alpha Omega blog of Frank Carver.
Frank is clearly an experienced and talented software engineer, and understands the inner workings of computer software in ways that I just struggle to grasp. So it was a pleasant surprise to find that Frank and I have been following virtually parallel journeys for the last couple of years, he from a software perspective - and myself from a hardware perspective.
This post is not specifically about Problem Oriented Languages, but more how they are still relevant today and can be applied to a range of fields of computing science.
A Problem Aired....
My immediate problem is that I am now working with a range of microcontrollers, both AVRs and ARMs of several different flavours and I need to find some common ground between them, and establish a comfortable development environment - founded on mutual territory. Throw into the mix, some stack-based soft cores running on FPGAs, and the chance of finding my Nirvana rapidly fades into dust.
All of these processors fit into the 20MHz to 200MHz clock speed, and really don't have enough memory resources to support an operating system like Linux. Some of the larger parts can be programmed in MicroPython or JavaScript but that's not much use for the soft cores or the smaller parts.
I wondered for a while whether Arduino might become the lingua franca, at least for "hobby" projects - because as well as the ATmega, it has been implemented on the STM32F ARM M3 and M4 parts and also the ZPUino soft core - hosted on the Spartan 6 of the Gadget Factory Papilio Duo.
So for the moment, you have a range of different microcontrollers, with which you can share Arduino sketches and libraries.
A word about FPGAs and Soft Core CPUs
In the last few years, FPGAs have become commonplace, and the toolchains needed to develop applications on them, have become free to use. Several tech suppliers are offering low cost dev-boards based around a small FPGA, with sufficient hardware support, to allow programming via serial or JTAG, plus support chips - such as external SRAM, SDRAM and configuration flash.
So far my journey has taken me to the Xilinx Spartan 6 - as there are several hobby-boards based around this device. Plus this part appears to have a lot of support from the emerging FPGA community.
Jack Gasset and his team at Gadget Factory have democratised the FPGA, in a similar way to how the Arduino Team democratised the ATmega and C++.
By porting an open source soft core 32bit CPU, plus a library of other cool hardware resource libraries - such as sound chips and music synthesisers, you can now make your own hardware designs relatively easily and control it all with the ZPUino softcore - executing Arduino sketches at 100MHz.
The great thing about the ZPUino FPGA soft core for projects, is that there is a hardware VGA generator plus the Adafruit graphics library available which can support 800x600 resolution VGA. You just plug in a VGA monitor, and you can draw graphics to your heart's content - all in a few lines of Arduino code. This is a super-quick Arduino, with colourful grahic output that you are totally in control of. Other libraries allow you to add a PS2 keyboard and mouse - you have the makings of a complete development environment on an FPGA. It's the computing equivalent of an early 1990s workstation - but unconstrained by any operating system - effectively a blank canvas onto which you paint your computing dreams!
If you want to look further - this was built using a Papilio Duo FPGA board fitted with a Computing Shield. If you want to go this route, make sure you buy the Papilio Duo with the 2MB SRAM - as the cheaper 512KB part will severely limit your graphics play.
So far, more interesting options - and no one solution. And also, the allure of FPGA soft core processors was becoming a great distraction.
J1 - A Forth CPU
Almost exactly 3 years ago to the week, I was in New York for the Open Hardware Summit. One speaker was James Bowman, who introduced us to GameDuino - a bolt on video system for an Arduino. In th form of a shield, with VGA and audio connectors - it could handle the whole video graphics - based on a neat Forth processor, that James had designed - and known as the J1. James had developed the J1 for a robotic video system based on a Xilinx Spartan 3E FPGA, which has more than enough grunt to handle the sprites, backgrounds and tone generators of a typical 1980s arcade video game.
The original J1, presented at EuroForth 2010 is descrbed here.http://www.excamera.com/files/j1.pdf
and further links to the J1 and GameDuino are here.
James has since ported it to the Spartan 6, made a few demon tweaks, and it can now run on the Papilio boards. The J1 can be instantiated as either a 16 bit or a 32 bit processor. Clock speeds approachin 100MHz are achievable.
In addition to developing the J1 hardware, James has created a version of Forth to run on it known as SwapForth, and has leveraged some open source FPGA tools to create an open core processor, running open source software - developed with open source tools. This video gives a quick demo.
I am still very much digesting the last 3 years on posts on Frank's blogsite. The next post here will try to make sense of it all.
Sunday, August 23, 2015
Simple Imaging using the Papilio Duo FPGA Board
This is a work in progress - have a look later for any updates
Introduction
Earlier this year I bought a Papilio Duo FPGA board from Gadget Factory. It has the combination of a FPGA and Arduino on the same pcb.
This board uses a Xilinx Spartan-6 closely connected to a 2Mbyte SRAM. This combination allows the FPGA to be used for generating VGA video - currently with a resolution of 800 x 600 pixels at 60Hz.
The killer feature of the Papilio Duo is that it will support the ZPUino - a 100MHz soft core which can be programmed using the Arduino IDE. This allows fairly rapid development of Arduino sketches - with the advantage of a fully accessible RAM block which can be used for frame buffers or other data storage.
In addition, the ZPUino will run the Adafruit GFX Graphics library. This is a generic graphics library for a number of different display types. When used with the ZPUino VGA it allows RGB 5:6:5 data for the 800 x 600 display. It has basic pixel plotting, line and circle drawing and fill commands - as well as various fonts and colours for on-screen text.
The ZPUino is fast enough to update the video buffer in about 1 second - this is fast enough for displaying captured video stills.
The combination of the above components creates a very basic but accessible Imaging Platform - which can be rapidly coded to perform. Whilst at first glance it might appear to be 25 year retro-step backwards in terms of computer graphics capailities, it offers an easy hackable platform, without all the constraints of a modern PC or operating system.
A Blast From the Past
30 years ago, in 1985, as my university final year project, I built up some hardware to allow the images from a scanning electron microscope (SEM) to be captured on an early x86 PC. Years later, a friend of mine who is a member of the Open Source Hardware Users Group, OSHUG, has acquired second hand, a scanning electron microscope dating from that era.
The SEM in question is a Cambridge Instruments Stereoscan 250 dating from 1985. It is in good condition, but lacks any means to capture images digitally, so is an ideal candidate to upgrade with a vision system - loosely based on my degree dissertation.
Of course, digital electronics has moved forwards inexorably since 1995, both in terms of speed of operation and RAM density - such that hardware costs in real terms is less than 100th of the price it was 30 years ago.
This makes it extremely viable to produce a complete imaging system using readily available open source hardware.
Some Design Aims and Objectives
Fundamentally this should be an open hardware project - reproducible by anyone using off the shelf hardware.
It will have an educational theme - allowing the user the experience of video systems, FPGAs and modern embedded mirocontrollers.
It will be extendable, and hopefully portable to other hardware - for example Raspberry Pi.
Some Specs
The SEM has an absolute scanning resolution of about 4096 x 4096 8 bit monochrome pixels. A full high-res image would therefore occupy 16MB of storage.
This resolution is not displayable on any monitor, so the compromise is to allow a smaller window view into the larger scanned field of view.
512x512 pixels is a convenient size for the available VGA system, so it would be possible to display a small window of just 1/64th of the whole field. When displayed on a 800 x 600 VGA monitor - this would allow adequate space around the image for text buttons, controls and tool icons.
It would be possible to extend this window to either (720x576) for 4:3 broadcast TV, or 800x600 for full screen display.
Introduction
Earlier this year I bought a Papilio Duo FPGA board from Gadget Factory. It has the combination of a FPGA and Arduino on the same pcb.
This board uses a Xilinx Spartan-6 closely connected to a 2Mbyte SRAM. This combination allows the FPGA to be used for generating VGA video - currently with a resolution of 800 x 600 pixels at 60Hz.
The killer feature of the Papilio Duo is that it will support the ZPUino - a 100MHz soft core which can be programmed using the Arduino IDE. This allows fairly rapid development of Arduino sketches - with the advantage of a fully accessible RAM block which can be used for frame buffers or other data storage.
In addition, the ZPUino will run the Adafruit GFX Graphics library. This is a generic graphics library for a number of different display types. When used with the ZPUino VGA it allows RGB 5:6:5 data for the 800 x 600 display. It has basic pixel plotting, line and circle drawing and fill commands - as well as various fonts and colours for on-screen text.
The ZPUino is fast enough to update the video buffer in about 1 second - this is fast enough for displaying captured video stills.
The combination of the above components creates a very basic but accessible Imaging Platform - which can be rapidly coded to perform. Whilst at first glance it might appear to be 25 year retro-step backwards in terms of computer graphics capailities, it offers an easy hackable platform, without all the constraints of a modern PC or operating system.
A Blast From the Past
30 years ago, in 1985, as my university final year project, I built up some hardware to allow the images from a scanning electron microscope (SEM) to be captured on an early x86 PC. Years later, a friend of mine who is a member of the Open Source Hardware Users Group, OSHUG, has acquired second hand, a scanning electron microscope dating from that era.
The SEM in question is a Cambridge Instruments Stereoscan 250 dating from 1985. It is in good condition, but lacks any means to capture images digitally, so is an ideal candidate to upgrade with a vision system - loosely based on my degree dissertation.
Of course, digital electronics has moved forwards inexorably since 1995, both in terms of speed of operation and RAM density - such that hardware costs in real terms is less than 100th of the price it was 30 years ago.
This makes it extremely viable to produce a complete imaging system using readily available open source hardware.
Some Design Aims and Objectives
Fundamentally this should be an open hardware project - reproducible by anyone using off the shelf hardware.
It will have an educational theme - allowing the user the experience of video systems, FPGAs and modern embedded mirocontrollers.
It will be extendable, and hopefully portable to other hardware - for example Raspberry Pi.
Some Specs
The SEM has an absolute scanning resolution of about 4096 x 4096 8 bit monochrome pixels. A full high-res image would therefore occupy 16MB of storage.
This resolution is not displayable on any monitor, so the compromise is to allow a smaller window view into the larger scanned field of view.
512x512 pixels is a convenient size for the available VGA system, so it would be possible to display a small window of just 1/64th of the whole field. When displayed on a 800 x 600 VGA monitor - this would allow adequate space around the image for text buttons, controls and tool icons.
It would be possible to extend this window to either (720x576) for 4:3 broadcast TV, or 800x600 for full screen display.
Saturday, August 22, 2015
Adventures in ARM Land Part 3 - What Next?
A series of blog posts about working with 32 bit ARM microcontrollers
See Part 1 "Surveying the Territory"
and Part 2 "Establishing Base Camp"
Whilst you are waiting for Part 3 - here's some nice bedtime reading
The STM32F ARM M4F Peripherals Explained - in 320 easy slides
In Part 2, I explained how in a typical STM32 device there might be as many as 30 on chip peripherals that require configuring before they can be used. I also stated that for convenience - and to improve code clarity, that the peripheral configuration functions were grouped together in a module which I call periph_config.c.
In this post, I will try to illustrate how a series of re-usable functions, can be utilised to create a simple working environment for code development.
This idea has been heavily borrowed from Arduino Wiring - in an attempt to create a simpler coding environment, where perhaps STM32 Arduino or mbed is not available.
These functions should provide the following:
1. Basic Input and Output using GPIO
2. PWM
3. Analogue to Digital Conversion
4. Digital to Analogue Conversion
5. Millisecond timing, uS and mS delays
6. Serial Input and Output
7. A simple serial command interpreter framework
8. Triggering of events using external interrupts.
1. Basic GPIO
digitalRead(pin)
digitalWrite(pin)
2. PWM
3. 12 bit ADC
Read_ADC_12()
4. DACs
analogWrite(channel, value)
5. Millisecond Timing
delaymS()
delayuS()
6. Serial Input and Output
putchar
print_num
See Part 1 "Surveying the Territory"
and Part 2 "Establishing Base Camp"
Whilst you are waiting for Part 3 - here's some nice bedtime reading
The STM32F ARM M4F Peripherals Explained - in 320 easy slides
In Part 2, I explained how in a typical STM32 device there might be as many as 30 on chip peripherals that require configuring before they can be used. I also stated that for convenience - and to improve code clarity, that the peripheral configuration functions were grouped together in a module which I call periph_config.c.
In this post, I will try to illustrate how a series of re-usable functions, can be utilised to create a simple working environment for code development.
This idea has been heavily borrowed from Arduino Wiring - in an attempt to create a simpler coding environment, where perhaps STM32 Arduino or mbed is not available.
These functions should provide the following:
1. Basic Input and Output using GPIO
2. PWM
3. Analogue to Digital Conversion
4. Digital to Analogue Conversion
5. Millisecond timing, uS and mS delays
6. Serial Input and Output
7. A simple serial command interpreter framework
8. Triggering of events using external interrupts.
1. Basic GPIO
digitalRead(pin)
digitalWrite(pin)
2. PWM
3. 12 bit ADC
Read_ADC_12()
4. DACs
analogWrite(channel, value)
5. Millisecond Timing
delaymS()
delayuS()
6. Serial Input and Output
putchar
print_num
Adventures in ARM Land - Part 2 - Establishing Base Camp
Introduction
In part 1, I introduced a range of commercially available development boards which would allow the newcomer to get started with 32bit ARM microcontrollers - specifically the STM32Fxxx range from ST Microelectronics.
I also highlighted a list of software tools which allow the user to develop code for these boards, from othe traditional compiler IDE, free GCC based such as CooCox CoIDE, to newer tools, such as online compilers, mbed, Espruino and simpler IDEs aimed at the newcomer, such as Arduino STM32.
There is a lot of choice available, both in terms of the hardware boards and the programming tools. It's a case of knowing what's out there - so you can choose a combination that suits your application and your programming experience.
These ARM boards fill the middle ground between Arduino and Raspberry Pi. Whilst many times more powerful than the original Arduino, they lack the GHz speed and the Linux operating system of the Raspberry Pi. Nevertheless, this gives them baremetal flexability and means that they are ideal for standalone, high speed, battery powered applications - and complement the capabilities of the Raspberry Pi.
Getting Started.
Here are some options:
Newcomer
1. Arduino STM32
If you have previously worked with Arduino, but are looking for more of a challenge or a faster microcontroller, then the transition may be made quite easily by using Arduino STM32. This is a community led project that upgrades the Arduino IDE toolchain so that it can be used to program the STM32 with "Arduino code". A sketch written for Arduino may be compiled and uploaded onto a board fitted with a STM32F103. All programming is done within the same familiar Arduino IDE.
The STM32F103 is a 72MHz microcontroller available with a range of different flash and RAM size options - all of which exceed the size of the Arduino MEGA. In comparative, standard Benchmark tests, the STM32F103 will execute code at between 4 and 7 times the speed of the Arduino mega.
However it's real advantage is the rich mix of peripherals that come with the '103.
On chip USB
12 bit ADCs
12 bit DACs
Multiple USARTs
Multiple I2C and SPI interfaces
Greater code and RAM size - for larger applications
Arduino STM32 has been tailored to suit the STM32F103 series of M3 microcontrollers - and is now a mature implementation, however it is now starting to support the M4 processors such as the '303 and '407.
2. mbed
mbed is an online compiler tool that supports ARM hardware from multiple vendors. It has comprehensive code libraries to support the various peripherals, and allows easy porting from one vendor's ARM devices to another. In terms of the STMF32 family it supports a range of Nucleo, Discovery and 3rd party boards.
From a programming point of view, mbed is similar to Arduino, but has a much cleaner, professional looking IDE. The code is compiled by an online compiler, where the binary file is generated and then forwarded to the browser as a download file. The bin file is then dragged onto the icon - which represents the target board as a flash drive, and the code is loaded and executed. It's fairly straightforward and easy to use. There are many code examples and templates to get you started and an online reference of what the various library functions do. As the compiler is cloud based, the application works on all platforms Windows, MAC and Linux.
If you want to progress away from the Arduino environment, and try out a wide range of powerful processors from many vendors - then mbed is probably the best way forwards.
3. Javascript for Microcontrollers
This is an interesting development by Espruino. It allows a few of the STM32Fxxx family of microcontrollers to be programmed using Javascript - generated from an online script editor.
Espruino produce a couple of their own target boards, the Espruino and the Pico, additionally the Javascript can be run on a variety of 3rd party boards including the Discovery F3, F4 and Nucleo 401 boards.
It is backed up with a comprehensive range of "modules" - essentially libraries that support common hardware devices - such as colour LCDs, WiFi, Ethernet controllers, and all the real world hardware that turns the microcontroller into a proper application. The list of hardware modules may be found here.
Intermediate
4. CooCox CoIDE
If you are an intermediate programmer, familiar with traditional IDE toolchains, then CoIDE from CooCox offers a free toolchain based on GCC and Eclipse. It takes a little bit of getting used to CooCox, but it forms a useful framework for developing code projects. CooCox supports ARM microcontrollers and boards from a range of vendors, and has built in extensions for flash programming the device.
5. Keil MDK-ARM Microcontroller Development Kit based on uVision 5
This is a full featured commercial tool chain from one of the principal compiler vendors. As a commercial product, it is likely to be too expensive for the amateur or hobbyist, however it is also available as a free to use, code size limited (32K) evaluation copy.
When I came to develop code on the STM32F746 BoB target board - this was the only available option. Shortly, there will be an option from mbed to support the STM32F746 Discovery platform.
Peripheral Vision
Having chosen your board, and your preferred toolchain, it's then a case of following some simple code examples in order to start exercising the hardware and peripherals. This where it starts to get a little complicated, primarily because a 32bit ARM microcontroller is a very complex piece of silicon.
The ARM core communicates with all of the on-chip peripherals via a vast array of memory mapped registers. For example a UART will have a Transmit register and a Receive register and a Status register. All of the on-chip peripherals will have several registers controlling their operation. Unlike an 8-bit processor, it's very difficult to remember what all these registers are, so ST Microelectronics provides a library of helper functions, called the Standard Peripheral Library. They do this for each of the microcontrollers in the various STM32 families. Very often the peripheral registers are given the same name from device to device - but that is not always the case. You might get code running perfectly well on a STM32F407, and then find that who ever wrote the Standard Peripheral Library for the STM32F303, used a different set of incompatible register names - doh. This is what keeps you on your toes with ARM baremetal programming.
Fortunately there is a Reference Manual for every processor, which gives all of the register names and usually code examples - you just have to keep reading, or finding specific code examples online to help you.
HAL
The Standard Peripheral Libraries are the first layer of hardware abstraction offered on the STM32 parts. About 18 months ago, STM moved towards a new system STM32 Cube. This replaced the standard peripheral libraries with a new Hardware Abstraction Layer - called HAL. HAL is designed to improve code portability and allow access to complex library resources - but if you are new to it, it is quite a challenging concept to take on board. HAL will be the subject of a future post - once I feel competent enough to describe it in detail.
Arduino removes the complexity of the underlying hardware with a series of common C++ functions, provided by their "Wiring" functions. This is also a hardware abstraction layer, which makes coding advanced hardware interactivity a lot easier for the newcomer. Arduino STM32 makes use of this "wiring" layer, to provide an Arduino-like programming environment for the STM32F103 range of processors.
Establishing a Base Camp
Every programmer, when faced with a new device, quickly wants to establish some familiar territory prior to starting the main task of coding. Having Arduino or mbed as a lingua franca is one good way - but what if your particular choice of processor is not yet supported by these?
Most of my coding is done using CooCox CoIDE - so within this environment, I wanted to establish a convenient framework to allow applications to be more easily developed.
The STM32Fxxx range of microcontrollers have a vast range of onchip peripherals. To use these effectively they first have to be configured and then enabled prior to use. To keep track of all the peripheral code, I tend to keep it in a separate module from the main code.
To illustrate the quantity of peripherals in a typical STM32F M4 application
8 to 10 Timers for frequency generation, PWM, quadrature decoding etc
4 USARTs
4 ADCs
2 DACs
3 SPI
2 I2C
Up to 80 GPIO lines
DMA
RTC
etc etc
Each of these peripherals needs a block of code to configure it - so the peripheral configuration module might have 30 such blocks of code and run to some 1500 lines.
Fortunately once this code has been written, it is relatively simple to maintain and modify. It is relatively easy to move from one STM32Fxxx family member to another.
To avoid the confusion and complexity of a modern coding project - especially handling the peripheral configuration, I developed a strategy, that would help organise the code, and one that would allow ease of porting to other processors, when they came available. I started with just two code modules to start with:
main.c
periph_config.c
main.c - as it's name suggest is where you put your main loop and application code
periph_config.c is where you put all the hardware specific, peripheral initialisation functions.
In this way, as and when you needed to add a new peripheral, it could just be added to the functions contained in periph_config.c
For example, my application requires a serial interface to a PC. So within periph_config.c, I write the function that configures USART1, in terms of baudrate, start bits, stop bits, parity etc.
void USART1_Config(void)
{
// Put the USART1 initialisation code here
}
As the application grew and I needed to configure the remaining 3 USARTS, I just had to add their configuration code to periph_config.c - for example
void USART2_Config(void)
{
// Put the USART2 initialisation code here
}
void USART3_Config(void)
{
// Put the USART3 initialisation code here
}
This process was repeated for the remaining peripherals, ADCs, DACs, I2C, SPI, GPIO, DMA etc. If a new peripheral was needed or an existing one modified - I just had to edit periph_config.c.
The next thing was to make sure that all of the right peripherals were initialised at the start of my main code. To do this I wrote an Init() function:
void Init(void)
{
USART1_Config();
USART2_Config();
USART3_Config();
// and so on for all the other peripherals.........
}
Borrowing from the SetUp() and Loop() concept from Arduino
main()
{
Init(); // All of the peripheral initialisation code is executed once here
while(1)
{
// Put you main loop code within this while loop
}
} // end of main
// Private functions used within main are placed here
Using this simple method, I had a coding environment quite similar to what I was familiar with in Arduino.
Next Time
In the next part, I will look at some of the functions which help build up a simple application.
In part 1, I introduced a range of commercially available development boards which would allow the newcomer to get started with 32bit ARM microcontrollers - specifically the STM32Fxxx range from ST Microelectronics.
I also highlighted a list of software tools which allow the user to develop code for these boards, from othe traditional compiler IDE, free GCC based such as CooCox CoIDE, to newer tools, such as online compilers, mbed, Espruino and simpler IDEs aimed at the newcomer, such as Arduino STM32.
There is a lot of choice available, both in terms of the hardware boards and the programming tools. It's a case of knowing what's out there - so you can choose a combination that suits your application and your programming experience.
These ARM boards fill the middle ground between Arduino and Raspberry Pi. Whilst many times more powerful than the original Arduino, they lack the GHz speed and the Linux operating system of the Raspberry Pi. Nevertheless, this gives them baremetal flexability and means that they are ideal for standalone, high speed, battery powered applications - and complement the capabilities of the Raspberry Pi.
Getting Started.
Here are some options:
Newcomer
1. Arduino STM32
If you have previously worked with Arduino, but are looking for more of a challenge or a faster microcontroller, then the transition may be made quite easily by using Arduino STM32. This is a community led project that upgrades the Arduino IDE toolchain so that it can be used to program the STM32 with "Arduino code". A sketch written for Arduino may be compiled and uploaded onto a board fitted with a STM32F103. All programming is done within the same familiar Arduino IDE.
The STM32F103 is a 72MHz microcontroller available with a range of different flash and RAM size options - all of which exceed the size of the Arduino MEGA. In comparative, standard Benchmark tests, the STM32F103 will execute code at between 4 and 7 times the speed of the Arduino mega.
However it's real advantage is the rich mix of peripherals that come with the '103.
On chip USB
12 bit ADCs
12 bit DACs
Multiple USARTs
Multiple I2C and SPI interfaces
Greater code and RAM size - for larger applications
Arduino STM32 has been tailored to suit the STM32F103 series of M3 microcontrollers - and is now a mature implementation, however it is now starting to support the M4 processors such as the '303 and '407.
2. mbed
mbed is an online compiler tool that supports ARM hardware from multiple vendors. It has comprehensive code libraries to support the various peripherals, and allows easy porting from one vendor's ARM devices to another. In terms of the STMF32 family it supports a range of Nucleo, Discovery and 3rd party boards.
From a programming point of view, mbed is similar to Arduino, but has a much cleaner, professional looking IDE. The code is compiled by an online compiler, where the binary file is generated and then forwarded to the browser as a download file. The bin file is then dragged onto the icon - which represents the target board as a flash drive, and the code is loaded and executed. It's fairly straightforward and easy to use. There are many code examples and templates to get you started and an online reference of what the various library functions do. As the compiler is cloud based, the application works on all platforms Windows, MAC and Linux.
If you want to progress away from the Arduino environment, and try out a wide range of powerful processors from many vendors - then mbed is probably the best way forwards.
3. Javascript for Microcontrollers
This is an interesting development by Espruino. It allows a few of the STM32Fxxx family of microcontrollers to be programmed using Javascript - generated from an online script editor.
Espruino produce a couple of their own target boards, the Espruino and the Pico, additionally the Javascript can be run on a variety of 3rd party boards including the Discovery F3, F4 and Nucleo 401 boards.
It is backed up with a comprehensive range of "modules" - essentially libraries that support common hardware devices - such as colour LCDs, WiFi, Ethernet controllers, and all the real world hardware that turns the microcontroller into a proper application. The list of hardware modules may be found here.
Intermediate
4. CooCox CoIDE
If you are an intermediate programmer, familiar with traditional IDE toolchains, then CoIDE from CooCox offers a free toolchain based on GCC and Eclipse. It takes a little bit of getting used to CooCox, but it forms a useful framework for developing code projects. CooCox supports ARM microcontrollers and boards from a range of vendors, and has built in extensions for flash programming the device.
5. Keil MDK-ARM Microcontroller Development Kit based on uVision 5
This is a full featured commercial tool chain from one of the principal compiler vendors. As a commercial product, it is likely to be too expensive for the amateur or hobbyist, however it is also available as a free to use, code size limited (32K) evaluation copy.
When I came to develop code on the STM32F746 BoB target board - this was the only available option. Shortly, there will be an option from mbed to support the STM32F746 Discovery platform.
Peripheral Vision
Having chosen your board, and your preferred toolchain, it's then a case of following some simple code examples in order to start exercising the hardware and peripherals. This where it starts to get a little complicated, primarily because a 32bit ARM microcontroller is a very complex piece of silicon.
The ARM core communicates with all of the on-chip peripherals via a vast array of memory mapped registers. For example a UART will have a Transmit register and a Receive register and a Status register. All of the on-chip peripherals will have several registers controlling their operation. Unlike an 8-bit processor, it's very difficult to remember what all these registers are, so ST Microelectronics provides a library of helper functions, called the Standard Peripheral Library. They do this for each of the microcontrollers in the various STM32 families. Very often the peripheral registers are given the same name from device to device - but that is not always the case. You might get code running perfectly well on a STM32F407, and then find that who ever wrote the Standard Peripheral Library for the STM32F303, used a different set of incompatible register names - doh. This is what keeps you on your toes with ARM baremetal programming.
Fortunately there is a Reference Manual for every processor, which gives all of the register names and usually code examples - you just have to keep reading, or finding specific code examples online to help you.
HAL
The Standard Peripheral Libraries are the first layer of hardware abstraction offered on the STM32 parts. About 18 months ago, STM moved towards a new system STM32 Cube. This replaced the standard peripheral libraries with a new Hardware Abstraction Layer - called HAL. HAL is designed to improve code portability and allow access to complex library resources - but if you are new to it, it is quite a challenging concept to take on board. HAL will be the subject of a future post - once I feel competent enough to describe it in detail.
Arduino removes the complexity of the underlying hardware with a series of common C++ functions, provided by their "Wiring" functions. This is also a hardware abstraction layer, which makes coding advanced hardware interactivity a lot easier for the newcomer. Arduino STM32 makes use of this "wiring" layer, to provide an Arduino-like programming environment for the STM32F103 range of processors.
Establishing a Base Camp
Every programmer, when faced with a new device, quickly wants to establish some familiar territory prior to starting the main task of coding. Having Arduino or mbed as a lingua franca is one good way - but what if your particular choice of processor is not yet supported by these?
Most of my coding is done using CooCox CoIDE - so within this environment, I wanted to establish a convenient framework to allow applications to be more easily developed.
The STM32Fxxx range of microcontrollers have a vast range of onchip peripherals. To use these effectively they first have to be configured and then enabled prior to use. To keep track of all the peripheral code, I tend to keep it in a separate module from the main code.
To illustrate the quantity of peripherals in a typical STM32F M4 application
8 to 10 Timers for frequency generation, PWM, quadrature decoding etc
4 USARTs
4 ADCs
2 DACs
3 SPI
2 I2C
Up to 80 GPIO lines
DMA
RTC
etc etc
Each of these peripherals needs a block of code to configure it - so the peripheral configuration module might have 30 such blocks of code and run to some 1500 lines.
Fortunately once this code has been written, it is relatively simple to maintain and modify. It is relatively easy to move from one STM32Fxxx family member to another.
To avoid the confusion and complexity of a modern coding project - especially handling the peripheral configuration, I developed a strategy, that would help organise the code, and one that would allow ease of porting to other processors, when they came available. I started with just two code modules to start with:
main.c
periph_config.c
main.c - as it's name suggest is where you put your main loop and application code
periph_config.c is where you put all the hardware specific, peripheral initialisation functions.
In this way, as and when you needed to add a new peripheral, it could just be added to the functions contained in periph_config.c
For example, my application requires a serial interface to a PC. So within periph_config.c, I write the function that configures USART1, in terms of baudrate, start bits, stop bits, parity etc.
void USART1_Config(void)
{
// Put the USART1 initialisation code here
}
As the application grew and I needed to configure the remaining 3 USARTS, I just had to add their configuration code to periph_config.c - for example
void USART2_Config(void)
{
// Put the USART2 initialisation code here
}
void USART3_Config(void)
{
// Put the USART3 initialisation code here
}
This process was repeated for the remaining peripherals, ADCs, DACs, I2C, SPI, GPIO, DMA etc. If a new peripheral was needed or an existing one modified - I just had to edit periph_config.c.
The next thing was to make sure that all of the right peripherals were initialised at the start of my main code. To do this I wrote an Init() function:
void Init(void)
{
USART1_Config();
USART2_Config();
USART3_Config();
// and so on for all the other peripherals.........
}
Borrowing from the SetUp() and Loop() concept from Arduino
main()
{
Init(); // All of the peripheral initialisation code is executed once here
while(1)
{
// Put you main loop code within this while loop
}
} // end of main
// Private functions used within main are placed here
Using this simple method, I had a coding environment quite similar to what I was familiar with in Arduino.
Next Time
In the next part, I will look at some of the functions which help build up a simple application.
Adventures in ARM Land - Part 1 - Surveying the Territory
Introduction
This post is the first of a series of three (or more), intended to introduce the newcomer to the world of 32bit ARM processors, based on my past experiences. Whilst not a tutorial with code examples (these are available elsewhere online) it is hoped that others will be inspired to follow a similar journey.
In this post I introduce some low cost commercially available development boards, and the range of software tools currently available with which to program them.
I also showcase three of my own open source hardware designs, to illustrate that these microcontroller pcbs are not beyond the realm of hobbyist pcb design and construction.
On the Job Tinkering with ARM Chips
In November 2013, I had the opportunity to explore a new range of 32 bit microcontrollers as part of a development to upgrade our product range at work.
Since then, I have been working both professionally and on a hobby basis with the series of ARM Cortex M microcontrollers from ST Microelectronics.
I was initially attracted to this series of devices because of their rich set of peripherals and resources, low cost development boards and that there was a rapidly growing User Community.
Having put a significant amount of time into familiarising myself with this new family of processors, I have found that they are relatively easy to use, and that it is fairly straightforward to move between different members of the family - depending on your application.
There are a very wide range of target boards available - some starting at less than $5 (from China). Additionally, ST Microelectronics produces it's own range of very low cost target boards - to get you quickly started on your application.
Not an Arduino and not a Pi
The STM32Fxxx family of 32bit microcontrollers are available with clock speeds between 72MHz and 216MHz. This places them at about 4 to 16 times faster than an Arduino based on the 16MHz ATmega328. In addition, their 32bit wordsize, larger flash memory and RAM allows more complex applications to be run. The STM32F Cortex M4 has a floating point unit (FPU) capable of executing single cycle multiplication, hardware divide and some DSP instructions.
Whilst faster than the original Arduino (and Due), they cannot compete in speed with the 1GHz quad core Raspberry Pi 2. However, as they were designed for the embedded microcontroller market, they have several peripherals that the Pi lacks - such as 12bit ADCs and DACs. Also, as they are unlikely to ever support Linux, it means that your application is not constrained by the operating system, giving you full access to the timing - making them ideal for Real Time Control applications.
Finally, the processor has a number of power saving modes, and even flat out will only consume between 50 and 100mA. This makes them ideal for hand held, battery operated applications.
Maple Mini (Chinese Copy)
The Maple Mini was one of the first hobbyist boards to use the STM32F103 - originally produced by Leaf Labs in Canada. Leaf Labs no longer support this board, but it has been widely copied in China and is available for as little as $5. The example above is a 40 pin DIL format making it ideal to fit into a prototyping breadboard. Leaf Labs derived their own version of the Arduino IDE - and now through a community project, their code has now been adopted and updated by Arduino STM32 - allowing you to program these little boards directly from the Arduino language. Ideal for beginners.
Nucleo Boards
These are produced by ST Microelectronics and offer a very low cost way to get started with ARM and mbed programming. The upper part of the pcb is a "detachable" ST Link V2 flash programmer - alone worth about £20. The programmer section can be used with a 6 way cable to program other STM32F ARM boards you may have.
The lower part of the pcb has both Arduino footprint connectors - allowing the use of some Arduino shields, but additionally the STM "Morpho" dual row connectors, allowing access to all of the I/O pins.
This ability to change between processors has been exploited to it's full potential with the range of ST Nucleo development boards - a small, low cost, "Arduino like" platform, with built in flash programmer, and the means to be programmed using the online mbed compiler. Each Nucleo board is fitted with a 64pin LQFP microcontroller which being virtually pin identical, allows you to choose which processor best suits your application.
A full list of Nucleo boards is described here - but notably here are the ones I have used
STM32F103 ARM Cortex M3 72MHz - a good general purpose microcontroller
STM32F303 ARM Cortex M4F 72MHz - Analogue SoC with 5MSPs ADC, PGA etc
STM32F373 ARM Cortex M4F 72MHz - 3 x 16bit SD ADCs
STM32F401 ARM Cortex M4F 84MHz - low power microcontroller
STM32F401 ARM Cortex M4F 100MHz - low power microcontroller
If you choose to develop code for these using the mbed platform, you can readily switch between target boards to assess which target is best for your application. For example, whilst all STM32Fxxx microcontrollers have multiple 12bit ADC and DAC channels, you will find that the STM32F303 has the highest speed ADC (5MSPs) but the STM32F373 offers in addition, 3 independent 16 bit ADCs - which is ideal for 3-phase energy measurements.
If however you are looking for a low power controller perhaps for extended battery operation, the STM32F401 and 411 are described as STM's "Dynamic Efficiency Line" and use a "Batch Acquisition Mode" BAM - a low power means of acquiring data from sensors, processing the data, then returning to a low power state.
Discovery Boards
STM also has a range of feature rich Discovery Boards - with additional hardware included on board to specifically highlight typical user applications. The top quarter of the pcb is the STM32F ST Link V2 flash programmer. All of the STM32F407 GPIO pins are broken out into the twin row connectors.
This Discovery F4 board is a powerful board - with a processing throughput approximately 15 times that of an Arduino. It has 80 GPIO lines and a rich set of peripherals making it idea for motor control and instrumentation systems.
These are available for the following microcontrollers (plus others)
STM32F303 - with on board compass and accelerometer sensors
STM32F407 - with accelerometer, audio sampling and playback
STM32F429 - with colour LCD
STM32F746 - with colour touchscreen LCD, Ethernet + camera, audio, + much, much more
My own ARM journey started with the Discovery F4, but I have evaluated the others above, for various applications, both at work and for play.
Software Tools
There is an ever increasing number of options available to allow you to program these microcontrollers - so far I have looked at the following:
1. A fully functioning tool suite from one of the major suppliers - very expensive
2. A code size limited tool chain - free to use for smaller applications
3. An online tool chain - for example mbed
4. Free to use IDE using open source GCC - Coocox CoIDE
5. Online Javascript - notably Espruino - offering JS to STM32xxx microcontrollers
6. Aruino_STM32 - a community based extension to Arduino allowing Arduino IDE coding for STM32F Cortex and M3 and M4.
Some of these are windows platform only. Some do not fully support certain microcontrollers - so for example, whilst I generaly use Coocox or mbed, I had to use a 32K code size limited version of Keil's uVision 5 in order to develop code for the STM32F746 Cortex M7.
Arduino STM32 is an interesting option for hobbyists, because it allows an easy transition from the AVR based Arduino platforms to much more powerful ones based on the STM32F103. Sketches written for the Arduino can be easily ported to ARM M3 and M4 based hardware. It also allows the Arduino community to break free from the limitations of the official Arduino platforms.
Some Hardware Notes
The STM32Fxxx range of microcontrollers are available in a range of package sizes from LQFP-48 upwards. The "leaded quad flat pack" package may be soldered by hand, if sufficient care is taken. This offers the options for enthusiasts to design their own pcbs - using EagleCAD or KiCAD etc.
Personally, I have designed pcbs to accept 48 pin, 64 pin and 100 pin parts using EagleCAD. Initially these were intended as Breakout Boards - so that I could access all the peripheral pins - without other hardware getting in the way. Later, these designs generally evolved into more application specific devices.
Three of my existing designs are intended for Open Sourcing:
1. ARMiGo - accepts a 48 pin LQFP, either STM32F103, STM32F303 or STM32F373 and makes its pins available on a 40 pin 0.6" DIL header - intended for breadboard prototyping.
2. Piano Forte - accepts a 64 pin LQFP, either STM32F103, STM32F303 or STM32F373 and makes its I/O available in an Arduino pin-out or as 2.1" wide SIL header format - that can be placed across 2 breadboards. Can also be plugged into a Raspberry Pi - and used as a PI-HAT compatible Analogue and Digital I/O board to augment the Pi.
3. BoB - A totally uncluttered breakout board for the 100 pin LQFP STM32F746. Breaks out the I/O of the STM32F746 into the 2x25 pin dual row headers as used on the Discovery F4. Allows the Cortex M7 to be evaluated as an 2X+ performance upgrade to the Cortex M4.
Availability
In the UK, STM32 Discovery and Nucleo boards may be obtained from
Farnell - business customers
CPC - hobbyists
RS Components
In the US
Newark
Digikey
Mouser
This post is the first of a series of three (or more), intended to introduce the newcomer to the world of 32bit ARM processors, based on my past experiences. Whilst not a tutorial with code examples (these are available elsewhere online) it is hoped that others will be inspired to follow a similar journey.
In this post I introduce some low cost commercially available development boards, and the range of software tools currently available with which to program them.
I also showcase three of my own open source hardware designs, to illustrate that these microcontroller pcbs are not beyond the realm of hobbyist pcb design and construction.
On the Job Tinkering with ARM Chips
In November 2013, I had the opportunity to explore a new range of 32 bit microcontrollers as part of a development to upgrade our product range at work.
Since then, I have been working both professionally and on a hobby basis with the series of ARM Cortex M microcontrollers from ST Microelectronics.
I was initially attracted to this series of devices because of their rich set of peripherals and resources, low cost development boards and that there was a rapidly growing User Community.
Having put a significant amount of time into familiarising myself with this new family of processors, I have found that they are relatively easy to use, and that it is fairly straightforward to move between different members of the family - depending on your application.
There are a very wide range of target boards available - some starting at less than $5 (from China). Additionally, ST Microelectronics produces it's own range of very low cost target boards - to get you quickly started on your application.
Not an Arduino and not a Pi
The STM32Fxxx family of 32bit microcontrollers are available with clock speeds between 72MHz and 216MHz. This places them at about 4 to 16 times faster than an Arduino based on the 16MHz ATmega328. In addition, their 32bit wordsize, larger flash memory and RAM allows more complex applications to be run. The STM32F Cortex M4 has a floating point unit (FPU) capable of executing single cycle multiplication, hardware divide and some DSP instructions.
Whilst faster than the original Arduino (and Due), they cannot compete in speed with the 1GHz quad core Raspberry Pi 2. However, as they were designed for the embedded microcontroller market, they have several peripherals that the Pi lacks - such as 12bit ADCs and DACs. Also, as they are unlikely to ever support Linux, it means that your application is not constrained by the operating system, giving you full access to the timing - making them ideal for Real Time Control applications.
Finally, the processor has a number of power saving modes, and even flat out will only consume between 50 and 100mA. This makes them ideal for hand held, battery operated applications.
Maple Mini (Chinese Copy)
![]() |
| A "Maple Mini" - a low cost STM32F103 board from China |
Nucleo Boards
These are produced by ST Microelectronics and offer a very low cost way to get started with ARM and mbed programming. The upper part of the pcb is a "detachable" ST Link V2 flash programmer - alone worth about £20. The programmer section can be used with a 6 way cable to program other STM32F ARM boards you may have.
The lower part of the pcb has both Arduino footprint connectors - allowing the use of some Arduino shields, but additionally the STM "Morpho" dual row connectors, allowing access to all of the I/O pins.
![]() |
| Nucleo-F103RB - about £8.50 from Farnell CPC |
This ability to change between processors has been exploited to it's full potential with the range of ST Nucleo development boards - a small, low cost, "Arduino like" platform, with built in flash programmer, and the means to be programmed using the online mbed compiler. Each Nucleo board is fitted with a 64pin LQFP microcontroller which being virtually pin identical, allows you to choose which processor best suits your application.
A full list of Nucleo boards is described here - but notably here are the ones I have used
STM32F103 ARM Cortex M3 72MHz - a good general purpose microcontroller
STM32F303 ARM Cortex M4F 72MHz - Analogue SoC with 5MSPs ADC, PGA etc
STM32F373 ARM Cortex M4F 72MHz - 3 x 16bit SD ADCs
STM32F401 ARM Cortex M4F 84MHz - low power microcontroller
STM32F401 ARM Cortex M4F 100MHz - low power microcontroller
If you choose to develop code for these using the mbed platform, you can readily switch between target boards to assess which target is best for your application. For example, whilst all STM32Fxxx microcontrollers have multiple 12bit ADC and DAC channels, you will find that the STM32F303 has the highest speed ADC (5MSPs) but the STM32F373 offers in addition, 3 independent 16 bit ADCs - which is ideal for 3-phase energy measurements.
If however you are looking for a low power controller perhaps for extended battery operation, the STM32F401 and 411 are described as STM's "Dynamic Efficiency Line" and use a "Batch Acquisition Mode" BAM - a low power means of acquiring data from sensors, processing the data, then returning to a low power state.
Discovery Boards
![]() |
| Discovery F4 - About £12.50 from Farnell |
STM also has a range of feature rich Discovery Boards - with additional hardware included on board to specifically highlight typical user applications. The top quarter of the pcb is the STM32F ST Link V2 flash programmer. All of the STM32F407 GPIO pins are broken out into the twin row connectors.
This Discovery F4 board is a powerful board - with a processing throughput approximately 15 times that of an Arduino. It has 80 GPIO lines and a rich set of peripherals making it idea for motor control and instrumentation systems.
These are available for the following microcontrollers (plus others)
STM32F303 - with on board compass and accelerometer sensors
STM32F407 - with accelerometer, audio sampling and playback
STM32F429 - with colour LCD
STM32F746 - with colour touchscreen LCD, Ethernet + camera, audio, + much, much more
My own ARM journey started with the Discovery F4, but I have evaluated the others above, for various applications, both at work and for play.
Software Tools
There is an ever increasing number of options available to allow you to program these microcontrollers - so far I have looked at the following:
1. A fully functioning tool suite from one of the major suppliers - very expensive
2. A code size limited tool chain - free to use for smaller applications
3. An online tool chain - for example mbed
4. Free to use IDE using open source GCC - Coocox CoIDE
5. Online Javascript - notably Espruino - offering JS to STM32xxx microcontrollers
6. Aruino_STM32 - a community based extension to Arduino allowing Arduino IDE coding for STM32F Cortex and M3 and M4.
Some of these are windows platform only. Some do not fully support certain microcontrollers - so for example, whilst I generaly use Coocox or mbed, I had to use a 32K code size limited version of Keil's uVision 5 in order to develop code for the STM32F746 Cortex M7.
Arduino STM32 is an interesting option for hobbyists, because it allows an easy transition from the AVR based Arduino platforms to much more powerful ones based on the STM32F103. Sketches written for the Arduino can be easily ported to ARM M3 and M4 based hardware. It also allows the Arduino community to break free from the limitations of the official Arduino platforms.
Some Hardware Notes
The STM32Fxxx range of microcontrollers are available in a range of package sizes from LQFP-48 upwards. The "leaded quad flat pack" package may be soldered by hand, if sufficient care is taken. This offers the options for enthusiasts to design their own pcbs - using EagleCAD or KiCAD etc.
Personally, I have designed pcbs to accept 48 pin, 64 pin and 100 pin parts using EagleCAD. Initially these were intended as Breakout Boards - so that I could access all the peripheral pins - without other hardware getting in the way. Later, these designs generally evolved into more application specific devices.
Three of my existing designs are intended for Open Sourcing:
1. ARMiGo - accepts a 48 pin LQFP, either STM32F103, STM32F303 or STM32F373 and makes its pins available on a 40 pin 0.6" DIL header - intended for breadboard prototyping.
2. Piano Forte - accepts a 64 pin LQFP, either STM32F103, STM32F303 or STM32F373 and makes its I/O available in an Arduino pin-out or as 2.1" wide SIL header format - that can be placed across 2 breadboards. Can also be plugged into a Raspberry Pi - and used as a PI-HAT compatible Analogue and Digital I/O board to augment the Pi.
3. BoB - A totally uncluttered breakout board for the 100 pin LQFP STM32F746. Breaks out the I/O of the STM32F746 into the 2x25 pin dual row headers as used on the Discovery F4. Allows the Cortex M7 to be evaluated as an 2X+ performance upgrade to the Cortex M4.
Availability
In the UK, STM32 Discovery and Nucleo boards may be obtained from
Farnell - business customers
CPC - hobbyists
RS Components
In the US
Newark
Digikey
Mouser
Sunday, August 09, 2015
Holiday Hacking - A Survivor's Guide
| I'd forgotten I was packing so many platforms..... |
The idea being that with a minimum kit of parts, easily carried, and perhaps some online guide, that it would be possible to set up virtually anywhere and learn how to code, by practical experimentation.
At the end of July, I had travelled to Rhodes, armed with a few dev boards, a breadbord, some components and a netbook, which I considered to be the minimum I could get away with and yet do some serious hacking.
As it Stands....
Presently, there are two main physical computing platforms, Raspberry Pi and Arduino, which between them, probably covers 90% of all hack applications, however there are some newer arrivals, mostly 32bit ARM based platforms, that offer some interesting new middle ground to explore as the basis for hacking projects. These will we covered later.
![]() |
| The Lunchbox has landed.... |
BOB - an ARM M7 breakout board
A small bomb disguised as an EE Powerbar
Essential FTDI cable
Two breadboards
jumper wires
all served on small raft of wire- ended components.
A Minimum Solution.
You can do a lot with an Arduino, a USB cable and a laptop or netbook PC. To me I feel this offers a minimum solution that provides a basis for experimentation. However an Arduino on it's own, lacks any real interactivity - there's only so much that you can do with a single flashing LED. We need to add a few more bells and whistles.
The Arduino Experimenter's kit (this one from Adafruit - but lots of others to choose from) seems a close approximate to what is needed, as it provides Arduino, breadboard and a selection of components and jumper wires that allow a fair amount of experiments to be performed. Add to this a Netbook, with the latest Arduino IDE loaded, and you have a minimum portable package that can be taken on the road.
Add a couple of your favourite shields, and you have a compact playkit that will easily fit into a plastic sandwich box.
The Arduino however is now showing its age, and lacks a lot of user interactivity. A better package would be a Raspberry Pi and a Pibrella - which includes a bunch of LEDs, switch and small speaker. By connecting the Pi to the PC, either with a USB or network cable you have a hackable platform, with the netbook PC providing a workable screen and keyboard, for code development. This was the arrangement we used at a recent node-RED workshop, hosted by Dr. Andy Stanford Clark and Dr. Lucy Rogers.
The Pi on it's own also lacks any real user interaction - unless you have keyboard and screen attached, and it also requires quite a lot of current to operate. This means that you probably won't be able to power it off a netbook USB port, which means finding a mains adaptor or some sort of alternative supply. Fortunately there are now a number of LiPo battery solutions being made available for the Pi to greatly extend its portability. At a pinch, you might be able to power one for a couple of hours from a mobile phone charging pack.
Then there is the question of what components to take, for maximum interactivity. LEDs, both individual, such as for traffic light displays, or 7-segment or matrix are also good for creating visual effects. Simple rows of LEDs, driven individually from a port pin are good for chaser effects (Knight Rider) and bargraph displays.
Switches, sensors and sounders also allow for a lot of creative coding. Last week in Rhodes, I knocked up a simple thermometer using a thermistor, resistor and an Arduino, and soon I could tell that it was 32C in the shade. Adding a couple of 7 segment displays would have made for an interesting self contained project.
As technology becomes more sophisticated, it is natural that hackers want to explore its bounds. One idea might be a colour LCD touchscreen that provides the user interactivity. Products such as Gameduino and Gameduino2, allow a platform even as humble as an Arduino to host an arcade style game- with the processing grunt to handle the display provided by the Gameduino.
It's a question of personal choice, given a restriction of how much kit you can take, would you opt for low level hacking of hardware, or spend time writing higher level code for simple games?
Hanging On the Telephone.....
The other possibility is that a Smartphone could be used for interactivity. This is the route suggested by the recent Microbit platform promoted by the BBC. Whilst it provides a simple LED matrix and a couple of switches, it could readily be connected to a mobile phone that provides a simple coding interface. Additionally it is powered by a small ARM processor with on chip Bluetooth LE, so board to board, and board to phone communications are achievable. An accelerometer and magnetometer compass sensor is provided on board, so interacting to motion and direction is also an area to explore. PC connection is via a USB cable and the interface is a web browser.
The inclusion of BLE on board allows this platform to connect with both Android and iOS smartphones - BLE being the common accessible link.
Microbits provides sufficient interactivity for fun-based hacking, and its relatively low power consumption means that standalone, battery operation is possible. This opens out possibilities for free-roaming robots, controlled via BLE, or battery powered sensors, communicating back to a phone or laptop via BLE.
Hopefully with the 1 million Microbit roll-out distribution to Year 7 students in UK schools, then this will inspire a new generation to explore the new world of physical computer hacking.
The good news is that the manufacturers intend to make Microbits available to anyone who wants to buy them - after the initial BBC rollout to secondary schools.
As soon as we start to see some real information, and tech specs, circuit diagrams of Microbits, then the hack community can go to work on this new device. I really hope that it succeeds, and that these little hack-buddies don't just go straight to landfill.
It's early days - so time will tell.
New Horizons
Arduino is a great beginner's platform but is now in it's 10th year, and starting to show it's age. It can easily be hacked with parts on a breadboard or additional functionality on a shield. It is low power, and the IDE is self-contained and usable for even the inexperienced coder. However, so much more can be achieved by moving on to platforms based on 32bit ARM technology.
Raspberry Pi, being a considerably more powerful processor and GPU, allows for the hosting of operating systems and high level languages, with video and graphics. Now in it's fourth year, there are an increasing number of Pi HATs available, for user experimentation. The GPIO is not as robust as that of the Arduino - so you have to treat it with a little more respect- nobody enjoys fried Pi!
Other platforms are available, that cover some of the middle ground between Arduino and Pi. These are 32 bit ARM based platforms which in some cases can be programmed with a modified Arduino IDE. Alternatively some host, scripting languages, (the Espruino - which runs JavaScript) which allow reasonable high level code development. The mbed online compiler, is another solution, which allows you to code in a fairly friendly environment, provided that you have internet access. There are not many resorts in Europe where you can't find a cafe or bar with wifi access. mbed supports a wide range of ARM platforms, including microcontrollers from FreeScale and STMicroelectronics. The low cost (<£10) ST Nucleo platforms are not only Arduino shield compatible, but offer 5V tolerance on all but the ADC pins and a lot more grunt than the Arduino.
Smartphone interactivity, WiFi, BLE and touchscreen displays will further enhance what can be done with these small platforms, making them an attractive addition to any Hacker's survival kit.
The laptop or netbook is the centre of your hack environment. Make sure that you have preloaded it with all the software apps that you might need whilst away from base. Mine has the Arduino IDE, Termite- a terminal emulator, EagleCAD and CooCox COIDE - an IDE for ARM code development. Irfanview is also great for photo handling. With Open Office/Libre, and using your smartphone as a camera, you can achieve a surprising amount with minimum tools. This blog was written in Notepad++ whilst no wifi was available and then ported to my blog when I got to my favourite bar.
Powerful Solutions
Electronics doesn't work without power, and in the case of a laptop or netbook, you will be looking to recharge every few hours. Don't forget to pack the charger and the travel adaptor for whichever continent you are visiting.
Don't wait till you get to the airport where they will fleece you £7.79 for something you can buy in Poundland. Speaking of which, Poundland is also a good source for microUSB cables and ear-plugs - stock up whilst you are there for some emergency spares.
If your laptop battery is down to 10%, find a cafe or bar, and have a snack or a drink for an hour, having either cased the joint for power outlets - or asked the staff politely. It will cost you about 4 Euros (£3) but that is the cost of an opportunity charge. Don't forget to plug in at night, if you are staying in an apartment. If you are roughing it - consider the possibilities of a small solar charger - there are some good ones about the size of a Kindle, or some of the new power packs - used for topping up mobile phones. If you are seriously hacking - find a nice, cool place to work - with a mains outlet.
Packing it Up
Taking hacking supplies abroad presents few if any real problems. Provided that you are careful, there's not many things that you can't pack in a suitcase. Pack your boards and bits into a small box, and put them in your hold luggage. Any tools you carry, screwdrivers or cutters, should also go in hold luggage. Try to include any original packaging, so that if your cache of boards is investigated, it can be clearly seen that they are commercial products - and not an IED. Any wires or components should be put in plastic bags - clearly visible, and not at all bomb like. Take special care with any LiPo batteries you are carrying - make sure they are secure and cannot short to any metallic object.
A few days after I got to Rhodes, there was a news story concerning faulty smartphone rechargers - the PowerBar distributed by EE. A particular batch had proven to be faulty and had to be recalled, as about 1 in 100,000 had an overheat/explode tendency. That's my "faulty" PowerBar (green&yellow) at the centre of the sandwich box. I will be particularly careful when packing that back in my hold luggage - though the risk is miniscule.
It is very unlikely that your hold luggage will go through an extensive search - but don't take any chances. I know a girl hacker in the USA who walked into airport security with a bit of wearable technology, and was very close to being shot by nervous armed guards.
Laptops, netbooks and tablets present little security threat, and can readily be carried on as hand luggage. The Airbus I travelled on provided WiFi, and provided that the GSM phone functions are disabled in "Airplane Mode", most airlines will now accept WiFi, BLE and other 2.4GHz device communications for the majority of the flight.
If you are on holiday - don't forget to do the usual holiday things too, but often, once away from the usual work environment, your brain finds spare capacity to think of new ideas, that can be planned and put into action upon return.
For extra Geekiness....In the top photo - top row
STM32F4 Discovery - low cost STM32F407 ARM M4 Cortex based
WiNode - Arduino based with 433MHz wireless (one of mine)
ServoNode - Arduino based - designed by my firm's student intern - in his first week :)
ARMiGo - ARM M4 Cortex designed for breadboard friendliness (one of mine)
Centre
BOB - a breakout board for the STMF7 (one of mine - making international debut)
Nanode - Arduino based - a friendly hackhorse I designed in 2011
Bottom Row - hatrick
PianoForte - an ARM M4 Cortex based I/O Pi HAT format supercharger for the Raspberry Pi WiFi/BLE/RFM69 connectivity - one of my DIYs.
Subscribe to:
Posts (Atom)








