// Week 11 Networking - ESP32 side of the XIAO <-> ESP32 UART link (Arduino IDE, board: "ESP32 Dev Module"). // Wiring: ESP32 GPIO16 (RX2) <- XIAO D6 (TX) // ESP32 GPIO17 (TX2) -> XIAO D7 (RX) // ESP32 GND <-> XIAO GND (both boards 3.3 V logic: direct wires, no resistors) // Messages are text lines ending in '\n', 9600 baud. // BOOT button (GPIO0) -> send "S" (XIAO servo toggles 90 <-> 0 deg) // "T" from XIAO -> on-board LED (GPIO2) toggles // anything typed in the Serial Monitor (115200, Newline) is sent to the XIAO too. const int RX2_PIN = 16; const int TX2_PIN = 17; const int BOOT_PIN = 0; const int LED_PIN = 2; // on-board LED on most ESP32 DevKits bool ledOn = false; int lastBoot = HIGH; String rxBuf, usbBuf; void sendToXiao(const String &msg) { Serial2.print(msg + "\n"); Serial.println("TX -> XIAO: " + msg); } void setup() { Serial.begin(115200); // USB Serial Monitor Serial2.begin(9600, SERIAL_8N1, RX2_PIN, TX2_PIN); // UART2 to the XIAO pinMode(BOOT_PIN, INPUT_PULLUP); pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW); Serial.println("ESP32 UART2 ready @ 9600 (RX2=GPIO16, TX2=GPIO17)"); } void loop() { // from the XIAO while (Serial2.available()) { char c = Serial2.read(); if (c == '\n') { rxBuf.trim(); if (rxBuf.length()) { Serial.println("RX <- XIAO: " + rxBuf); if (rxBuf == "T") { ledOn = !ledOn; digitalWrite(LED_PIN, ledOn ? HIGH : LOW); Serial.println(ledOn ? "LED ON" : "LED OFF"); } } rxBuf = ""; } else { rxBuf += c; } } // typed in the Serial Monitor while (Serial.available()) { char c = Serial.read(); if (c == '\n' || c == '\r') { usbBuf.trim(); if (usbBuf.length()) sendToXiao(usbBuf); usbBuf = ""; } else { usbBuf += c; } } // BOOT pressed: one "S" per press int b = digitalRead(BOOT_PIN); if (b == LOW && lastBoot == HIGH) { sendToXiao("S"); delay(30); // debounce } lastBoot = b; }