Note: I am a mechanic, machinist, fabricator, but not so much a programmer. I'd like to hear of perhaps better ways to go about organizing similar code or if my reasoning is flawed.
I've read quite a bit of documentation and done some searching but have not found any specific example of an array of structures containing ISRs as member functions. Is that a valid way to declare them for the sake of readability?
I am building a controller for a car seat that has six motors which adjust position.
Each motor has the same set of attributes relevant to my program, so it makes sense to define an array of six structures containing the different variables.
Can I somehow define an ISR within the structure that can be used in the loop for each motor by indexing the array?
Example:
struct Position {
long saved[4];
long current;
};
struct Motor {
const byte sensorPin; // pins detecting rising edge of Hall sensor signal
const byte switchPin[2]; // corresponding pins from switches
const int value; // corresponding nominal analogRead() values
bool direction[2]; // [0]: forward [1]: backward
Position position; // positions for each motor/axis (counting revolutions from front limit of travel)
static unsigned int interruptDetected; // flag for ISR
// ISR to set flag
static void track(void) {
interruptDetected++;
}
void initializeISR() {
attachInterrupt(digitalPinToInterrupt(sensorPin), track, RISING);
}
} M[6] = {
{26, A0, A2, 142},
{24, A0, A2, 312},
{22, A0, A2, 626},
{23, A1, A3, 142},
{25, A1, A3, 312},
{27, A1, A3, 626}
};
void setup() {
for (int m = 0; m < 6; m++)
M[m].initializeISR();
}
void loop() {
// read switches, actuate motors, etc...
// interrupts used to track motors:
for (int m = 0; m < 6; m++) {
if (M[m].interruptDetected) {
if (M[m].direction[0]) {
M[m].position.current -= M[m].interruptDetected;
}
else if (M[m].direction[1]) {
M[m].position.current += M[m].interruptDetected;
}
M[m].interruptDetected = 0;
}
}
}
Is there a better way to get around defining 6 separate ISRs at the top of my program and then including attachInterrupt() for each?