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.








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




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.




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)


A "Maple Mini" - a low cost STM32F103 board from China
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.


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 Hackers Survival Kit was an idea that simultaneously occurred to me and Les Pounder @biglesp - me stranded in Greece for 2 weeks, with my brain idling, and Les thinking about a combined Hacker's blog where they contribute details of their minimal means to provide a hacking environment. Just the essentials for a Hacker's Toolbox, to help teach physical computing and coding to newcomers.

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....
On the menu...

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.

Saturday, July 25, 2015

First steps coding and speed testing the STM32F746 Break Out Board



It's a few days since I received my prototype STM32F745 Breakout boards and I have slowly been writing some basic firmware functions to test out the hardware.

Whilst I have done a fair bit of code development for the STM32F4, F373 and F103 microcontrollers, this was my first exposure to the awesome Cortex M7.

Every programmer wants to create a comfortable coding environment around any new microcontroller platform, and often this is done by porting familiar routines across to the new target and re-using tried and tested libraries in order to develop the application.

With a few basic functions, you can do a surprising amount - here's one approach

digital input and output - flash a LED to confirm code is running
serial USART - allows text output and a simple command interface from PC
timers - by establishing a millisecond and microsecond tick you have precision timing
timers also allow pwm to be generated
ADCs - 12bit or even 16bit resolution measurements become possible
SPI  - connect to SD-Card,  Colour TFT LCD, etc
I2C - add an eeprom
RTC - and battery backup.  The STM32F series often have on chip RTC and non-volatile RAM

The Arduino project has done this time and again for the various microcontrollers used on their boards - proving that code originally written for an AVR, can be ported to various manufacturers ARM processors.  The STM32duino project has gained a fair amount of traction porting the Arduino environment so that it will run on STM32F1xx  M3 and STM32F4xx M4 processors.

The Arduino language successfully removes much of the complexity, or possibly quirkiness, from the C programming language, and at the same time creates a robust application framework onto which the hardware specific functions and libraries may be placed.

Purists, or old-school C programmers, may delight in criticising it's oversimplification of the language, but for beginners or those that have had no exposure to traditional C and C++, it's a fast way of getting simple applications running - and now with the benefit of moving between a range of more capable processors.

Tool Chain

I found that I could download a codesize limited (32KB) version of the Keil ARM-MDK, which runs under their uVision 5 toolchain. This was the easiest route to take, as it includes all the library headers, and numerous examples of how to configure the various on-chip peripherals.

If you are familiar with the STM32F  Standard Peripheral Libraries,  then this may be a mixed blessing.  STM have ported their functionality across to their new Hardware Abstraction Layer HAL, under their new development suite known as STM32 Cube.

There is no question that STM32 Cube will provide faster development for complex applications, as it combines graphical libraries, ethernet and TCP/IP stacks in an integrated design environment. However, the initial barrier to learning enough about HAL to reach the point of understanding it's various structures can be quite high, leaving the user somewhat perplexed that what should be easy, turns out to be really quite a challenge.

Once over the HAL Hurdle - progress will be much quicker.

Get it Running

The usual route to getting a new board up and running is to start with the bare minimum of code to prove that it will actually run.  Traditionally this is normally a simple LED flashing routine.
With the STM32 series of microcontrollers - and any 32bit mcu, for that matter, there is quite often a considerable quantity of registers to initialise first.

I started with the LED flash example, that came with the ARM-MDK download. It is often wiser to start with a known working example, rather than start from scratch, especially with an unfamiliar microcontroller.

As it happened, my problems were initially hardware related - as I had forgotten to connect the all-important analogue VDDA supply. Once this was connected, the microcontroller accepted code and sprang into life.  Without VDDA, the clock oscillator and the PLL blocks are not powered - so the mcu cannot run.

Once I had the LED flashing, it was time to check out the system timing, and make sure when you used the 100mS delay routine - that it was actually 100mS.  I had used an 8MHz crystal and so I had to change the PLL divisor ratio, in order to get the right timing, as the code in the example was for an EVAL kit - which used a 25MHz crystal.

Once this was done, I wrote the code to configure the GPIO pins so that I could toggle more of the I/O pins.

Next - USART

Basic GPIO is always the starting point for code development, but pretty soon you need to get a serial connection to a terminal program - so you can see numerical and text output plus the means of controlling the application with a simple command interpreter. With about 3 or 4 basic functions you can implement a surprisingly flexible user interface.

1.  putchar  - send a single ASCII character to the serial port.  This is the basis of all serial output.
2.  getchar  - receive a character from the serial interface
3.  print_num  - this will send an integer number to the serial interface
4.  Get_Serial  - a routine that accepts simple alpha-numeric serial commands for machine control

The USART proved somewhat trickier to implement, mainly because the HAL routines were somewhat different to the old STM32Fxxx_USART library code that I was used to. After a day spent failing to import the USART initialisation into my code, I decided to port my code into the HAL USART example - starting with a known working example.

This approach was a lot more successful, and soon I had printf(), putchar() and getchar() all working nicely.

Benchmarking the STM32F7xx.

Having got the first prototype running to the point where I could run code and get numerical output, I decided that it was time to run a standard benchmark test on it - so that I could compare it with other devices.

The dhrystone is the classic integer math benchmark that has been run on various computers for over 30 years.  A C code version (actually Arduino) of it can be downloaded from here

 http://www.saanlima.com/download/dhry21a.zip

Some months ago, I tested the standard Arduino MEGA, which uses an ATmega2560 running with a 16MHz clock.

The results were as follows

ATmega2560 16MHz

Dhrystone Benchmark, Version 2.1 (Language: C)
Execution starts, 300000 runs through Dhrystone
Execution ends
Microseconds for one run through Dhrystone: 78.67
Dhrystones per Second: 12711.22
VAX MIPS rating = 7.23


STM32F746 216MHz

Dhrystone Benchmark, Version 2.1 (Language: C)
Execution starts, 300000 runs through Dhrystone
Execution ends
Microseconds for one run through Dhrystone: 3.33
Dhrystones per Second: 300000
VAX MIPS rating = 170.74

So the STM32F7xx is approximately 24 times faster than the Arduino on integer maths. But when you look at the whole package:

1M Flash
320KB  SRAM
4 USARTS
USB full-speed
Up to 6 SPI
Up to 18 timers
etc, etc

The list of peripherals is most comprehensive.  Best check the datasheet for full details.

And all available in LQFP packages that the hobbyist can actually solder.

Conclusion.

This week I have made great progress getting the basics of a code development environment put together for the STM32F746.

The board was cheap and easy to build, with a record short development time of just 14 days from starting the pcb layout to first having the LED flashing, and so far all appears to be working as intended.

This is certainly a powerful processor, and with the right coding environment, such as Arduino or mbed will make a great little target for those wanting to move into 32bit  ARM bare metal programming.








Wednesday, July 22, 2015

How Ragworm helped me create a STM32F746 breakout board in under 2 weeks

EagleCAD Layout


Last time I described how ST Microelectronics had finally released their long awaited STM32F7xx series of ARM Cortex M7 microcontrollers, and how, conveniently for the hobbyist, that a device was available in a 100 pin LQFP package.  All that was needed was a suitable break out board so that the new device could be evaluated and built into cool projects.

The Solution

The solution was to design a simple breakout board, and so the idea of BOB - the STM32F746 break out board came to fruition.

I wanted a fairly rapid turn-around on this board - so without delay I set about the CAD design - commencing after lunch on Tuesday July 7th.

Mini-Projects like this can be undertaken quickly and cheaply by the hobbyist  by using free to use (eg KiCAD, EagleCAD) printed circuit design tools that run on all common platforms.  An idea can readily be turned into a real pcb and a real design with the use of these tools plus the relatively recent online pcb manufacturing services offered by a number of companies.

Previously, I had looked at some of the very low cost pcb services - like SeeedStudio Fusion pcb - which is a Hong Kong/Shenzhen based outfit which will offer very economical pcbs - provided that your design will fit into a 5 x 5cm or 10 x 10cm board size. Outside these board formats, things become a lot more expensive. In addition, overseas shipping charges from mainland China, may cost more than the actual pcbs. Whilst these services will deliver very cheap pcbs - it may take 3 weeks or more from sending the files, to getting the boards in your hand.

Fortunately, there are a number of local suppliers in the UK, who have set up services aimed specifically at the hobbyist and prototyping marketplace. They offer typically a 10 day turnaround for 2 layer, plated through boards.  Provided that your design rules are not too extreme - and you are happy with a minimum track and gap size of 6 thou, and a minimum drill of 0.5mm then these services are fast and economical.

The Design.

The schematic design took an afternoon, as I had to create a new symbol for the STM32F746. Another half day of pushing tracks around and the layout was nearly finished.

This is an easy board as boards go - as the dual row header connectors are almost an exact 1:1 match to the pin-out of the 100 pin LQFP mcu package.  I just had to add the crystal, RTC backup super capacitor and the connectors for connecting FTDI and USB.

It was then a case of finalising the board layout in EagleCAD and then sending off the gerber files to a local pcb manufacturer.

The Sting

Departing from my supplier of over 10 years, who had become increasingly expensive, and had recently made a number of manufacturing errors and delivery cock-ups, I decided to move my business elsewhere and choose a new pcb supplier.

The Worm

This time I chose Ragworm, based in Kent, whom I had had recommended by a number of fellow open source hardware enthusiasts, in particular Glyn Hudson at Openenergymonitor - who regularly uses them for his designs.

The Ragworm operation is one part of a small family run firm, with a traditional pcb manufacturing operation, that has developed an online service specifically aimed at the needs of hobbyists or those that need a small quantity of  economically priced pcbs.

Ouch!

I first checked my existing supplier's prices,  5 off, 2 layer pcbs size 66mm x 66mm on a 10 day turnaround. The price came back at £92.66 - however this is not the full story - once you add 20% VAT and £10 for shipping we have a bill of  £121.19.

By contrast, the Ragworm online ordering process is a breeze - just enter the X and Y dimensions of the pcb and the quantity required, upload the zipped gerbers and the price you see, is the price you pay. In the case of the Bob board  the grand total was £81.02 - a saving of just over £40.  This  33% saving was such a no-brainer, and with the payment process handled by PayPal made the whole process very quick and easy.

The order was placed on the morning of Thursday 9th July, and at all stages of the process, I was kept updated by email by one of the team at Ragworm.  On the afternoon of July 16th, I was informed by email that my pcbs were to be dispatched that day - barely a week after I sent the order. A 10 day service turned around in only a week!

One of the ways in which Ragworm keep their shipping costs down, is by using UK 2nd class post. This is not the fastest service - but under the circumstances it was not a problem, and my boards arrived on the morning of Monday 20th July.

The freshly minted board back from Ragworm

The bare boards were exceptionally well made, with good definition both of the tracking and the screen printed legend.  In talking with Stacey Driver at a local Raspberry Pi event, I found out that this is because they were using a better type of white screen printing ink - that gives better clarity.  It stands out well against the orange background. Whilst these boards use ROHS compliant HASL (hot  air solder leveling) this is ideal for prototype boards  - making them easy to solder by hand.


The next challenge was to make up the pcb to the point where it would run code.  This involves soldering down the processor, the crystal, a voltage regulator and a few decoupling capacitors and connectors.  The picture above shows the minimum build of the board. Not fitted at this stage were the boost regulator (to allow operation from a Li Ion battery) and the USB components.

The board has been designed to provide a STM32F7  equivalent of the STM32F4 Discovery board. This means that almost all of the 80 or so GPIO lines are brought out directly to the dual row 50 way header connectors underneath the board.  For those familiar with the F4 Discovery board - this is a very close copy - with the important interfaces unimpeded by additional hardware. The only thing missing is the ST-Link programmer section - but if you already have a Discovery or a Nucleo board, you can use this to program and debug the board.

Initial Testing.

The FTDI cable provides a source of 5V to power this board - as well as a serial debug port.  The on board 3V3 regulator provides a source of VDD and VDDA.  Remember to connect VDDA - otherwise the PLL and clock circuit will not work, and your board will appear lifeless.

A single orange LED, connected to PC13 shows that there is life.

I had hoped to use mbed to program this board - but their compiler (at the time of writing) does not yet support the STM32F7. Instead I downloaded the 32KB codesize limited version of Keil's uVision 5 - as this provided all the toolchain and libraries that I needed.

After hacking their blinky example - so that it uses PC13 instead of PI1, I very soon had the orange led winking at me - and with the fundamentals of the pcb proven to be working, it was time to get down to some more serious code development.

I hope to use the STM32 HAL libraries to give "Arduino-like" functionality to this board. Additionally, I am recutting the Bob design onto a n Arduino MEGA compatible footprint. This will be the subject of a future post.

In the spirit of open source hardware - if you you would like the EagleCAD design files for the STM32F746  BOB board - you can find them here.  Unfortunately I cannot offer any assistance at this stage with firmware, except for the most simple of Blinky code.

The next blogpost will have more details of how I managed to get some simple firmware running on this board - plus some speed tests - relative to the Arduino.

If you are in the UK, please consider using Ragworm for your latest pcb projects.



From Ragworm - with Love :)


Thanks to Stacey, Stephanie, Adam and all the pcb staff at Ragworm, who turned this mini-project around in record quick time.

Ragworm can be found at the following site: http://www.ragworm.eu/ and also have Twitter presence @ragworm




Saturday, July 11, 2015

At last - The STM32F7xx a 216MHz ARM Cortex M7 core for the hobbyist

ARM core microcontrollers have made significant advances over the last few years, and last week saw the commercial release of the STM32F746 - an ARM Cortex M7 core that runs at 216MHz.

With this newly released microcontroller, we now have the means to make a very fast "Arduino".

At the same time as releasing the STM32F7xx range,  ST have made a low cost Discovery Board available.  This breaks with tradition over previous Discovery boards  and is very much all the bells and whistles needed to showcase the new F7 family.

It comes with a 4.3" capacitative TFT colour LCD, and some fairly sophisticated demo software.
In addition it has Ethernet, additional external SDRAM, NAND flash, audio interfaces, camera interface, microSD socket - and what little I/O is left is brought out to Arduino compatible shield headers!

You can read all about the new STM32F7-DISCO board here

More importantly for the hobbyist, the STM32F7xx part is available in a series of LQFP packages - which whist still quite a challenge to solder to a pcb - is not as impossible as Ball Grid Array BGA packages - which need to be machine placed and reflow soldered.

The STM32F746 is available in 100, 144, 176 and 208 pin LQFP packages.  The three larger sizes have additional GPIO ports, and are ideal if you want to drive an LCD using 8 bit RGB parallel data. However, I chose the 100pin package - to keep it simpler for the hobbyist.

I have been using the smaller packages of M4 ARM for about 18 months, and was keen to upgrade to the M7 and at least evaluate the 2X performance increase and the faster I/O.

My current application is particularly I/O intensive - so I needed unhindered access to all the pins. It is a multi-axis motor control board and as such needs 4 quadrature decoders - for rotary position sensing. It also needs 4 USARTS, USB, and complementary PWM for driving two dc motor H-bridges.  There is a user interface consisting of a small (2.8") colour TFT display driven by a SPI bus, 5 user buttons and a scroll wheel encoder - for menu item selection. Further inputs from sensors and safety limit switches mean that virtually all of the 80 I/O lines are  committed.

Having read the datasheet, I found that the 100 pin LQFP package is not quite pin compatible with the STM32F407 Cortex M4 device.  ST Microelectronics have chosen to add another power pin, and as a result, shifted 30 of the I/O pins one place to the left.  (The other 70 are in their original locations). This was going to need some board modifications compared to my M4 designs - but then I had the idea of  making a simple Break Out Board, which would be pin header compatible with the STM F4 Discovery Board.

Whilst the new STM32F7-DISCO board is a superb showcase for the new F7 microcontroller - the lack of free GPIO and access to peripherals made it too limiting for my application - so I decided to bite the bullet and make a very simple dev board - with every signal broken out to pin headers.




Anyone familiar with the F4 Discovery board will see that this has the same pin headers. The ST-Link section of the board is not present - as it is assumed that the user will already have a ST-Link or other means to program the board.

On the left is a mini-B USB connector which will power the board, and the mcu can run USB VCP firmware to communicate with a PC. In addition USART 1 and USART 3 are broken out in the form of FTDI compatible headers.  USART 1 can be used to bootload firmware onto the board - which I  have conveniently included RESET and BOOT switches for this purpose.  All STM32F devices (and virtually all manufacturers ARM core devices come with a factory bootloader, to allow for some simple means of programming).

In addition to a 5V supply, the board uses a MCP1640 boost regulator - and can run on voltages down to about 1V. This allows the use of LiPo or even alkaline cells to power the board.

The board is fitted with an 8MHz crystal for the main oscillator - with an on-chip PLL that synthesises the main clock at 216MHz, and a 32768Hz watch crystal for the Real Time Clock. There is also an 0.22F supercapacitor to maintain the RTC registers and the non volatile RAM.

The STM32F7xx offers a performance increase of approximately 2.2 over the previous F4 series.  It has built in display controller - so ideally suited to driving LCD panels in parallel mode. The larger LQFP packages (144, 176, 208) are ideal for direct drive of LCD panels using 8 bit RGB. There is 128K extra RAM and an external memory interface  - over and above what the F4 offered.

Costing.

Digikey, Farnell/Newark and Mouser hold stock of the STM32F746VGT6 100 pin  microcontroller.

It's one off price is about $17.75 or  $16.16 in 10 off

The 66 x 66mm pcb could be sourced from low cost board manufacturers for about $2.20 in 10 off quantity - such as SeeedStudio PCB service

So for about $25 outlay  - you could have a very capable 216MHz ARM board which can ultimately be programmed with open source tools - such as GCC, Arduino, Python, Javascript etc.

Final Impressions.

The STM32F7xx range represent the current state of the art in ARM devices to be used stand-alone in microcontroller mode- without the use of an operating system.

They contain a very rich mix of GPIO and periperals, plus the ability to drive a colour LCD - for applications where a modern user interface is needed.

At the same time, you have full access to the I/O ports - allowing you to drive I/O at up to 108MHz  - which makes for a very versatile real time controller - to interface with sensors and actuators.

USB and ethernet is on-chip (but the ethernet will need an external phy device).  ST Microelectronics provide a library of standard peripheral firmware and USB plus TCP/IP stack to allow these devices to be used to maximum advantage.

Whilst this device runs at better than 200MHz - it is only a single core device.  It is not in the same league as the 900MHz 4 core Raspberry-Pi 2, nor should it be considered to be.  It's more equivalent to a high speed Arduino Due, than a low end Pi.

The difference is that a hobbyist skilled at soldering can make and repair one of these for themself, and use it as the basis of new designs, whereas the Pi, relying heavily on BGA devices is well beyond the scope of amateur construction. The breakout board shows that you can still put a microcontroller, but a fast one, down onto a simple pcb, with crystal and reset circuit, and a serial USART connection, and with minimum effort using opensource programming tools have it up and running code.




Saturday, May 23, 2015

Using Piano Forte with the Espruino Javascript Interpreter

Piano Forte - with ESP8266 WiFi and HM-11 Bluetooth Low Energy 


In the last few weeks, a few things have come to light that make working with the STM32Fxxx series of ARM microcontrollers a lot more fruitful.

Espruino - JavaScript On-Board

The Espruino project, which provides a JavaScript interpreter for several of the STM32F ARM devices has blossomed and matured, giving a whole host of new powerful functionality and the benefit from the immediacy and interactive nature of an interpreted language.

Also - there is now a large user base for Espruino, and a forum offering help and guidance for the newcomer - as well as code examples.

As the standard variant of Piano Forte uses virtually the same microcontroller as the Espruino board - (they are both STM32F103 with 256K of flash and 48K of RAM), it's just a case of downloading the latest code image from their site and programming it in using the STM32 bootloader utility.


Making Connection

Espruino uses the STM full speed USB com port driver, but if there is no USB plugged in, it defaults to USART1 which appears on PA9 and PA10.  This is useful for testing - as it allows you to get a board up and running with just a FTDI or similar serial cable.  The serial baud rate defaults to 9600 baud - but this is intentional, because it allows a Bluetooth module - such as the HM-11 to be used directly for programming and communicating with the Piano Forte.

The Piano Forte was also designed to be an I/O board for the Raspberry Pi.  The Pi can be used to send the javascript text across to the Piano Forte - again at 9600 baud - using it's UART pins (8 and 10) on the GPIO connector.


The FTDI  is debug cable connected via USART1 - this also has access to the serial bootloader

PA9      Tx
PA10     Rx

If the Piano is to be fitted to a Raspberry Pi - the FTDI cable is redundant and the USART1 is connected to the PI GPIO header via a couple of series resistors on the underside of the pcb.

Wireless Options

Piano Forte was designed from the start to allow various wireless connectivity options. These will be most useful when the board is intended for stand- alone operation - and not as an I/O slave for the Ras-Pi.

An 8 pin header is included on the pcb to allow the ESP-01 to be fitted.

The ESP8266 module is connected via USART2 which appears on PA2 and PA3

PA2  Tx
PA3  Rx

Additionally there is a footprint on the pcb which accepts the HM-11 Bluetooth module.

The HM-11 BLE module is connected via USART3 on ports PB10 and PB11

PB10 Tx
PB11 Rx

On the first set of prototype boards this will need a couple of wire links.

Friday, May 08, 2015

Interfacing a Chord Keypad to Papilio Duo FPGA Board

Five keys plus thumb operated shift/control key
This is a simple chord style keypad that I made up a few years ago.  It is loosely based on the Microwriter - an early UK designed portable keypad / notewriter.

The five main keys are located under the fingertips and thumb of the right hand, plus an additional shift key that can be held down with the thumb.  This combination allows up to 64 key combinations  - which is enough for simple ascii, alphas and numerals.

However, this time the application is not for text entry, but to allow very rapid access to menu items, tools and colour options for a CAD program - without having to break concentration and use the keyboard.

In the early 1990's, Charles Moore - the founder of the Forth programming language, devised a similar simple keypad, to allow him fast, direct and immediate control of his OKAD suite of VLSI CAD design tools. It means that all the frequently used options, for example the toolset in CAD, are immediately below your fingertips and accessible without remembering a series of keyboard strokes or moving the mouse off the working drawing area, to the menu bar, to select a new tool.

If this multi-keypad were combined with the position and scrolling functions currently provide by a mouse, then it would mean that a considerable amount of program interaction could be done from the "mousekey"  without having to take one's hand of the mouse to type at the keyboard.

Wiring Up

The keypad will interface directly into the Atari joystick port of a Classic Computing Shield that I purchased from Gadget Factory - as part of the Papilio Duo development kit. I am slowly developing a stand alone CAD workstation, based around a 32 bit soft processor running on the Papilio Duo FPGA.

The wiring is very simple - just 6 microswitches connected to inputs pins which short to ground when pressed.  The Computing Shield provides 47K pull-up resistors - such that the port lines will all appear high until a keyswitch is pressed. The wiring schematic is provided in the Computing Shield hardware guide



For the moment, the keypad inputs will have to be polled, but a little more logic - such as 6 diodes, would allow a further line to indicate an interrupt from the keypad - if any switch is pressed, the diode AND  (inverted logic OR) would bring the interrupt line low.

Decoding the key inputs in code is fairly simple - we assign binary weights to each of the key inputs, and then the unique combination of switch presses is the binary sum of these weights.

For example - assign a weight of:
1 to switch 1,
2 to switch 2,
4 to switch 3,
8 to switch 4,
16 to switch 5,
32 to switch 6.

If switches 1 and 2 are pressed together, the decoding returns a value of (2+1) = 3.

Some consideration was given to switch debounce - multiple sampling of the key-inputs until a stable, repeatable sum is achieved.

The keypad is first scanned to see if any key is pressed.  If there is, we wait for 30mS and scan again. We then wait a further 30mS and scan a second time.  If the first and second scans are equal - we know we can return with a valid keycode.

Why a Custom Keypad?

The keypad provides a simple and fast means of navigating and selecting a wide range of options from a menu.

It may be used for causing a quick change in operation - such as an original games controller.

It can also be used for text input - but this requires a bit of practice and learning the character set.







Saturday, May 02, 2015

Benchmarking Arduino - and his Chums.

Background

The standard Arduino based on the ATmega328 is an 8-bit device with a 16MHz clock frequency and 2K bytes of RAM.

I have for some time been exploring more powerful alternatives to the Arduino - especially the 32 bit STM32Fxxx ARM Cortex M4 range of microcontrollers, and some softcore processors implemented in a FPGA.

The one thing that these processors have in common is that they can all be programmed using the Arduino IDE - so in theory, code written for the Arduino will run on all devices -almost without modification.

The flavour of C++ used by Arduino has become a kind of lingua franca for these widely varying processors, allowing access to vast knowledge base and range of libraries that permit the easy interfacing of hardware devices. In truth, if you wish to use an integrated device or sensor, then someone will already have created an Arduino library for it.

Since the earliest days of commercial computers, both manufacturers and users have had a strong interest in their computing performance. Computers were expensive, and computing time was equally expensive. Any way of increasing performance and reducing programming costs was sought after. As memory technologies improved, processor cycle times reduced to match the shorter access time of the memory.

When launched in 1965, the PDP-8 was capable of 312,500 12-bit additions per second.  How does the Arduino compare with that figure?

Into Practice

The Arduino is a great platform for trying things out.  Whilst not the fastest board available, it's resources are easily accessible, and the millis() and micros() timer functions allow simple benchmarking to be done. 

Remembering the claimed performance for the PDP-8, I decided to set up a simple addition test for Arduino. First I formed an array of 16 bit integers - remembering that in the Arduino there is only sufficient RAM space for about 500 16-bit words. Exceeding this gives a risk of overwriting some of the stack, heap and system variables.

I then loaded up the array with random integers 

void setup()
{  
  Serial.begin(115200);
  
  for(int i = 0; i <=500; i++)
  {
  m[i] = random(0,65535);
  }  

}

The main routine would then add two of the memory locations together, working it's way through the array. The time taken for the 500 iteration function was calculated using the micros() function.

Results were as follows:

1. Adding a constant to memory    1uS
2. Adding contents of two memory locations into a variable   1.4uS
3. Adding  contents of two memory locations and storing back into a third memory location 1.6uS

So based on this, the Arduino is performing addition of  memory located operands at between 2 to 3 times the speed of the 1965 PDP-8.

However  - we should bear in mind that at 16MHz, the Arduino is executing approximately 16 instructions per microsecond.  Whilst an 8-bit add is a single cycle instruction, by the time we have used it within a 16-bit add routine, and involved a memory access, the Arduino is taking roughly a microsecond to achieve a common operation in a typical program.  

I then conducted the same test on the 72MHz STM32F103 board programmed using Arduino_STM32.

1. Adding a constant to memory    0.156uS    (6.4X faster)
2. Adding contents of two memory locations into a variable  0.294uS  (4.76X faster)
3. Adding  contents of two memory locations and storing back into a third memory location 0.32uS (5X faster).

Next was the turn for the 96MHz ZPUino - a softcore running in a Xilinx Spartan 6 - on a Papilio Duo FPGA board.

1. Adding a constant to memory    0.58uS    (1.72X faster than Arduino)
2. Adding contents of two memory locations into a variable  0.708uS  (1.39X faster)
3. Adding  contents of two memory locations and storing back into a third memory location 0.706uS (1.41X faster).

The skeleton Arduino code for these addition speedtests is available on this Github Gist

The results for the ZPUino were a little disappointing - bearing in mind it is being clocked at 6X the speed of the Arduino. However it is a stack based processor, which uses external RAM. The external bytewide RAM will slow down RAM accesses and perhaps C does not compile efficiently to its stack based architecture.

Whetstone and Dhrystone Benchmarks

One solution is to use standard benchmark code, of which there are several well documented programmes, designed to test the various performance aspects of the processor. These include:

Dhrystone  - an integer arithmetic benchmark
Whetstone  - a floating point benchmark
CoreMark - for multi-core processors
LinPak      - for Linux based systems

Dhrystone - a fixed point benchmark

The Dhrystone benchmark code - suitable for small microcontrollers is available here - however the Dhrystone caused some me difficulties in converting it to an Arduino compatible format - particularly because of the shortage of RAM on the ATmega328.

Fortunately, I was contacted by Magnus of Saanlima Electronics - with an Arduino friendly version. You will however need an Arduino MEGA - because the Uno does not have enough RAM to run this benchmark.

http://www.saanlima.com/download/dhry21a.zip

Results:

Arduino MEGA1260 board 16MHz

Microseconds for one run through Dhrystone: 78.67
Dhrystones per Second:12711.22
VAX MIPS rating = 7.23


72MHz STM32F103 programmed using Arduino_STM32 

Microseconds for one run through Dhrystone: 11.66
Dhrystones per Second: 85762.68
VAX MIPS rating = 48.81
I then ported it to ZPUino2.0  - and after a little fiddling got the following:
Microseconds for one run through Dhrystone: 37.95
Dhrystones per Second: 26351.79
VAX MIPS rating = 15.00


Whetstone - a floating point benchmark

The Whetstone test code adapted for Arduino by Thomas Kirchner is here
When run on a standard Arduino 16MHz Duemillenove the Whetstone produced the following result

Starting Whetstone benchmark...
Loops: 1000 Iterations: 1 Duration: 81740 millisec.
C Converted Double Precision Whetstones: 1.22 MIPS

On the STM32F103 board with a 72MHz clock

Starting Whetstone benchmark...
Loops: 1000 Iterations: 1 Duration: 19691 millisec.
C Converted Double Precision Whetstones: 5.08 MIPS

So the STM32F103 appears to be running at approximately four times the speed of the Arduino. This speed increase is dominated by the faster clock on the STM32F103, and not that the ARM processor is executing the compiled code any more efficiently than the AVR.

Whilst an indication of processor performance, the benchmarks are a somewhat artificial test, and the actual performance of one processor compared to another will depend on the application. Additionally, the manner in which the compiler interprets the C source code and efficiently converts it into the native machine language of the processor has an effect on the overall processing speed.


Conclusions

The 16MHz Arduino can execute real code at around 1.22 million instructions per second.

Moving up to a 72MHz STM32F103 ARM will give about a 5X to 7X speed advantage over the Arduino. A lot of this is down to the faster clock, and some down to the fact that double precision arithmetic will be easier (less cycles) on a 32bit processor than an 8 bit device

Soft core FPGA processors are interesting, but may be constrained by the use of external RAM and the restriction of an 8 bit external bus hen accessing multi-byte words. It must therefore be possible to improve their performance, with the used of internal (on chip) RAM.