Battery Leakage Again
A recent purchase:
Battery Leakage Again
A recent purchase:
Finite State Machines and the Software Hammer
The firmware that runs the Casio FX502P gadget that I recently created has a structure and uses a technique that I though was worth documenting. The gadget uses the Arduino framework and is described in the following videos and blog entry.
This device has some tight timing constraints while performing interactions with a real-time interface. It cannot waste time deciding what to do next as it has a bidirectional synchronous bit stream to attend to at about 200kHz. The processor itself runs at tens of MHz so there's time for several instructions to run between clock edges, but not enough time that the code can perform time consuming operations.
As the protocol isn't officially documented I'd like to be able to change the interface behaviour to add new commands, remove commands and maybe alter some of the existing commands. The code needs to be easy to understand and change.
So, we have two requirements:
A. Code must run fast
B. Code must be easy to understand and not break if altered
These requirements, even if they don't officially declare war on each other, fight against one another. Code that is easy to understand and change isn't usually fast, and code that is fast isn't usually easy to understand or change.
Fast Code
One fast way to respond to inputs is to use interrupts. Something happens and a fragment of code runs. That's the basis of interrupts. If you have something simple then it's relatively easy to implement. A push-button, for instance, is a single input and an interrupt service routine (ISR) that runs when the input is either changed or at a certain logic level. (An interrupt that runs code when an input changes is edge-triggered, one that fires at a certain level is, well, level-triggered).
In the push-button example it's all straightforward. The push-button is pressed, the input changes level and the code runs. Whatever is needed to be done is done and the ISR exits. There are details that have to be attended to, such as using the volatile keyword (in C), we are more interested in the overall structure here than details.
For the FX502P gadget the interface has:
A clock line that runs at approximately 200kHz and clocks data on both edges
A data line, which is bidirectional
Two control lines, active high
A serial data format that uses packets of different lengths, including a longer packet that has a payload with start bit, stop bits,data and parity, which also gets clocked out on a different edge to the data clocked in.
We therefore have edge triggered signals, level triggered signals and have to collect and build packets of different lengths and formats. Suddenly it's all a lot more complicated than a push-button.
At the time of writing (and as this code is easy to change, it changes now and again), there are two interrupts, one driven from the clock and one from a chip enable (CE) control line. The complexity has just moved up a notch. There's now two interrupts that have to be handled. Fortunately in this case they cannot execute simultaneously, although the method I have used doesn't have problems if they do execute simultaneously (on different cores, for example).
Orchestration
So how can you create something that can react to interrupts and perform actions based on those interrupts? Not only react, but react in a way that has memory of what has happened in the past. For instance, if the clock changes state do we clock data in or out? We need to know if we are in the middle of receiving a packet or sending one.
In the gadget this is done with a Finite State Machine (FSM). It's a thing (Machine) that can be in one of a Finite number of States at any time. FSMs move between states when they receive an input (stimulus). (An FSM is always in a state, and changing from one state to another logically takes no time). There are many ways an FSM can drive outputs, in the one used here, a function is called when the FSMmoves to a new state. An action is taken on entry to a state.
When an ISR runs, it sends a stimulus to the FSM and that may causes a state change. Code is run when entering a new state, that code can do anything required at that time.
Implementation
There are several ways to implement an FSM. As the gadget doesn't have time to spare it uses nested switch statements. You can use a table driven approach but searching the table uses processor cycles and hence more time than a switch statement approach. Using a table, though, allows you to use a higher level of abstraction when defining the FSM. With the gadget I wanted a similar abstraction, but to achieve this I used what I call a 'software hammer'. The idea is to have an abstract description of what you want to achieve, in a form that is easy to understand and easy to alter, and support code that hides the details. This support code is 'hammered' into shape to support the abstract code and handle all the details.
In the gadget code, the nested switch FSM is the abstract part, the rest of the code is hammered to support that abstraction.Here's a fragment of the FSM code which shows the two nested switch statements:
sets up the length of the packet.
Then:
isr_send_flag = true;
indicates to the support code that a transmission is needed.
There's some other housekeeping stuff, because the universe requires it, such as the SET_DATA_BIT0 which is exposed here due to the timing of the interface. It can't be done later.
What is important is that the fact that the received data packets are clocked in on one edge of the clock while the transmitted packets are clocked out on the other edge is completely hidden at this layer of abstraction. That detail has been hammered into the support code.
Even though the details of the support code are probably horrible with lots of special case required by the interface, that doesn't matter once it works, as from then on it should only be necessary to change the abstract code when new packets need to be decoded or transmitted. The support code handles the interface, and that isn't going to change.
The whole of the FSM looks pretty much like these two pieces of code, although there are other things that need to be done, like this:
Notes
FSM State
The state an FSM is in is determined by it's state variable. Whatever number is in that variable is the state it is in. It can't be in two states at once and it take no time (logically) to update a variable's value.
DFSM
These FSMs are actually DFSMs (Deterministic Finite State Machines), which means that the state transitions are deterministic. Non deterministic state machines can also be useful, their state transitions can be random in some way. They are not that common, though.
Race Conditions
FSMs can be resilient against race conditions. If stimulii are queued and then processed then you can build your FSM to handle stimulii in any order and still get the correct behaviour. Every state should be examined to see what action it should take for every possible stimulus. It doesn't matter when or in what order the stimulii arrive, the FSM states will always take the appropriate action, and it won't miss stimulii as long as the queuing code is correct.
Casio FX-502P SD Card Gadget Prototype
A while back I made a gadget that attached to a Casio FX-502P via an FA-1 and stored programs and data on an SD card instead of a cassette .
https://trochilidae.blogspot.com/2017/06/fx502p-cassette-interface.html
It decoded the frequencies that the FA-1 sent to a cassette recorder and wrote the data to an SD card attached to an Arduino Due. I had to use a Due as it was the only combination of clock frequency and RAM that could keep up with the data stream coming out of the FA-1.
The advantage of using this approach was that the cassette interface was a well-known format and fairly easy to decode. The disadvantage is the bulk of the final package. To get the data onto the tiny little SD card you need the FA-1 cradle and the gadget. A few weeks ago I suddenly realised that I could cut down on a lot of the hardware needed by attaching a gadget to the expansion port on the top of the FX-502P. This would involve interacting with the protocol that goes over the expansion port, but that shouldn't be a problem. There's a lot of detail here about the expansion port of the FX-602P and FX-700P.
As a base for a prototype I used the Sharp PC-G850 gadget, using the Blue Pill processor and the OLED display. The expansion port signals are attached to the 11 pin Sharp interface connector on the gadget using a cable.
The protocol that the expansion port uses is a bit odd. It seems to be the bus that the processor in the calculator uses to talk to the LCD controller. It has a single bi-directional serial data line, a chip select, a command/data control line and a clock for the serial data. The data packets are of variable length, which makes it a bit hard to decode. Most packets are 6 bits long, there is one two bit packet and a 16 bit long data packet (holding an RS232 type character format that encodes a single byte of data. The clock edge that the data is latched on is different for transmitted and received data. And the data is inverted logic (0 is 3V and 1 is 0V, not forgetting that the calculator uses 3V as it's 'GND' and -3V as its VDD).
Once the signal levels are sorted (use 0 and 3V to power the STM32, invert data to get levels that match the known commands for the FX-602P) the data and clock can be fed to GPIO lines on the STM32, The bus runs at around 200kHz, so there's not a lot of time to process the packets. It is not feasible to have any delays so I run the decoding code purely in interrupts (one on the SP or clock line and one on the CE signal). The timing is so tight that initially I had problems with the serial port disabling interrupts (I presume that is what it was, disabling serial IO removed the problem), those problems went away with later code, but I can still disable the serial port access when packets are received.
The data that is sent and received is held in a RAM buffer, there is no time for access of the SD card, so the RAM buffer is stored and loaded from SD card when needed.
After quite a lot of reverse engineering of the interface (the FX-502P is not quite the same as the FX-602P) including capturing traces of communication between the calculator and an FA-1 adapter, I got some working code that could both send and receive data files from the calculator.
This gives a gateway between the calculator and the outside world. The calculator has a limited number of ways to send information over the interface. It can send or receive a single number (this is the quickest transfer), it can send or receive all memories
At this point the prototype was limiting the code as there isn't sufficient flash memory on a Blue Pill (STM32F103C8) to implement the features I wanted to add. The basic idea had been proven with the prototype, time to move on to a better platform. For that I chose the STM32F103RE device. Or, more accurately I chose the 64 pin QFP package. The STM32F103 family has nice pin compatible genetics, so several devices of different capacities will fit onto a particular footprint. Using the 64 pin QFP I can got up to 1M of flash and 96K of RAM down to 16K of flash and 6K of RAM. There's also a lot of GPIO on this package, way more than I need for this gadget.
It has a small 0.96" OLED display, an SD card module and a programming header that uses an STLINk V2. It also has a serial data header with TX and RX, and a header with 8 GPIOs on it (and power):
The PCB plugs into the connector on the top of the calculator. Optionally the PCB can supply power to the calculator, or it can run off batteries, there's a jumper for that. It's the red one.
I have also used a USB socket breakout board for the USB connection, which supplies poiwer for the PCB and also provides a serial connection. I use a breakout board as the USB sockets have a habit of ripping off the PCBs and taking tracks with them. This way the tracks are on a disposable PCB, not the more valuable one. I've already replaced the USB socket and breakout board on the is PCB...
The code is based on the Arduino platform, so it can connect to the serial monitor of the IDE.
What can it do? Well, it can save and load programs and memories to and from the SD card, that's the basic function. It also uses several 'special' values to do other things. Things like displaying programs on the OLED display:
You can also read the time (and date) into calculator memories:
Of course, it is useful to be able to print things out now and again. Interfacing a simple thermal printer isn't difficult. The one I used accepts serial data so I attached it to the serial data header .The calculator can set up a print flag that sends programs and memories to the printer as well as SD card.
There was a printer that attached to the FX-502P, but it used magic metallised paper which is pretty much impossible to find these days, so a thermal paper option is a nice alternative. See here for more magic metallised paper experiments: