Oh and PS. Just posting this sketch in case its ever useful for anyone - I couldn’t find an example passthrough sketch with a buffer when I was searching, and you need it when you’ve got very different baudrates (and need to send a complete string, like with AT commands). It can obviously be simplified further, probably down to a single function or as basic library, but it’s simple enough for this.
These functions can be thrown in with other code - they’re written so they won’t hang your program waiting for serial data if there’s none available.
/*
Software Serial Passthrough sketch - with a string buffer
Written to pass AT commands to a shield via a software serial port.
Based on https://forum.arduino.cc/t/serial-input-basics/278284
Buffers until it hits a newline character '\n'
*/
#include <SoftwareSerial.h>
int const BufferLength = 64; //Set the maximum number of characters to buffer before printing
char SerialBuffer[BufferLength+1] = {0}; //Allocate the memmory. Don't forget to +1 for the end of string null byte.
char SoftSerialBuffer[BufferLength+1] = {0};
char rc; //A received character
char const endMarker = '\n'; //our end of string marker
boolean PrintToSerial = false; //Are we ready to transmit data received from the Software Serial port over the Hardware Serial port?
boolean PrintToSoftSerial = false; //Are we ready to transmit data received from the Hardware Serial port over the SoftwareSerial port?
SoftwareSerial SoftSerial(11, 10);
void setup() {
Serial.begin(115200);
SoftSerial.begin(300);
}
void loop() {
ReadSerial();
ReadSoftSerial();
PrintData();
}
void ReadSerial() {
static unsigned int BufferIndex = 0;
while (Serial.available() > 0 && PrintToSoftSerial == false) { // If anything comes in Hardware Serial (USB),
rc = Serial.read(); // Buffer the input.
SerialBuffer[BufferIndex] = rc;
BufferIndex++;
if (rc == endMarker || BufferIndex >= BufferLength) { //if we're at the the end, or run out of storage space
//terminate the string and print
SerialBuffer[BufferIndex] = '\0';
BufferIndex = 0; //reset for the next string
PrintToSoftSerial = true;
}
}
}
void ReadSoftSerial() {
static unsigned int SoftBufferIndex = 0;
while (SoftSerial.available() > 0 && PrintToSerial == false) { // If anything comes in the Software Serial port
rc = SoftSerial.read(); // Buffer the input.
SoftSerialBuffer[SoftBufferIndex] = rc;
SoftBufferIndex++;
if (rc == endMarker || SoftBufferIndex >= BufferLength) { //if we're at the the end, or run out of storage space
//terminate the string and print
SoftSerialBuffer[SoftBufferIndex] = '\0';
SoftBufferIndex = 0; //reset for the next string
PrintToSerial = true;
}
}
}
void PrintData() {
if (PrintToSerial == true) {
Serial.println(SoftSerialBuffer); //Send data from SoftSerial over Hardware Serial
PrintToSerial = false;
}
if (PrintToSoftSerial == true) {
SoftSerial.print(SerialBuffer); //Send data from Hardware Serial over SoftwareSerial
PrintToSoftSerial = false;
}
}