By dave | February 9, 2018

Have you ever wanted to treat switch presses similar to how you work in other languages, where you get an event callback when the switch is pressed? Look no further, the IO abstraction library can do that with very little fuss. In fact it can also do the same for rotary encoders as well, treating them similar to how scroll bars work in desktop applications.

To start we need to get the IoAbstraction library and open the encoderSwitch example. This example shows how to use a rotary encoder and two switches (the encoder push switch and another micro-switch) with the switches class. It outputs changes to switches and encoders to the Serial port.

First, you’ll need to build the following circuit:

Circuit example for wiring switches and encoder

Schematic for wiring switches and encoder

A walk through of the code

This page is based on the example packaged within the ioabstraction library, called encoderSwitch. It’s packaged within the examples directory, in Arduino IDE should be openable directly from the examples once the library is installed.

Link to the example sketch file

This sketch may look slightly different when you first see it, at the top of the file are a lot of event handlers, they are called by switches when buttons are pressed or the encoder changes value. An example callback is shown below:

void onRepeatButtonClicked(uint8_t pin, bool heldDown) {
  Serial.println("Repeat button pressed");

In the setup of the sketch we see that the event handling for switches is set up, and we tell switches to use arduino pins for IO.


switches.addSwitch(somePin, aCallBackFunction);

We then go ahead and set up the rotary encoder, setting the range of values to be between maximumEncoderValue, starting out at 100:

switches.initialiseEncoder(encoderAPin, encoderBPin, encoderChangeFn);
switches.changeEncoderPrecision(maximumEncoderValue, 100)

Notice that the loop function just contains one line, as everything else is controlled by TaskManager.


For more detail, there’s complete documentation for the library. In addition to this, there’s also lots of other examples packaged with the library.

comments powered by Disqus
We use cookies to analyse traffic and to personalise content and adverts. Our social buttons may also use cookies.