const byte buttonPins[] = { 2, 3, 4, 5, 6, 7, 8, 9 }; // Define an array of button pins
const byte numButtons = 8; // Number of buttons
byte buttonStates[numButtons]; // Current button states
byte lastButtonStates[numButtons]; // Previous button states
unsigned long lastDebounceTimes[numButtons]; // Last time each button state changed
byte debounceDelay = 50; // Debounce delay in milliseconds
// Define digital pin numbers for LEDs
const byte ledPins[] = { 23, 25, 27, 29, 31, 33, 34, 35 }; // Updated for Mega
//temp string for printing..
char buff[80];
void setup() {
Serial.begin(115200); // Initialize serial communication at 115200 bits per second
Serial1.begin(115200); // Initialize UART with a baud rate of 115200
Serial2.begin(115200); //init receiver, remove this on seperation..
for (int i = 0; i < numButtons; i++) {
pinMode(buttonPins[i], INPUT_PULLUP); // Set button pins as inputs with internal pull-up resistors
buttonStates[i] = HIGH; // Initialize button states
lastButtonStates[i] = HIGH; // Initialize last button states
lastDebounceTimes[i] = 0; // Initialize debounce times
}
for (int i = 0; i < numButtons; i++) {
pinMode(ledPins[i], OUTPUT); // Set LED pins as outputs
digitalWrite(ledPins[i], LOW); // Initialize LEDs as off
}
pinMode(LED_BUILTIN, OUTPUT); // Set LED pin as output
}
void loop() {
unsigned long now = millis();
for (int i = 0; i < numButtons; i++) {
//read buttons with debounce..
if ((now - lastDebounceTimes[i]) > debounceDelay) {
buttonStates[i] = digitalRead(buttonPins[i]);
}
// Button state has changed..
if (lastButtonStates[i] != buttonStates[i]) {
//button has changed, start debouncing..
lastDebounceTimes[i] = now;
//print nice formatted string into buff..
sprintf(buff, "Button %d state %d", i, buttonStates[i]);
Serial.println(buff);
lastButtonStates[i] = buttonStates[i]; // Update the last button state
//send button number to be toggled..
Serial1.print(i);
}
}
//receiver code..
//this would be in the other sketch using Serial1 object..
if (Serial2.available()) {
char buttonChar = Serial2.read();
Serial.print("Received character: "); // Debugging output
Serial.println(buttonChar);
if (buttonChar >= '0' && buttonChar <= '7') {
int ledIndex = buttonChar - '0';
Serial.print("Toggling LED at index: "); // Debugging output
Serial.println(ledIndex);
digitalWrite(ledPins[ledIndex], !digitalRead(ledPins[ledIndex]));
}
}
}