First of all I'm not sure where something like this goes. Are there dedicated 8266 categories? Anyway I'm tinkering with learning Interrupts. (Well actually learning/re-learning everything 8266.) I'm going to be monitoring relays etc. My original method was polling now wandering into Interrupts. My initial stab at this is monitoring the state of 7 buttons. It all works but for some unknown reason, well unknown to me, when I press the button associated with pin D4 while I hold down the button the built in LED lights. This doesn't happen with any other button. From the NodeMCU 12E pinout I see that D4 is also associated with TXD1 but the other pins are associated with other things as well. Like I mentioned just curious and low priority as other than the blue light on for D4 when LOW, it does what I've told it to do.
#define numRelays 7
const int relayPins[] = {D1, D2, D3, D4, D5, D6, D7};
volatile bool relayFlags[numRelays];// = {false, false,false, false,false, false, false};
volatile unsigned long lastDebounceTimes[numRelays];
bool currentRelayStates[numRelays]; // Array to store the current relay states
const unsigned long debounceDelay = 50; // Debounce delay in milliseconds
void IRAM_ATTR relayISR();
void setup() {
//Initialize arrays and Interrupt handlers
for (int i = 0; i < numRelays; i++) {
relayFlags[i] = false;
lastDebounceTimes[i] = 0;
currentRelayStates[i] = HIGH;
pinMode(relayPins[i], INPUT_PULLUP); // Set relay pins as input with internal pull-up resistors
attachInterrupt(digitalPinToInterrupt(relayPins[i]), relayISR, CHANGE); // Attach interrupt
}
Serial.begin(115200);
Serial.println("ESP8266 ready");
}
void loop() {
unsigned long currentTime = millis();
for (int i = 0; i < numRelays; i++) {
if (relayFlags[i]) {
if ((currentTime - lastDebounceTimes[i]) > debounceDelay) {
bool state = digitalRead(relayPins[i]);
if (state != currentRelayStates[i]) {
currentRelayStates[i] = state; // Update the current state
if (state == LOW) {
Serial.print("Relay ");
Serial.print(i+1);
Serial.println(" activated!");
} else {
Serial.print("Relay ");
Serial.print(i+1);
Serial.println(" deactivated!");
}
}
relayFlags[i] = false;
}
}
}
}
void IRAM_ATTR relayISR() {
unsigned long currentTime = millis();
for (int i = 0; i < numRelays; i++) {
relayFlags[i] = true;
lastDebounceTimes[i] = currentTime; // Reset debounce timer
}
}