i am testing out communication between an arduino nano and arduino nano esp32 and am having issues. I've tested both independently and they work. Example the nano sends on/off commands to serial and the esp32 turns the led on or off if i type "ON" or "OFF" in serial. However when connected the two and powering at the same time the led doesn't turn on when the button is selected. They are both connected correctly (Arduino RX to esp32 TX and Arduino TX to the esp32 RX & share a ground). Is there something im missing on how to accept serial commands different if not sent via the IDE? Here is the scripts for reference:
//nano
const int buttonPin = 13; // Button connected to pin 13
int buttonState = 0; // Variable to store button state
int lastButtonState = LOW; // For edge detection, assuming LOW as the unpressed state
bool toggleState = false; // Toggle state for switching between ON and OFF
void setup() {
pinMode(buttonPin, INPUT_PULLUP); // Initialize the button pin as an input with an internal pull-up resistor
Serial.begin(9600); // Start serial communication at 9600 bps
}
void loop() {
buttonState = digitalRead(buttonPin); // Read the current state of the button
// Check for button press with edge detection (transition from LOW to HIGH)
if (buttonState == HIGH && lastButtonState == LOW) {
// Delay for debouncing
delay(200);
// Ensure that the button is still pressed after debounce delay
if(digitalRead(buttonPin) == HIGH) {
if (toggleState) {
// If toggle state is true, print "OFF"
Serial.println("OFF");
} else {
// If toggle state is false, print "ON"
Serial.println("ON");
}
toggleState = !toggleState; // Toggle the state
}
}
lastButtonState = buttonState; // Store the last button state
}
//nano esp32
void setup() {
Serial.begin(9600); // Initialize serial communication at 9600 bps
pinMode(13, OUTPUT); // Set the digital pin as output
}
void loop() {
// Check if data is available to read from the serial port
if (Serial.available() > 0) {
// Read the incoming byte
String command = Serial.readStringUntil('\n'); // Adjusted to read string until newline character
// Trim any whitespace or new line characters
command.trim();
// Check if the command is "ON"
if (command == "ON") {
digitalWrite(13, HIGH); // Turn the LED on
}
// Check if the command is "OFF"
else if (command == "OFF") {
digitalWrite(13, LOW); // Turn the LED off
}
}
}
