// Fnu Shoaib Ahmed, 652420658, fahme8
// Muhammad Taha, 671153042, mtaha6s
// Lab 7 - Communication of Arduinos
// Description - This code enables two Arduino devices to communicate via a button press,
// toggling an LED on the other Arduino while displaying status updates on an LCD for debugging.
// Assumptions - Both Arduinos share a common ground, and the button is correctly debounced using millis() to prevent unintended multiple triggers.
// References - I used the prelab links to connect the Arduinos together.
#include <LiquidCrystal.h>
// Initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int buttonPin = 7; // Pin for the button
const int ledPin = 13; // Pin for the LED
bool ledState = LOW; // LED state
int buttonState = 0; // Current button state
int lastButtonState = 0; // Previous button state
unsigned long lastDebounceTime = 0; // Last time the button state changed
const unsigned long debounceDelay = 50; // Debounce delay time
void setup() {
Serial.begin(9600); // Start serial communication
lcd.begin(16, 2); // Initialize the LCD
lcd.print("Ready"); // Display initial message
pinMode(ledPin, OUTPUT); // Set LED pin as output
pinMode(buttonPin, INPUT); // Set button pin as input
}
void loop() {
// Get the current time
unsigned long currentMillis = millis();
// Read the current state of the button
int reading = digitalRead(buttonPin);
// Check if the button state has changed (i.e., button is pressed or released)
if (reading != lastButtonState) {
lastDebounceTime = currentMillis; // Reset the debounce timer
}
// If enough time has passed since the last state change, proceed
if ((currentMillis - lastDebounceTime) > debounceDelay) {
// Check if the button state has changed
if (reading != buttonState) {
buttonState = reading;
// Only act if the button is pressed
if (buttonState == HIGH) {
lcd.clear();
lcd.print("Signal Sent!");
Serial.write("Button Pressed!");
}
}
}
// Check for incoming data from the other Arduino
if (Serial.available() > 0) {
String data = Serial.readStringUntil('\n'); // Read the incoming data
if (data == "Button Pressed!") {
lcd.clear();
lcd.print("Signal Received!");
ledState = !ledState; // Toggle LED state
digitalWrite(ledPin, ledState); // Update LED based on received state
}
}
// Update the lastButtonState
lastButtonState = reading;
}