Bidirectional Communication with Collision Avoidance Since SoftwareSerial is half-duplex, implement a simple protocol:
#include <SoftwareSerial.h> For ESP8266/ESP32, note that they have a different SoftwareSerial implementation (often renamed or not available due to better hardware serial options). Constructor SoftwareSerial mySerial(RX_pin, TX_pin); // Example: RX on pin 10, TX on pin 11 SoftwareSerial gpsSerial(10, 11); Essential Methods | Method | Description | |--------|-------------| | begin(baud) | Initializes the software serial port. | | available() | Returns number of bytes ready to read. | | read() | Reads one byte (-1 if none). | | write(data) | Sends a byte (or string via print() / println() ). | | listen() | Enables this port for reception (if multiple ports exist). | | isListening() | Checks if this port is active. | | overflow() | Returns true if data was lost due to buffer overflow (64-byte buffer). | Simple Example: GPS Module #include <SoftwareSerial.h> SoftwareSerial gps(10, 11); // RX=10, TX=11 softwareserial.h library
// Periodically check Bluetooth (non-blocking) if (bluetooth.available()) char cmd = bluetooth.read(); if (cmd == 'G') gps.listen(); // Switch back to GPS | | read() | Reads one byte (-1 if none)
void loop() if (gps.available()) char c = gps.read(); Serial.print(c); // Echo GPS data to Serial Monitor | | isListening() | Checks if this port is active
void setup() Serial.begin(9600); // Hardware serial for debug gps.begin(9600); // GPS module baud rate
void loop() if (port1.available()) // Process port1 data
The classic Arduino Uno, Nano, and Mega 2560 (for its first few ports) have dedicated hardware UARTs (Universal Asynchronous Receiver-Transmitters). However, hardware UARTs are limited in number. Once you connect a GPS module, a Bluetooth module, and a debug console simultaneously, you run out of ports.