These days, as I've been using callbacks more and more (through Arduino-style APIs, for example IntervalTimer or attachInterrupt()), it's become apparent that this programming paradigm depends on there being global state. I'm finding myself rewriting these pieces but I lose the ability to automatically upgrade my code if any of the core code changes, or having very large switch statements that assign specific ISRs, depending on which pin, etc.
My current consternation has to do with finding out which pin triggered an edge interrupt. I can solve this in a few ways:
I'm seeking opinions on how to do approach #3. Following is some example code. My challenge to you is to modify the "API Section" of the program so that the ISR (could be new functions) prints the state of the associated Holder object. You aren't allowed to modify the "User Section" because that emulates calling an API.
My current consternation has to do with finding out which pin triggered an edge interrupt. I can solve this in a few ways:
- Reimplement internal APIs that I need (yuck).
- Write a callback routine for every pin possibility (yuck again).
- ???.
I'm seeking opinions on how to do approach #3. Following is some example code. My challenge to you is to modify the "API Section" of the program so that the ISR (could be new functions) prints the state of the associated Holder object. You aren't allowed to modify the "User Section" because that emulates calling an API.
Code:
// --------------
// API Section
// --------------
void pin_rising_isr();
// Holds some state.
class Holder {
public:
Holder(int state) : state_(state), risingPin_(-1) {}
void setRisingPin(int pin) {
if (pin >= CORE_NUM_DIGITAL) {
return;
}
risingPin_ = pin;
if (pin >= 0) {
attachInterrupt(pin, pin_rising_isr, RISING);
}
}
int state_;
int risingPin_;
};
void pin_rising_isr() {
Serial.println("My caller's state is: ???");
}
// --------------
// User Section
// --------------
Holder h1{100};
Holder h2{200};
void setup() {
Serial.begin(115200);
while (!Serial && millis() < 4000) {
// Wait for Serial to initialize
}
h1.setRisingPin(2);
h2.setRisingPin(6);
}
void loop() {
yield();
}