As you may have noticed, I’ve been working with an STM32 ARM CPU using Mbed. There was a time when Mbed was pretty simple, but a lot has changed since it has morphed into Mbed OS. Unfortunately, that means that a lot of libraries and examples you can find don’t work with the newer system.
I needed a rotary encoder — I pulled a cheap one out of one of those “49 boards for Arduino” kits you see around. Not the finest encoder in the land, I’m sure, but it should do the job. Unfortunately, Mbed OS doesn’t have a driver for an encoder and the first few third-party libraries I found either worked via polling or wouldn’t compile with the latest Mbed. Of course, reading an encoder isn’t a mysterious process. How hard can it be to write the code yourself? How hard, indeed. I thought I’d share my code and the process of how I got there.
There are many ways you can read a rotary encoder. Some are probably better than my method. Also, these cheap mechanical encoders are terrible. If you were trying to do precision work, you should probably be looking at a different technology like an optical encoder. I mention this because it is nearly impossible to read one of these flawlessly.
So my goal was simple: I wanted something interrupt driven. Most of what I found required you to periodically call some function or set up a timer interrupt. Then they built a state machine to track the encoder. That’s fine, but it means you eat up a lot of processor just to check in on the encoder even if it isn’t moving. The STM32 CPU can easily interrupt with a pin changes, so that’s what I wanted.
The problem is, of course, that mechanical switches bounce. So you have to filter that bounce either in hardware or software. I really didn’t want to put in any extra hardware more than a capacitor, so the software would have to handle it.
I also didn’t want to use any more interrupts than absolutely necessary. The Mbed system makes it easy to handle interrupts, but there is a bit of latency. Actually, after it was all over, I measured the latency and it isn’t that bad — I’ll talk about that a little later. Regardless, I had decided to try to use only a pair of interrupts.