There is a library davetcc / IoAbstraction. The only library working as expected with my rotary encoder. The problem that on rotation I can only see serial output with position data, but I cannot get these data as some variable value.

There is the swithch initialization and function definition in main.cpp switches.addSwitch(spinwheelClickPin, onSpinwheelClicked);

void onSpinwheelClicked(uint8_t pin, bool heldDown) {
  Serial.print("Button pressed ");
  Serial.println(heldDown ? "Held" : "Pressed");

The definition from SwitchInput.cpp

bool SwitchInput::addSwitch(pinid_t pin, KeyCallbackFn callback,uint8_t repeat, bool invertLogic) {
    if(internalAddSwitch(pin, invertLogic)) {
        KeyboardItem item(pin, callback, repeat, invertLogic);
        return keys.add(item);
    return false;

There is the callback function type definition from SwitchInput.h

typedef void(*KeyCallbackFn)(pinid_t key, bool heldDown);

I canon just change void to bool. So how can I get this heldDown variable value?

Sorry if the question is stupid.


Callback functions are usually void and don't return real data, because they are called by some type of event handling system, like the mentioned library. As this is calling the callback function, not you, it does not make much sense to return data from it. To get that return value, you would need to change the library for every bit of data, that you want. Thus return values of callback functions are either void or some message to the event handling system (for example to make the event system send down the event to the next possible handler).

But you can use global variables to get the data from the callback. Define a global variable for the value, that you want to extract, and inside the callback function set that variable. Then at other places in your code you can use that global variable.

The library, that you linked, seems to handle the event in the main code and not in interrupts. So you are safe to just use the global variables as you like.

Though to be complete: When interrupts are involved and you change global variables inside an interrupt service routine, you need to be very careful. Single byte variables are not problem, but with multi-byte variables you can get scrambled data, as the interrupt might occur in the middle of processing that variable. Then you need to introduce a critical section, where interrupts are disabled for a very short time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.