Introduction: State Machine and Multitasking on Arduino With SPI Expanders


Last week, I was asking to create a system to pilot fireworks with an arduino. It needed about 64 outputs to control the fires. One way to do it is to use IC expanders. So 2 solutions are available:

- an I2C expander but it needs inverter when you power on the IC (see my previous instructable on finite state machine) because all the outputs goes quickly ON and OFF: a problem with fireworks.

-an SPI also easy to run and with no problem on the power on.

So I decided to studied this kind of expanders. I use also a state machine with multitasking to control digital 16 I/O and 2 analog outputs. This card is designed to control automation systems like a PLC.

I also studied the differences and the translation beetween the drawings of the state diagram and another graph heavy used in automation: the SFC (Sequential Function Chart) based on the former Petri nets.

Step 1: The Cards and the Circuits

I use an arduino uno and 2 types of DIL chips:

- the MCP23S17, 2 x 16 I/O expander controled with SPI

-the MCP4921, DAC 12 bits, 0/5V

Thes IC are very cheap and reliable and also very easy to link and program. On the schematics i used some additional components like decoupling capacitors, pull-down resistors for the inputs.

Step 2: The Program to Run a Multitask State Machine

The global idea is to control digital I/O and meanwhile launch a fade ON/OFF effects on LEDS connected to the both analog outputs.

Another thing, i do on purpose the separate connection of the CS pins (chip select) to have more possibilities to more IC on the SPI bus. So I used:

- a special library for the state machine

-a special library for the MCP23S17

-NO special library for the MCP4921, the CS and the SPI connection soft is "handy" done.

You can see on the pics the translation beetween the expected state machine and SFC (also called GRAFCET or gr7 in french). Some common terms: concurent states, multitask and encapsulation.

I provide the libraries and the source code with a lot of comments. To read and understand it, you must also read at the same time the state diagram or the SFC.

Step 3: To Conclude

It works!!

When you power up the system you DO wait few seconds and then use the expander (time to initiate the SPI bus).

The system has very quick reactions and you need to create a power interface card if you want to control whatever machine. See my previous instructables, It's very easy!!

Thanx to very interesting and working tutorials all over the world.