Saturday, May 17, 2014

Make Life Easy, Make it Modular



This is a follow on to a post I wrote back in March 2014.  

As integrated circuits get smaller, and more powerful, it becomes increasingly difficult for the hobbyist to utilise them easily. Soldering tiny SMT parts is a challenge for many - so let's try to find a way to make life easier.

Why not make our microcontrollers modular - so you buy what you need that matches your application, and at a price you can afford. Unbelievably you can now buy an Arduino Nano or Pro-Mini from China, cheaper than you can buy the microcontroller IC from a Western supplier.

So if you want to quickly hack stuff together, standardised modules are one way to go.

A standard module footprint across different manufacturers.

This would really open up the competition between the various microcontroller suppliers.  Whether it's PIC, TI or Atmel, they all release a reference design for a standard module, and an accompanying IDE based on a common standard, so that you can easily, and seamlessly swap between devices.

So let's speculate about a series of standardised modules, which can offer varying degrees of performance, choice of microcontroller and yet are available in a compact, breadboard friendly, dual in line (DIL) footprint. For interchangeability, the power pins, reset and uart pins need to fixed, whilst the remainder of the pins can be general purpose I/O, perhaps arranged into a row of analogue function pins on one side, and a row of digital on the other. SPI interfaces should preferably be assigned to 4 consecutive pins for convenience. 

32 bit versus 8 bit. 

32 bit ARM microcontrollers are now virtually the same cost as older 8 bit devices, yet offer a many fold increase in performance, as a result of their 32 bit architecture and faster clock speed. In addition to this, they come with a rich set of peripherals, making them ideal for more demanding applications.

For the hobbyist who may have first gained exposure to microcontrollers via 8 bit products such as the Arduino, the move to 32 bit may appear a little daunting.  However we all have to progress and keep up with the times, so forget 8 bit and 5V logic and get into the world of 32 bit devices running at 3.3V - or less.

The Arduino shield idea was a good move to gain standardisation and traction within the Maker Community, but as we move to more powerful microcontrollers, the original shield pin-out is no longer appropriate or desirable. Perpetuating the non-standard header spacing this long after the original mistake was made is questionable.

At 68x53mm, the original Arduino form factor is starting to look a lot on the large size - particularly when you want to compact it into a small device, such as a robot. Fortunately this has been addressed, and the very compact Pro-Mini and Nano are clearly a step in the right direction.

In an ideal world we ought to be able to buy standard modules, that come in 28, 32 or 40 pin DIP packages, that offer whatever speed and resources we need. A 40 pin DIP is about the maximum convenient size, and with 35 or 36 I/O pins available it's well suited to the pin-out requirements of 48 pin microcontrollers, and offers nearly twice the I/O of the original Arduino in a footprint that is a quarter of the size. A smaller format uses a lot less pcb material, increases the density of the hardware, and allows manufacturers to focus on supplying a high-end microcontroller in a usable package,

In the Arduino world, the Pro-Mini and Nano, go some way to pin compatibility, at least they have the power pins and most of the I/O lines appearing on the same pins.

All it would take is someone to define a popular standard, and everyone else produces compatible hardware.

There will obviously be a requirement for more sophisticated boards, generally of the Raspberry Pi and BeagleBoard format, where a high-end ARM, running an operating system, is combined with external RAM, flash and a host of external peripheral interfaces. For these devices a different solution will emerge, but first let's focus on the easy stuff.

Keep it Modular - So easy to upgrade.

When your 16MHz ATmega328 module can no longer hack it, you search the suppliers for an upgrade. Do you stick with Atmel, or switch to TI, STM or Microchip? You select a module with the right footprint, Flash and RAM resources and clock frequency and do an instant upgrade.  All of your existing code is easily ported to the new module.

I wanted to explore the module concept further, so set about designing my own.

Getting Started.

The plan was to make a standard plugable component, that gives users the power of a 32 bit ARM, but in an easy to use and breadboard friendly module. I reckoned that a 40 pin DIL module would be about the right format for most small projects.

I elected to use the STM32F3xx range of microcontrollers from ST Microelectronics.  They have a great mix of both digital and high speed analogue ADC peripherals and are good value for money.

Initially I bought a Discovery F3 development board, which uses a 100 pin STM32F303 processor and has  compass, accelerometer and gyro devices on the board. It was exceptionally good value at under $11 from Newark.  However, whilst it provided a platform to get me started writing code and getting the framework to support my application built, it was just too big and the double row headers are not the friendliest of connectors to use. I didn't need all of the 80 lines of I/O provided by the 100 pin device, so I settled on the 48 pin part, offering 35 I/O lines, which was somewhat smaller, cheaper and more manageable in terms of pcb layout.





My solution was to create a 51mm x 19mm  double sided pcb, which mounts the STM32F303 microcontroller,  its clock and reset circuits and USB/programming connectors. This small breakout pcb, converts the pins from the 48 pin LQFP to an easier to use 40 pin dual in line module, and provide the minimum of features to get the STM32 to load and run code.  

This approach is not new and has been used in minimalist products such as the Maple Mini, Teensy and the Arduino Pro Mini and Nano, all of which have been around for some time.

I decided to name the board "ARMiGo" in respect to its user friendliness and I designed the ARMiGo to be as open and flexible as possible, so that it can be used as a core for incorporation into other designs.  The essential parts of that core are the microcontroller, the 8MHz crystal, the reset circuit, USB connection and programming header. 


The first of the prototypes arrived this week, and now working running some simple test code.

ARMiGo uses the STM32F303 Cortex M4 ARM device which runs at a maximum of 72MHz.  The pcb will also support the cheaper STM32F103 which is based on the M3 core and does not have such a rich mix of analogue peripherals.

The board is the same size as a standard 40 pin DIL format IC - making it ideal for breadboarding, and small enough to be used as a plug in module in a 40 pin socket, on a larger board.

All 35 I/O lines of the ARM chip are brought out to standard 2.54mm spaced headers.

The 5 pin right angle header on the left accepts the clock and data signals from the "ST-Link" programmer/debugger device.  These are available very cheaply from ebay/taobao/deal xtreme etc.
However it is relatively simple to use the embedded STM bootloader and program it via either the mini-B USB connector on the right or via one of the USART channels.

There is a really rich mix of on-chip peripherals, particularly analogue ADCs, op amps, comparators and programmable gain apmplifiers, which gives these small ARM parts tremendous flexibility - including the following:

Full speed USB interface on chip - no need for FTDI or equivalent

4  Fast (5 Msps)  12bit ADCs, each with up to 4 input channels

4 Programmable gain op-amps and 7 comparators

2  12 bit DACs

3   USARTS

3   SPI

2   I2C

RTC with 32768 Hz oscillator and dedicated output pin for "alarm"

10 timer channels,  2 basic,  6 general purpose and 2 advanced:5  General purpose  16 bit timer channels with up to 4 outputs for PWM generation, timing, counting etc.

1 general purpose 32 bit counter/timer - for optical encoder reading etc

2 advanced 16 bit timers for complimentary PWM generation etc.

In addition, the analogue section of the IC contains programmable gain op-amps and comparators which feed the ADC channels, and can be used to replace external analogue circuitry.

This small 48 pin packaged part contains 128KB of Flash and 40KB of SRAM - of which 8K can be battery backed up when the rest of the IC is powered down.

In the attached picture, most of the lower row of pins is the analogue I/O, and the upper row is mostly digital, although there are many options for allocating the peripheral functions to different pins.

With 5MHz 12 bit analogue interfaces it offers greater resolution and much faster sampling speed than Arduino. Additionally the 72MHz clock and 32bit wordsize will all make for a much faster data thoughput.

The combination of 35 I/O lines, on chip USB and a user friendly module, should make ARMiGo the starting point for a wide variety of new projects. Prototypes can now be breadboarded or easily built on stripboard, and the module just plugged straight in.

If you want more details about ARMiGo - please drop a comment.  I expect to release the upated EagleCAD files shortly.

Sunday, May 11, 2014

SIMPL Revisited

SIMPL

SIMPL stands for Serial Interpreted Minimal Programming Language.

It provides a quick means of programming microcontrollers for I/O interaction, using short text strings.

What this means is that a block of code or function can be invoked by sending a single serial character. Text strings are interpreted, character by character, to produce a complex program flow.

A few characters typed in to the serial terminal can be used to set output ports, read inputs or create accurately timed, complex sequences of I/O interaction. Operations can be chained together, stored in RAM and given a single uppercase alpha identity, which when typed will execute the whole sequence of instructions.

SIMPL is an interpreted language, which although this gives a minor speed disadvantage over compiled code, is fast enough for most experimentation - but to it's advantage, massively increases interactivity with the code.  Commands are easily retyped, modified and re-executed immediately, without having to go through the edit - recompile - reload process, which even on the Arduino slows down iterative development to every couple of minutes or so.

SIMPL builds up an interactive programming environment, the framework of which can be re-used from project to project, either for debugging, experimentation, or interacting with the microcontroller with the minimum of overheads.

The Arduino is essentially a serial connected device, as are many other microcontroller dev-boards, and as a simple, low overhead means of controlling the micro from a serial terminal program SIMPL provides a framework onto which more elaborate applications can be built. Blocks of code can be exercised in turn using serial commands, and debug sent to a terminal.

At the heart of SIMPL is an interpreter written in Arduino (or other microcontroller) using standard C code - for ease of portability.  I have recently ported SIMPL to the 32 bit ARM STM32F407, STM32F303, and the 16 bit MSP430 in order to illustrate it's versatility.

SIMPL is an ongoing project that was inspired by Ward Cunningham's Txtzyme interpreter.  If you want to learn more about Txtzyme - here's the link, and the Txtzyme Github page, where you can download the Arduino sketch version of Txtzyme. If you are new to this, it's worthwhile playing with Txtzyme, and studying the interpreter code to get a better understanding of it's operation.

For more background on SIMPL - please look at my blog posts from May 2013 onwards - starting here.

The Interpreter

At the centre of SIMPL is the interpreter, derived directly from Ward Cunningham's Txtzyme, which is just 90 lines of code.  It is a series of switch/case statements contained within a loop.  ASCII characters are allocated a function, which is executed by a small block of code, and then program control is returned to the main loop, to fetch the next character.

The original Txtzyme interpreter handles the following commands:

0-9    Numerical characters are enumerated to a 16 bit integer variable x
{}     Code within the braces is executed repeatedly controlled by a loop counter
m      A blocking delay of 1 millisecond
u       A blocking delay of 1 microsecond
p       Print the value contained in variable x to the serial terminal
_ _    Print the text contained within the underscores to the serial terminal
d       Allocate a digital port pin
o       output to the allocated port pin
i        read input from the allocated port pin
s       read the analogue input
k       A variable which is decremented on each iteration of the loop


Txtzyme interprets a character into an action, and that action may be controlled using a single numerical 16 bit integer parameter x.  It is the equivalent of passing an integer variable to a function in C code.

Numerical characters are enumerated into a 16 bit integer x.  The value of x is used as a control parameter for the next instruction. For example

100{}    this sets x to 100 and then repeats the commands within the braces 100 times

10m       this sets up a delay of 10mS before the next instruction is executed

13d        this allocates digital pin 13 as the one that will be handled by the next instruction

1o          Set logic high (output) on the previously allocated pin

0o          Set logic low on the allocated pin

So by combining these commands we can produce a simple LED flasher - on Arduino the LED is on digital pin 13

13d100{1o100m0o100m}  

Turn the LED on, wait 100mS, turn it off, wait 100mS and repeat this 100 times.

If however you wanted a very accurate on and off time, you could incorporate the u microsecond delay command into the above.

13d100{1o100m250u0o100m350u}

This sets the on time to 100.25mS and the off time to 100.35mS

As you can see, Txtzyme used a mix of lower case alpha characters and punctuation symbols as the instructions.  A Txtzyme interpreter running on any microcontroller, should be able to decode any string of these characters and produce the same overall action. This will give the language portability between microcontrollers. As there are only 26 lower case characters and 32 punctuation characters, this limits the scope of the language to something manageable. The alpha characters are chosen to act as mnemonics, so that the instructions are easy to remember.  This mix of lowercase alpha and punctuation characters are known as the primitives.

Txtzyme was great and a lot of fun to use, but I wanted to extend it into a more capable language, which allowed more than just a few I/O and printing operations to be performed.

I chose to add some arithmetic operators to Txtzyme, and in doing so added a second 16-bit integer variable - called y.

Then it became obvious that the ascii strings typed in via the serial terminal could be stored in RAM, and executed at any time.

I found a simple way of  allowing them to be addressed and executed, by using an upper case alpha character to act as a label to the address where the strings were stored.

This allowed the very short programs to be stored in RAM and executed just by typing a single uppercase character.  These characters could be concatenated, formed into loops, or called recursively from within Txtzyme strings. Whilst only 26 of these micro-programs were available, it is sufficient to build up some quite sophisticated operations - the sort of thing that could be used for teaching programming techniques to a young audience.

With the extensions I have added to Txtzyme, the program is still only about 260 lines of C code or just over 6.1k when compiled for the Arduino.

The main loop of SIMPL consists of just 3 functions:

txtRead
txtChk
txtEval

txtRead simply reads a character from the serial input buffer.

txtChk looks at the first character to see if it is a colon : and if so, writes the remainder of the text buffer to an area of RAM, with the store address based on the value of the uppercase alpha character that follows the colon. This takes case of colon definitions.

txtEval is the heat of the interpreter. It does one of three things:

It takes each character in turn, if it is a number it forms a 16 bit integer which it stores in variable x.

If it is a lower case alpha or punctuation character, it looks it up in a switch/case structure, and executes any code associated with it.

If it is an uppercase alpha character, it transfers the attention of the interpreter to the area of RAM addressed by that character, and continues to interpret characters from there.

I have deposited this latest version of SIMPL at this Github Gist  It compiles on Arduino 1.0.4.

FYI

There have been a few minimalist interpreted languages over the years, one notable example Mouse, was developed to operate within the acute memory limitations of an early minicomputer, intended for electronic music composition on a PDP-8. If you want to delve deeper - the full Mouse history is here.

Monday, May 05, 2014

A little more shifty....

Recap

In the previous post, I quickly reviewed the techniques for interfacing shift registers to Arduino based hardware and highlighted some simple code for reading and writing to the external shift registers.

Whilst to some, this may have appeared to be a whistle-stop tour, there is however a wealth of similar information available online and I felt that it would have been of little overall value just repeating the excellent examples and documentation provided by others.

Instead I wanted to get something up and running quickly which would extend the Arduino and act as the basis of a variety of projects, requiring additional input output devices such as LEDs, switches, and actuators such as stepper motors and hobby servos.

I am using the SIMPL language to control the shift registers.  If you have not come across SIMPL yet - please see my related blog post, and those going back to May of 2013.

Output to Shift Registers

With my recent experiments with shift registers, I wanted to send a 16 bit word out to a pair of output shift registers to selectively illuminate an array of LEDs.

In SIMPL, I chose the lower case ascii character "r" to represent this output to register function using the following Arduino code:

      case 'r':            // Send an 16 bit byte to the shift register using shiftOut
   
      PORTB &= ~_BV(0);
      shiftOut(dataPin, clockPin, MSBFIRST, x,8);      // shift out the high bits:
      shiftOut(dataPin, clockPin, MSBFIRST, x);        // shift out the low bits:
      PORTB |= _BV(0);
      break;

To use this function, you need to supply the 16 bit integer x immediately preceding the r character,

so 0r will turn off all the LEDs and 65535r will turn them all on.

Light Chasers

These are very simple to set up just by turning on the LEDs in a sequence. SIMPL is ideal for this.

We have a SIMPL command "r" which does a 16 bit write to the pair of shift registers.

128r will turn on LED 7, 64r will turn on LED 6 and so on.  We can use the millisecond command m, to keep the LEDs lit for, say 100mS.

128r100m64r100m and so on.

So let's define a LED sequence that counts down from the left - ie moves to the Right. We do this using the colon to start a definition - called R

:R 128r100m64r100m32r100m16r100m8r100m4r100m2r100m1r100m

And similarly a LED sequence that moves to the Left

:L 1r100m2r100m4r100m8r100m16r100m32r100m64r100m128r100

Now you can use L and R to make chase sequences

10{LR}  - 10 iterations of the Left-right chaser sequence

Stepper Motors

From creating a moving light chaser display, it is a very simple step to controlling the motion of a stepper motor.  Rather than turning the LEDs on in a sequence, it is simply a matter of energising the windings of the stepper motor in the correct sequence.

The hardware we will use is available cheaply on ebay, and consists of a small unipolar 5V stepper motor with 64:1 reduction gearbox, and a small circuit board that contains a power driver IC (ULN2003) and usually 4 LEDs.

The stepper motor coils are energised in the following sequence for forwards motion. This sequence of 8 steps is known as a half step sequence :

1
1 and 2
2
2 and 3
3
3 and 4
4
4 and 1

So let's code these into a number sequence that can be sent to the shift register and driver.

1
3
2
6
4
12
8
9

Now let's define a Pause statement, so that we don't have to keep changing the 100m delay when we want to change speed.  100mS may be OK for testing, so as you can see what is going on, but for the real miniature stepper motors, this delay should only be about 1mS.

:P  1m

Now let's code these numbers into definitions F, for Forwards and B for Backwards

:F 1rP3rP2rP6rP4rP12rP8rP9rP

:B 9rP8rP12rP4rP6rP2rP3rP1rP

So we can now use a sequence of F or B to provide forwards or backwards motion

512{F} will produce one complete turn of the motor shaft, because there are 512 steps to a full rotation of the gearbox shaft, and each iteration of "F" produces 4 steps.

At the end of each sequence t might be wise to send a 0r - in order to turn off all of the windings whilst the stepper is idle.

There are other sequences of coil energisation, which are used, sometimes when more torque is needed. A useful link here.

step-fig-3-1.gif (5087 bytes)


step-fig-4-1.gif (10593 bytes)

Input from Shift Registers

To complement the output command q, I wrote a short function to read the input shift registers. Command "t" is used to test the input registers and put the resultant value into x.

In order to display the value x, you need the print command p.  So the following construct was used

tp   test the input register and print the value to the serial monitor

tq   test the input register and display the value on the output LEDs

The code behind the "t" function is as follows:

     case 't':     // test the inputs from 74HC165 shift registers
   
      digitalWrite(loadPin, LOW);
      digitalWrite(loadPin, HIGH);
      x = shiftIn(sinPin, sclkPin, MSBFIRST);  // Read incoming word from 74HC165
      digitalWrite(sclkPin,HIGH);
   
      break;

In the next part, I'll be looking at the high power TPIC6B595 and using it to control a pair of stepper motors using SIMPL.



Friday, May 02, 2014

A little bit shifty

Experimenting with Shift Registers and Arduino

Shift registers are probably the least understood class of devices used in microcontroller and hardware design, yet they are central to so many common interfacing techniques, so I thought I would spent a few evenings getting to know how to use them.

There are some very good online tutorials regarding the use of shift registers, so I will not try to improve upon the wealth of good material that is already available, instead I will attempt to document some of my recent findings, in the hope that someone finds it useful. Everyone can type Arduino and shift register into Google and come up with a whole bunch of useful information.

My experiments have been done with an Arduino, or rather a low cost clone that uses the ATmega328P microcontroller, but could equally be applied to any other microcontroller, as the firmware is written in C or C++.

Here are 10 facts about shift registers that make them very useful.

1. They convert serial data to parallel, and parallel data to serial.
2. They can be easily chained together, generally 8 bits at a time to make longer wordlengths.
3. They are cheap and readily available - about £0.30 for an 8 bit shift register.
4. They can be used for storing data
5. They are used in UARTs for serial communication
6. They are used in I2C and SPI interfaces
7. They can be used to extend the simple I/O capabilities of small pin-limited microcontrollers
8. They can come with power drivers stages for driving lamps, relays and stepper motors
9. They are ease to wire up, using few pins and easy to control with simple firmware
10. They often form the basis of many segment LED drivers

I will be looking at some very common types:

74HC595  - this is the ubiquitous 8 bit series to parallel shift register, used for outputing parallel data. It requires just 3 pins on the Arduino to control it, and can be chained together to make much larger word sizes. It is available as a breadboard friendly 16 pin DIP, but also as compact SOIC, TSSOP and QFN packages.  As a HC device is is compatible with both 3V3 and 5V logic and can be powered from 2V to 6V. Each output can supply 20mA - which is ideal for driving LEDs with a suitable series resistor. Available from several manufacturers the world over. Datasheet here

74HC165 - this performs the complimentary function to the '595 which is parallel to series conversion. It also requires 3 pins to drive, can be chained to make larger word sizes and is very often used to provide additional input lines on small microcontrollers. These are very useful for reading switches (such as DIP switches used for configuration), or any other parallel input data. Again the HC logic allow a wide range of supply voltages, and available in a 16 pin DIP or several other compact packages.  Datasheet here

TPIC6B595 - this is an 8-bit serial to parallel shift register followed by a DMOS power driver stage, capable of 500mA of drive. It can be used for driving higher current, inductive loads directly such as relays, solenoids and small stepper motors. Available as a 20 pin DIP (or smaller) package, it can be used to replace the popular combination of a 74HC595 followed by a ULN2803 octal darlington driver.  If you are short of pcb space - this device is worth considering.  About £1 each in 10 off quantity.  A typical application would be driving a "fruit machine" where a few hundred lamp drivers are needed. Datasheet here

If you follow the links to the datasheets, you will see that 2 of them are via the Sparkfun site, showing the popularity of shift register devices amongst hobbyists. Indeed, shift registers are available on breakout boards and Arduino Shields, like this 48 Channel Output shield that uses six of the 74HC595 devices.

My experiments are slightly less ambitious. I decided to breadboard two 74HC595 devices and two 74HC165 devices to make a 16 bit output LED display, and a 16-bit switch input in order to expand the capabilities of the Arduino. Additionally I wanted to explore the use of the TPIC6B595 device as a means of driving a pair of small stepper motors - as the basis of some robotics and automation projects.

Wiring Up

74HC595 Output

Connecting a pair of shift registers on a breadboard to make a 16 bit word size is fairly straightforwards - here is a circuit from a French tutorial. It has nice clear diagrams of the breadboard layout too.

You will need 3 spare pins on the Arduino, referred to as latch, data and clock.  If you use the Arduino ShiftOut() function, these can be any three spare pins, but I chose to use 8,9 and 10 in order to leave 11,12 and 13 spare for future SPI work. If you follow the tutorial above and the code example provided it is very simple, and you will be up and running in no time.

I wanted to speed up the time that the latch signal was present, so in order to lower the latch I substituted the usual digitalWrite() function for the direct port command

PORTB &= ~_BV(0);  // This lowers digital pin 8

and to raise it

PORTB |= _BV(0);      // This raises digital pin 8

Doing this small code change allows the shift register to be updated at about 8000 times per second.


74HC165 Input

Wiring this up was also fairly straightforward.  Again you will need 3 lines to control the shift registers. I used digital lines 5,6 and 7 - again to avoid the SPI pins.  Again this  French wiki provides nice neat circuit diagrams in EagleCAD format.  However, I used pull down resistors, rather than pull-ups, and I used the Arduino shiftIn() function.  At first I noticed some very odd behaviour, where the register appeared to be multiplying the input number by 2. I had had a past experience of this, and realised that it was caused by clocking on the wrong edge of the clock.  This was easily corrected by making sure that the clock line is raised after the shiftIn(), so that it idles in the HIGH state, not the low state.

Code

Now we look at the code to combine the reading of the input shift registers with writing to the output registers. First we need to define the 6 various pins that carry the control signals:

   int sinPin = 5;            // Serial input pin from 74HC165
   int sclkPin = 6;          // Clock pin to 74HC165
   int loadPin = 7;         // Parallel load pin of 74HC165  
   int latchPin = 8;        // Pin connected to ST_CP of 74HC595
   int dataPin = 9;         // Pin connected to DS of 74HC595
   int clockPin = 10;     // Pin connected to SH_CP of 74HC595

and then within setup() - set them up as INPUT or OUTPUT

    pinMode(d,OUTPUT);
    pinMode(loadPin, OUTPUT);
    pinMode(sclkPin, OUTPUT);
    pinMode(sinPin, INPUT);
    pinMode(latchPin, OUTPUT);
    pinMode(clockPin, OUTPUT);
    pinMode(dataPin, OUTPUT);
    digitalWrite(sclkPin,HIGH);    // initialise the clock HIGH


Once you have set up the pins it's just 4 lines of code to read the inputs

// Read incoming word from 74HC165

digitalWrite(loadPin, LOW);
digitalWrite(loadPin, HIGH);
int incoming = shiftIn(sinPin, sclkPin, MSBFIRST);
digitalWrite(sclkPin,HIGH);

and 3 lines of code to write to the outputs

// and write it out to 74HC595

PORTB &= ~_BV(0);
shiftOut(dataPin, clockPin, MSBFIRST, incoming);  // shift out the bits:
PORTB |= _BV(0);

This sketch is available in full at this Github Gist

Once the signals have been defined and initialised, the code to read and write to the registers is really very trivial.  Whilst I have used the shiftIn() and shiftOut() functions provided by Arduino, these functions are also fairly simple and can readily be substituted for routines that directly control the I/O pins - if additional speed is needed.

In the next part I will look at how this shift register functionality can be incorporated into real applications such as stepper motor driving.


More Information

Nick Gammon's tutorial on using the '595

Nick Gammon's tutorial on using the '165

These outline using the shift registers with the SPI bus. This is the next step if you need the fastest speed data transfer.

The flawed Arduino tutorial - do not connect the 1uF capacitor there!! It's supposed to be a 100nF capacitor across the 5V and 0V power pins!















Saturday, March 29, 2014

Further Wanderings in Low Power Land

Introduction to Low Power

On this Arduino Day 2014, I thought I would investigate very low power operation of the ATmega328P-PU.

With low power and low energy battery powered devices becoming the norm, the desire to run the microcontroller on low voltage, derived from a coin cell or single AA cell is becoming increasingly popular. Some microcontroller manufactures, including Atmel, Silicon Labs and Holtek have identified this need for "single cell operation" and have built a simple boost converter into their device. Others - particularly, EM Microelectronic, have a core, the EM6682 that will actually run at 0.9V.

So we are going to see a proliferation of low power microcontroller solutions, and as a preliminary investigation into what was to come, I thought I'd explore the performance of a very common micro, as used in all Arduino Unos - the ATmega328P-PU, one of Atmel's PicoPower range.

This post is inspired by Nathan Seidle's Spark Fun post of 2011 "Adventures in Low Power Land".

Nate wanted to get a ATmega328 to run at the lowest possible sleep current whilst used in a digital watch application.

Now typically, an ATmega328P running code at 16MHz will draw about 7mA at 3V3, and whilst asleep, with almost everything turned off, Nate's investigation showed that 1.0uA operation was feasible.

I wanted to explore the territory between these two extremes, and determine whether there were other "safe havens" of operation, which could be usefully be exploited for low power applications.

I wondered whether by a combination of low power techniques it would be possible to run the Arduino at a greatly reduced clock speed, and at a lower voltage, and still have the microcontroller  running code and communicating via the UART.

Please note that this investigation is entirely experimental.  Several of the ATmega peripherals will no longer function at low voltage and low clock speed - in particular the ADC.  Also it should be remembered that just turning on an LED is going to consume many times more microwatts than just the microcontroller running code.

Getting Started

My initial experiments involved using  the prescaler on the external 16MHz crystal oscillator. On the standard Arduino Duemillenove with ATmega328 16MHz, the brown out detector is set to 2.7V. With this setting, a supply of 2.8V and the prescaler set to give a 62500Hz clock, the current dropped to a more reasonable 750uA.  This was a modest first effort, as even at less than 1mA, a coin cell is only going to last about a week.

I then decided that the 16MHz oscillator was always going to be power hungry, so I followed Nate's example and configured the device as an Arduino Pro 3V3 8MHz using the internal 8MHz oscillator.  I also turned off the Brown Out Detector (BOD) because I soon realised that this would prevent the IC running at low voltages.

I divided the 8MHz internal clock oscillator using the maximum prescaler value of 256. This meant that the code was executing at 31250 Hz, or 1/512 of the usual execution speed.

By setting Serial.begin(76800), I was able to get 300 baud communications from the new divided clock frequency.

BOD Alert!

There have been a number of cautionary tales about disabling the BOD, which could lead to corruption of the flash memory, but as this was entirely an exercise in pushing the device to investigate it's lowest limit of supply voltage and current, I accepted that there may come a point where I could no longer guarantee code integrity.

So I disabled the BOD, and the current started to creep down, first to 450uA, then 300uA. I then remembered the post in Jeelabs, about how the MCP1702 regulators start to draw large amounts of current when the supply voltage falls below their minimum LDO point.

So after I removed the MCP1702 regulator and set up a 2.0 V supply, the current dropped massively, remaining close to 100uA.  I then wondered if I could lower the supply to closer to 1.8V and see what current consumption would result.

I quickly learned that the CP2102 serial adaptor was supplying current to the application via the Rx line. The greater voltage on the Rx line leaks through the input protection diodes on the Rx input and contributes about 80uA - which caused the super capacitor to charge up!  I disconnected the Rx line, to ensure that subsequent measurements were accurate.

A rather poor, unregulated supply made from a potential divider on the 5V supply from my CP2102 cable, allowed me to get a datapoint at 1.8V, where the average current was close to 60uA.  The individual characters sent from the UART at 300 baud, were clearly visible in the current measurement.

Unfortunately, I didn't have access to a variable low voltage power supply, so I charged up a 0.22F super capacitor and ran the ATmega from this, monitoring the voltage and current drawn, via the voltage drop across a 1000 ohm resistor in the +ve supply lead, as the super capacitor slowly discharged.  Here are some voltage and current way-points during the discharge - it really highlights how dropping the supply voltage reduces the power (microwatts) drastically:

Volts        Current             Power

3.30V       450uA              1485uW
2.50V       100uA              250uW
2.00V       70.5uA             141uW
1.95V       64.7uA
1.90V       62.5uA
1.85V       61.3uA
1.82V       60.0uA
1.80V       58.9uA             106uW
1.75V       57.6uA
1.70V       55.6uA
1.65V       53.9uA
1.60V       51.1uA
1.55V       48.2uA
1.50V       44.5uA             66.75uW
1.45V       39.8uA             57.71uW
1.44V       38.7uA           - Dead!

Current consumption shoots up after 2.5V!
Power / uW in red also increases dramatically
As can be seen from the graphs - Low Power Land is definitely entered below 2.0V supply voltages!

Using this method I was able to show that code was still running at 1.71V supply and 55.8uA average consumption - printing serial to the terminal every second or so.

At 1.68V supply the CP2102 would no longer correctly receive characters - although the ATmega was still sending them - but at a much reduced amplitude.

So the ATmega328P-PU will still run code at 1.45V  consuming about  58 microwatts of power.

Later in the evening, I realised that it was my CP2102 serial adaptor cable Rx input that was giving up at 1.7V, and failing to read the very low voltage signals from the UART.   I continued to monitor the ATmega UART output with the scope running code right down to a supply voltage of 1.43V and 39.5uA of current. The ATmega328P-PU was actually running on 56.5 microwatts of power.

If you are concerned about disabling the BOD, then assume that the minimum safe supply voltage is stated as 1.8V in the datasheet, for clock frequencies below 4MHz. Set the BOD to this lower limit and accept that you can run the IC at between  60 and 100uA, depending on clockspeed and what peripherals you have enabled.

Applications

So why is this important?  It means that we can have very low power consumption from Arduino based hardware, making it compatible with Bluetooth low energy. A simple interrupt from the BLE module can wake the '328 to whatever clock frequency is needed to handle the RF data.

Additionally, it allows new power sources to be developed, such as energy harvesting devices, or even a small 3" x 2" photovoltaic collector, illuminated by ambient lighting is sufficient to power the microcontroller.

Clearly their will be a compromise between fast and slow clocking, and a combination of spending long periods asleep, and waking up to run at high clock speed, may be more advantageous than plodding along at 31kHz. It's definitely a tortoise and hare situation, and the overall winner is likely to be highly application dependent.

Photos and more detail to  follow.




Saturday, March 22, 2014

Clarity of Vision

A simple serial port graphing program helps debug high speed sensor data.

This week, I have been debugging a high speed 24-bit ADC, connected to an STM32F303 ARM microcontroller. Unfortunately my usual arsenal of debugging tools were starting to creak under the strain. Here I discuss existing methods, plus a new approach which will be of interest to the hobbyist/Arduino community.

The Old Fashioned Way...

With any microcontroller project, during debugging, it is essential that you have the tools available to get data in and out of the micro so that you can see what's going on. Often this may just be a UART link to a serial terminal program which allows you to print out results and enter serial commands to control the application.  Frequently, when I start with a new microcontroller, I use a simple framework program that provides the serial link with basic functions such as

putchar(x);            // Prints the ASCII character of x, sends x to the uart transmit buffer

print_num(x);       // Prints x as an integer

getchar();            // checks to see if there is a character waiting in the uart receive buffer

Now putchar and getchar  are as old as the hills, and have been associated with character input and output - probably before C was even thought of.  They may be as simple as testing for a uart flag to be set, and then writing or reading the uart tx or rx registers, but once you have these working, and can get characters in and out of your application program, then debugging becomes a whole lot easier. With just putchar you can do hex dumps of memory, send data to a file or even make a very simple realtime horizontal bargraph display - handy if you are looking at time varying analogue data.

My framework program often uses getchar and a switch/case statement to select different modes of working. One example this week was being able to control the sampling and averaging of an ADC that I have been working on, just by sending a single ASCII character to the microcontroller.

Another good technique is to set up a timer channel to count milliseconds. This establishes a time framework to your application program.  By reading the millisecond counter, it becomes easy to co-ordinate tasks at given times, say once every 10mS, or once a second, and also to print out the millisecond count at each end of a task - to see how long it takes.

Fairly early on in your developments, you will want to start testing the I/O pins. One technique is to toggle an output port line each time you enter a given routine, this might drive a LED or better still connect a scope probe and use an oscilloscope to time the event. If you are going to be laying out a pcb for your next project, it is very worthwhile to break out some of the spare I/O pins, to say a 2.54mm header, which gives you something to clip a scope probe onto, or use jumper leads to a temporary array of LEDs. Modern microcontroller packages are very small, and the pins are not easy to probe individually - so break a few spare pins out - so you can get at them easily.

This week, I have been debugging a high speed 24-bit ADC, connected to an STM32F303 ARM microcontroller. Not only does this involve high resolution data, but it is output at high speeds, which makes seeing what's going on a little challenging.  The particular ADC would be producing 24 bit readings at approaching 20kHz, and data sent at 921,600 baud. Whilst a terminal program, in this case RealTerm would be a start, it's very hard to visualise what's actually happening with streams of hex digits scrolling up the screen at an alarming rate. Clearly a new approach would be needed.

The project involves reading very small changes in voltage signals - down to fractions of microvolts, and as such it is essential to have good analogue design, and use precision low noise components. I found a good application note from Linear Technology, which describes most of the techniques in detail. If you are interested in high resolution analogue datalogging, and low noise analogue techniques - this app-note is well worth a read

Unfortunately, electrical noise is a fundamental property of the universe we live in, so minimising noise to the point where it no longer interferes with your ADC readings, is quite a challenge.

The ADC and microcontroller are mounted on a small pcb, along with voltage  regulators, op-amps and an RS232 driver IC. Whilst RS232 might appear a little old fashioned, it is a robust way of communicating between instruments over moderate distances.

The microcontroller produces a 1MHz clock for the ADC, and every 8uS, the ADC interrupts the micro, to announce that it has another reading ready.  The micro then reads the ADC using SPI, does some quick calculations on the readings and then passes the results out through the serial port for analysis on a PC.

This might appear simple enough, until you realise  that even with some data averaging, the readings are being sent to the PC every 50uS, or 20,000 readings per second, and to achieve this, the UART has to run at 921,600 baud, nearly a megabit per second.

Visualisation of Your Data

During the debugging of this project some simple tools have been invaluable to capture the data, and allow visual analysis on a graphical display. By turning the ADC sample numbers from the sensor into a "scope trace" display I could see in real time what was happening.

SimPlot - A Simple Serial Plotting Program

After a quick search, I came across a program,  SimPlot  (downloadable here) This has been developed within the Arduino community, and allows up to four channels of data to be plotted against time, like an oscilloscope display. A few lines of code will produce the 16 bit integer data in the format needed by SimPlot, and it is very easy to use. The screenshot above shows one channel of data being captured from an Arduino at 115200baud, where the ADC input has been left floating.  SimPlot allows you to set both the number of samples in the horizontal axis, and also the range displayed in the vertical axis.  By choosing a certain sample rate, and setting the horizontal scale accordingly, it is possible to determine the frequency of the displayed waveform - in the above case it's just 50Hz mains hum.

Fortunately, SimPlot will handle high baudrates, and just typing in 921600 set it up correctly and I was soon able to view the amplitude of my data, noise and all.  It is so much easier to see what is happening with a realtime trace, than to try and look at reams of hex data, or capture the data to a file and analyse later using plotting programs such as KST.

As microcontrollers become more sophisticated, and often within the hobbyist community, they are now used to read advanced analogue sensors, such as accelerometers and gyros, having a 4 channel display of analogue data like this is an absolute god-send. You can see in real time the changes in the signal, it's sensitivity to changing external parameters, such as temperature, and monitor drift and noise.

24 bit ADCs - what's available.

24 bit ADCs are now becoming more widely available, at an affordable cost.  Most of the recent developments have been with the Delta-Sigma converters, which have an internal architecture that suits high speed digital signal processing and efficient translation into silicon. As a result Delta-Sigma converters tend to be cheaper and more widely available than the more traditional successive approximation (SAR) converters.

However, Delta-Sigma converters are about a magnitude slower than the SAR converters, max sample rates of about 10,000 samples per second, and as you sample faster, the weight of noise increases, so that a 24 bit converter, might only return about 17 noise free bits at 4kHz, rising to 20 bits at 2kHz sample rate.

Nevertheless, there are some good Delta-Sigma converters, and the LTC2440 from Linear Technology is a good representation of what is available.  There has been some work done within the Arduino community on this device, and a link to a report on its performance whilst being read by an Arduino is here.

These converters are available for about £11 (Farnell) - but you will need a TSSOP adapter pcb in order to make use of them. They don't exactly lend themselves to breadboard prototyping either.

The resolution of a 24 bit converter is such that if we chose a 5V range, then the voltage represented by a single count would be 298nV - or approximately 0.3 microvolts.  Compare this to the 10 bit converter on the Arduino, where the smallest voltage step is 4.88mV,  or 16384 times larger.  However this resolution is somewhat theoretical, and not really achievable in practice. Most Delta-Sigma converters are used at very low sampling speeds, often below 10Hz, in applications such as weighing scales.

Successive Approximation converters can convert much quicker, and the AD7767 I have chosen for my project can produce a maximum of 128,000 samples per second.  The conversion rate is controlled entirely by the clock frequency you supply it with, up to a maximum of 1.024MHz. A new conversion is available every 8 clock cycles.  Currently I am clocking it at 800kHz, in order to achieve 100,000 samples per second.  These are averaged down, so that a new result is available every 8 samples - or 12.5kSps, or if you only wish one sample, then these can be output at 20KSps - which is limited by the speed of the RS232 interface.



Sunday, March 16, 2014

Joining the Dots .......

In the Beginning..

In the early 1960s, Digital Equipment Corp, were contracted to build a system to control and monitor certain processes at a Canadian nuclear power station which would convey data back to a mainframe computer. One of the young hardware engineers, Gordon Bell, came up with the proposal, that rather than building a one-off, custom digital control system from their digital modules, that they should build a small and low cost programmable 12 bit computer. It's programmability would make it more flexible, and, as a general purpose product, could be sold to other customers. Thus the DC-12, later the PDP-5 was conceived. It was the fore-runner of the PDP-8, which was the first true minicomputer, benchtop sized and a major commercial success for DEC.

The idea of using a small computer to perform specific tasks, whilst interfaced to a larger machine was not entirely new.  Seymour Cray had developed the CDC-160 back in 1960, again a 12 bit machine, reportedly designed over a 3 day weekend!

History indeed repeats itself, as some forty years later, the Arduino team first designed their product to be an input/output board, which would interface with a desktop or laptop machine, running Processing. The easy to program Arduino could be connected to analogue and digital signals and make these available to the laptop for controlling or graphing, in a way that previously had been a lot of hard work. Either you needed to be an embedded specialist, with a register level knowledge of programming microcontrollers or use proprietary software.

It's now 10 years since the creation of the first Arduino, and this will be celebrated around the world on Arduino Day, March 29th.  Whether you love or loathe Arduino, you have to accept that it has introduced a whole generation of youngsters to open source technology, and some of them are destined to become the programmers, developers, designers and entrepreneurs of tomorrow.

Arduino is just one of the ways in which technology has been opened up - a process that began about 25 years ago, with the creation of the World Wide Web, and followed by other notables including Linux, open source software, Android and open hardware, trailblazed by Arduino, and followed by many.

I recall that 25 years ago, when I started my career, that a genuine IBM PC cost the equivalent of about 5 months wages, and you could spend a similar amount on the software packages to run on it.  Now you can purchase a tablet machine for a few hundred dollars, and we have come to accept that a lot of the software is bundled into that price, or open source, free and downloadable from the web.

In my opinion, it is this democratisation of technology that has brought about the rapid developments we have seen over the last 5 years.

On a hardware front, 32 bit ARM devices are competing in price with 8 bit devices.  $5 will buy you a lot of processing power,  or $10 or $12 will buy a dev board that is Arduino compatible. The open source GCC compiler and a free, unrestricted IDE can be downloaded.  So for a few dollars, you have more computing power than that 1985 IBM PC or the 1964 PDP-5, which back then cost $27,000, at a time when a new Mustang would be $2000.

Other drivers of this technology revolution include wireless communications and improved battery technology.  Devices will become smaller, smarter and run for years on low cost batteries.  The SmartPhone can provide a common interface for controlling household technology, such as channel hopping on the TV, when you can't find the remote,  programming the central heating controller, or selecting the correct program on the washing machine.

All of these applications are on convergent trajectories, powered by open source technology which is now accessible to the hobbyist.


Quick Hack - Arduino with Bluetooth Low Energy



This week, the nRF 8001 module arrived from Olimex. These are available for around $14 and take just over a week to ship from Bulgaria.

In order to connect it up, I used a "bare bones" Arduino like board of my own design, that runs at 3.3V This is important, as the nRF8001 IC from Nordic Semiconductor will not withstand 5V.  The board is simply an ATmega328, a 16MHz crystal, reset circuit, a 3V3 regulator and a 6 pin header for a FTDI cable.

The nRF8001 module from Olimex is breadboard friendly, and once having soldered a couple of headers to the underside, it can be mounted in a breadboard.

In the middle is the nRF8001 IC, with the 16MHz crystal above it. To the left is the low power 32kHz crystal, and to the extreme right of the  pcb is the L-shaped pcb trace antenna.  Another 22 surface mount passive components complete the design.

The close up above shows how just 8 jumper wires are needed to connect it. The top header connects 3.3V, 0V and Reset, and the bottom header connects MOSI, MISO, SCK and two handshaking signals REQN and RDYN on digital pins 9 and 8 respectively.  These are used to synchronise the transfer of data between the ATmega328 and the nRF8001.

Once I had downloaded the latest Nordic Semiconductor nRF8001 example sketches and Library from Github, and loaded the nRF UART app from the Google store (Apple version also available), it was very quick and easy to get the example running.  Within a few minutes I was able to type ASCII characters into the phone and have them appear on the Arduino serial terminal window, and vice versa.

Other example code allows the phone to control the various ports on the Arduino remotely over the BLE link.  Once connected the nRF8001 uses only about 600uA average current, whilst the ATmega uses about 7mA!

 



More ARM Adventures





Update 28/03/2014.

An excellent online book "Discovering the STM32 Microcontroller" by Geoffrey Brown is now available.  This comprehensive, up to the minute text leads the beginner through the main techniques involved in writing applications, and interfacing hardware devices to these increasingly popular microcontrollers. Communications with serial, SPI and I2C are covered, also interfacing to a colour LCD, a SD card and a Wii Nunchuk.

In an earlier post, I described how 32 bit ARM microcontrollers are now making substantial inroads into applications previously hosted by 8 bit micros.

In order to get started with ARM devices, I decided to make a minimalist breakout board for the STM32F303, which has an ARM Cortex M4 core. This has a floating point unit and additional DSP instructions making it quick for math intensive code.

The STMF32303 has a maximum clock frequency of 72MHz, but has several low power modes where it can be clocked from a low frequency internal clock source.  This is important for battery powered devices,  where battery life may be an important issue.  At 72MHz, I measured the current consumption at 35mA from the 3V3 supply.

One of the biggest challenges to the ARM newcomer, is understanding the vast menagerie of on-chip peripherals and how to initialise them.  Once this is mastered, programming becomes as simple as any other microcontroller.

Arduino manages to make the task of programming easier, by providing a few memorable C++ functions, which take care of basic I/O operations, effectively shielding the user from the minutiae of bit manipulation at register level.  It is this hardware/register abstraction layer which makes programming the Arduino so much simpler for beginners.

There is no reason why these user friendly functions cannot be recreated on the ARM. So if you prefer 

digitalWrite(1,HIGH);

Instead of 

GPIO_SetBits(GPIOA, GPIO_Pin_1);

then this is perfectly understandable, and a lot less typing.  Abstracting complex functions to simpler, easier to remember commands is definitely the way to introduce newcomers to programming.  I'll cover more on this in a future blog-post.

For those wishing to remain within the Arduino comfort zone, Leaf Labs has produced an Arduino "look-alike" IDE for their STM32 based Maple, and Maple-mini products.  However, most of their IDE developments have been restricted to Linux platforms, having abandoned the PC as a platform a couple of years ago.

Peripherals

The STM32F303 has a rich set of peripherals including USARTS, Timers, SPI, I2C, ADCs and DACs. Additionally it has programmable gain op-amps and comparators which can help reduce the amount of analogue circuitry needed in an application.  There is also a capacitive  touch-sensor interface allowing user controls to be implemented easily on the pcb.  Almost all of the I/O pins are multi-function, and getting to know what is available where is one of the hardest tasks when first getting started with the ARM.

On the ARMiGo board, I have tried to simplify this by primarily putting the analogue interface signals along one side of the pcb and the digital signals along the other, but a closer inspection of the datasheet will show that further pin-swapping between functions is possible.

ST Microelectronics provide a comprehensive set of "wrapper" functions to assist the user in the process of setting up the peripherals. Ultimately these functions set the individual bit patterns in the peripheral control registers, but abstract a lot of this low level bit manipulation from the user.

In the same way that Arduino has a setup() function where most of the hardware initialisation is performed, I chose to have a separate file, which I call periph_config.c, where I put all of this setup code, and a single function Init(), called from the start of my main code, which calls the relevant functions in periph_config so as to initialise the hardware. It's then an easy matter just to change periph_config when you need a slightly different hardware configuration.

It would be relatively straightforward to automatically generate the periph_config file from some sort of GUI. Here the user would select the various functions needed and the file would be automatically generated.

Applications

ARMiGo is intended to take over when the Arduino just runs out of steam.  It has a 72MHz maximum internal clock frequency, provided from an 8MHz crystal that drives a phase locked loop. So raw speed is available when necessary, but using the clock divider, the 8MHz clock can be divided down to a plodding 125kHz, when much lower power is needed. In this condition the ARM will consume around 1mA.

Full speed USB is available on-chip, and STM have provided source code for CDC, virtual com port VCP and other USB profiles.  As well as being able to communicate directly over USB, as a slave device, with a PC or other device acting as host, all of the STM32 family have an embedded (factory programmed) bootloader which allows firmware to be programmed into the device directly from USB. This is known as DFU - device firmware upgrade.

For communicating with other devices, the STM32F303 has 3 USARTS available, plus SPI and I2C interfaces. In a recent application, I have sent data to a PC using one of the USARTs, at 921,600 baud, whilst using the SPI bus to take readings from a 24 bit ADC (AD7767) at 125kHz sampling frequency. One of the timer channels provides a 1MHz clock signal for the ADC.

The STM32F303 also has four individual 12 bit ADCs, which can sample at 5MHz. Each ADC has a front end multiplexer, allowing up to 4 analogue signals to be read from each ADC. This opens up interesting applications in energy monitoring, or as a low cost multifunction test instrument.  The excellent Miniscope project is based on the STM32F303 - be sure to watch the video of the arbitrary waveform generator - which uses one of the 12 bit DAC channels.

The STM32F303 has up to 35 I/O lines available, making it a little more flexible than Arduino or other ATmega328 boards. However, it should be appreciated that it is a 3.3V part, and whilst the digital I/O lines are 5V tolerant, the analogue ones are not.  This comes as a mixed blessing, as it can interface directly with newer 3V3 devices without the use of level converters, but caution is needed when using in a project that has mixed supply voltage logic.

ARMiGo is a low cost/low tech product to get people started with ARM. Whilst many other boards use ARM devices, the ARMiGo tries to remove to remove the clutter and provide direct access to all ports and peripherals, in an easy to use, plug in module.



Monday, March 10, 2014

ARMiGo - A breakout board for STM32F303 ARM Microcontrollers



As integrated circuits get smaller, and more powerful, it becomes increasingly difficult for the hobbyist to utilise them easily. Soldering tiny SMT parts is a challenge for many - but an amazingly useful skill, once mastered.

32 bit ARM microcontrollers are now virtually the same cost as older 8 bit devices, yet offer a many fold increase in performance, as a result of their 32 bit architecture and faster clock speed. In addition to this, they come with a rich set of peripherals, making them ideal for more demanding applications.

For the hobbyist who may have first gained exposure to microcontrollers via 8 bit products such as the Arduino, the move to 32 bit may appear a little daunting.  However we all have to progress and keep up with the times, and so now the time has come to move up to the "big school".

For a particular microcontroller to gain traction in the hobbyist community, it has to meet a few basic requirements:

1.  Low cost development boards
2. Free to use, open source toolchain
3. Lots of online code examples, projects, forum support
4. Support from a vibrant user community
5. Easy to use and incorporate into projects
6. Easy to upgrade to different devices from within the same microcontroller family


1.  Low Cost Hardware

After some investigation, and triggered into action by exceptionally low cost development boards, I have settled on the ST Microelectronics STM32F range of microcontrollers as being the basis for future projects.

These micros are already being used extensively in a range of hobbyist boards including Maple, Netduino, Olimex, Expruino, mbed, MicroPython and STM's own range of very low cost Discovery boards, which are priced around the range  ($11 - $18).

A recent offering from mbed in collaboration with ST is offering boards for as little as $10, and come complete with a detachable ST Link programmer, which can be used for programming other boards.

These boards are now available from suppliers including Farnell, Newark,  Mouser, Digikey.

Low cost hardware is the new trend, with dev kits often being sold at close to cost price,  so, gone are the days when you forked out £20 for your first Arduino, and then another £20 when you wanted to build it into a more permanent project.

2.  Open Source Toolchain


Free to use toolchains are nothing new. Microchip realised in the 1990's that they would sell more chips if they made the coding tools free. Fortunately the ARM microcontroller is supported by GCC, and there is a free to use IDE,  called CooCox CoIDE, which supports a wide range of ARM chips from several main manufacturers.


3. Lots of Online Support and Code Examples

Getting started with ARM chips is as easy as dowloading the free tools, installing some drivers and learning the basics from a wide range of code examples easily found online.  The STM32 range of microcontrollers have been available for about 4 years now, and so there is a rapidly growing resource of online code examples, reference designs and supporting documentation. ST Microelectronics produces a firmware pack for all of its evaluation and Discovery boards, and this is a good place to start for code examples. Other online examples,  which are easily Googled, are downloadable from repository sites such as Github amongst others. YouTube is also a good place to search for STM32 projects. As the processors are considerably more powerful than 8 bit devices, they are often used with LCD colour displays, and there are several examples of these on YouTube.

4. A Large User Community.

All popular devices build up a loyal user community and the STM32 is no exception.  The popularity is driven by low cost hardware and free tools, and is ever expanding as new products based on the STM32 are released.  Again a simple Google search will often turn up a blog from an enthusiast who has already covered a lot of ground and is happy to share it. 

5. Easy to Incorporate into Projects.

This is where things are not so clear-cut.  The problem with most dev boards is that they are either too big, or use header pin layouts that are incompatible with breadboard or stripboard.  This can be a major inconvenience, and often force the user to buy some form of shield for mounting other hardware expansion, or resort to using female/male jumper leads, so that the headers can be jumpered into a breadboard. Either way the result is not ideal, and a rat's nest of jumper wires is neither permanent nor easy to work with.

6. Easy to move between devices in the STM32 family range.

There are now a considerable number of devices in the STM32Fxxx family, based broadly around the Cortex M0, M3 and M4 ARM architectures. Whilst to the newcomer the range of different parts may seem confusing, STM have designed the family in such a way which makes it relatively easy to move between parts.

The first thing to realise is that they are all microcontrollers, with on chip SRAM, and only the larger packaged parts will support external memory.

Secondly, all parts share identical, or very similar I/O and peripheral architectures, so if you are using USART , or Timer 2 on a 48 pin pack, you will find the same peripherals, and more, in the 64, 100 and 144 pin packages.

Thirdly, you will find that you can switch between family members - because they share common pin-outs. This means if you have designed a pcb for a 48 pin STM32F103, and you want to move up to the STM32F303, then you will find all the ports, clock lines and power pins are exactly the same - so no pcb changes are needed.

Here are some guidelines to selecting a part:

1.  How much I/O will my application require?  The GPIO ports are 16 bits wide, and devices are made with between 2 and 8 ports.  The 48 pin package provides 2 ports PortA and PortB,  the 100 pin package provides 5 ports PortA - PortE.

2. Choose the appropriate amount of flash memory and SRAM.  The smaller parts have 128kB of flash and 32kB of SRAM. The largest parts have 2MB of flash and 256k of SRAM.

3.  Choose the Cortex family member.  M0 is the cheapest with the slowest clock, and generally without USB. M3 is a good starting point with a 72MHz clock and on chip full speed USB.  M4 is similar to M3, but supports clock speeds up to 180MHz and has a floating point unit (FPU) which may be useful for intensive maths code such as used in robotics and flight controllers.

Getting Started.

Initially I bought a Discovery F3 development board, which uses a 100 pin STM32F303 processor and has  compass, accelerometer and gyro devices on the board. It was exceptionally good value at under $11 from Newark.  However, whilst it provided a platform to get me started writing code and getting the framework to support my application built, it was just too big and the double row headers are not the friendliest of connectors to use. I didn't need all of the  80 lines of I/O provided by the 100 pin device,  so I settled on the 48 pin part, which somewhat smaller, cheaper and more manageable in terms of pcb layout.

My solution was to create a 51mm x 19mm  double sided pcb, which mounts the STM32F303 microcontroller,  its clock and reset circuits and USB/programming connectors. This small breakout pcb, converts the pins from the 48 pin LQFP to an easier to use 40 pin dual in line module, and provide the minimum of features to get the STM32 to load and run code.  

This approach is not new and has been used in minimalist products such as the Maple Mini and the Arduino Pro Mini and Nano, all of which have been around for some time.

I decided to name the board "ARMiGo" in respect to its user friendliness and I designed the ARMiGo to be as open and flexible as possible, so that it can be used as a core for incorporation into other designs.  The essential parts of that core are the microcontroller, the 8MHz crystal, the reset circuit, USB connection and programming header. 


The first of the prototypes arrived this week, and now working running some simple test code.

ARMiGo uses the STM32F303 Cortex M4 ARM device which runs at a maximum of 72MHz.  The pcb also supports the STM32F103 which is based on the M3 core.

The board is the same size as a standard 40 pin DIL format IC - making it ideal for breadboarding, and small enough to be used as a plug in module in a 40 pin socket, on a larger board.

All 35 I/O lines of the ARM chip are brought out to standard 2.54mm spaced headers.

The 5 pin right angle header on the left accepts the clock and data signals from the "ST-Link" programmer/debugger device.  These are available very cheaply from ebay/taobao/deal xtreme etc.
However it is relatively simple to use the embedded STM bootloader and program it via either the mini-B USB connector on the right or via one of the USART channels.

There is a really rich mix of on-chip peripherals, which gives these small ARM parts tremendous flexibility - including the following:

Full speed USB interface

4  Fast (5 Msps)  12bit ADCs, each with up to 4 input channels

4 Programmable gain op-amps and 7 comparators

2  12 bit DACs

3   USARTS

3   SPI

2   I2C

RTC with 32768 Hz oscillator and dedicated output pin for "alarm"

10 timer channels,  2 basic,  6 general purpose and 2 advanced:5  General purpose  16 bit timer channels with up to 4 outputs for PWM generation, timing, counting etc.

1 general purpose 32 bit counter/timer - for optical encoder reading etc

2 advanced 16 bit timers for complimentary PWM generation etc.

In addition, the analogue section of the IC contains programmable gain op-amps and comparators which feed the ADC channels, and can be used to replace external analogue circuitry.

This small 48 pin packaged part contains 128KB of Flash and 40KB of SRAM - of which 8K can be battery backed up when the rest of the IC is powered down.

In the attached picture, most of the lower row of pins is the analogue I/O, and the upper row is mostly digital, although there are many options for allocating the peripheral functions to different pins.

With 5MHz 12 bit analogue interfaces it offers greater resolution and much faster sampling speed than Arduino. Additionally the 72MHz clock and 32bit wordsize will all make for a much faster data thoughput.

The combination of 35 I/O lines, on chip USB and a user friendly module, should make ARMiGo the starting point for a wide variety of new projects. Prototypes can now be breadboarded or easily built on stripboard, and the module just plugged straight in.

If you want more details about ARMiGo - please drop a comment.