//
// Half-duplex Software Serial over a single wire UART
// Communication for a Shared Serial Bus
//
#include <SoftwareSerial.h>
#define RTX 2 // Single Wire Shared Bus Pin
#define BaudRate 9600U // set UART baudrate
SoftwareSerial swSerial(RTX, RTX);
HardwareSerial &hwSerial = Serial;
String hwSerialData = ""; // a String to hold incoming data
String swSerialData = "";
bool hwDataComplete = false; // whether the string is complete
bool swDataComplete = false; // whether the string is complete
void setup() {
// SwSerial.begin(115200, SERIAL_8N1, SingleWire_pin, 16);
pinMode(RTX, INPUT); // put RTX pin in Input mode
swSerial.begin(BaudRate); // initialize SoftwareSerial
hwSerial.begin(BaudRate); // initialize HardwareSerial
swSerialData.reserve(128); // reserve 128 bytes for the inputString:
hwSerialData.reserve(128); // reserve 128 bytes for the inputString:
hwSerial.println("Start");
}
void loop() {
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
swSerialInput();
}
void swSerialInput() {
while (swSerial.available()) {
char character = swSerial.read(); // Receive a single character from the software serial port
swSerialData.concat(character); // Add the received character to the receive buffer
if (character == '\n') {
//hwSerial.print("Received: ");
hwSerial.println(swSerialData);
// Add your code to parse the received line here....
// Clear receive buffer so we're ready to receive the next line
swSerialData = "";
}
}
}
void swSerialOutput() {
// print the string when a newline arrives:
if (swDataComplete) {
pinMode(RTX, OUTPUT); // put RTX pin in Output mode
swSerial.println(swSerialData);
pinMode(RTX, INPUT); // put RTX pin in Input mode
// clear the string:
swSerialData = "";
swDataComplete = false;
}
}
/*
SerialEvent occurs whenever a new data comes in the hardware serial RX. This
routine is run between each time loop() runs, so using delay inside loop can
delay response. Multiple bytes of data may be available.
*/
void serialEvent() {
while (hwSerial.available()) {
// get the new byte:
char inChar = (char)hwSerial.read();
// add it to the inputString:
hwSerialData += inChar;
// if the incoming character is a newline, set a flag so the main loop can
// do something about it:
if (inChar == '\n') {
hwDataComplete = true;
}
}
swSerialOutput();
}