如何基于循环迭代器选择函数

How to Choose Function Based on Loop Iterator

本文关键字:选择 函数 迭代器 循环 何基于      更新时间:2023-10-16

我在这里寻找解决方案的部分问题可能是我不知道我所问的正确术语。 为此,我提前请求原谅。

对于微控制器,我有一个希望同时启动的引脚列表。 每个实例都有自己的 ISR,并为每个实例调用类的相同成员,但使用引脚号作为参数。

我正在尝试将数组中的每个引脚连接到其相应的 ISR,但我想通过引脚的索引选择哪个 ISR。 这是邮件代码™,可能不会编译,但我相信这足以得到这个想法:

#define PIN1 4
#define PIN2 9
#define PIN3 10
#define PIN4 8
#define PIN5 12
PinAct *pPinact; // Pointer to Counter class
static ICACHE_RAM_ATTR void HandleInterruptsStatic1(void) {
pPinact->handleInterrupts(1);
}
static ICACHE_RAM_ATTR void HandleInterruptsStatic2(void) {
pPinact->handleInterrupts(2);
}
static ICACHE_RAM_ATTR void HandleInterruptsStatic3(void) {
pPinact->handleInterrupts(3);
}
static ICACHE_RAM_ATTR void HandleInterruptsStatic4(void) {
pPinact->handleInterrupts(4);
}
static ICACHE_RAM_ATTR void HandleInterruptsStatic5(void) {
pPinact->handleInterrupts(5);
}
class PinAct {
public:
PinAct() {};
void handleInterrupts(int);
}
void PinAct::PinAct() {
int actPins[] = {PIN1, PIN2, PIN3, PIN4, PIN5};
for (int i = 0; i <= sizeof(actPins); i++) {
pinMode(actPin[i], INPUT)
attachInterrupt(digitalPinToInterrupt(KEG1), HandleInterruptsStatic + i, FALLING);
}
}
void PinAct::handleInterrupts(int pin) { // Bubble Interrupt handler
// Do something with pin
}

目标是实际使attachInterrupt(digitalPinToInterrupt(KEG1), HandleInterruptsStatic + i, FALLING);工作,通过索引 i 选择哪个 ISR。

我需要就是否分配 ISR 做出其他决定,因此连接要分配的 ISR 名称是可取的。

attachInterrupt(/* ... */, HandleInterruptsStatic + i, /* ... */);
//                                              ^^^^^

为了根据某些整数索引i选择要在运行时调用的函数,您可以使用函数指针数组:

typedef void (*FunctionPointer_t)(void);
FunctionPointer_t functions[] = {
HandleInterruptsStatic1,
HandleInterruptsStatic2,
// ...
};
// to use:
functions[i]();