I am trying to define multiple serial ports (multiple BMS management boards) and select via a global variable the port which one is active, this is the sketch I am trying to modify.
https://github.com/bres55/Smart-BMS-arduino-Reader/blob/master/smart_bms_reader_Mega_v11.ino
The function I want to write could be called "MySerialSwitch"
The smart_bms_reader_Mega_v11.ino has 19 calls to serial in a number of different functions. I want to be able to define the "active" MySerial in a variable that can be changed on the fly.
Something like this.
#include <SoftwareSerial.h>
SoftwareSerial MySoftSerial1(10, 11); // RX, TX
SoftwareSerial MySoftSerial2(12, 13); // RX, TX
#define MySerial1 MySoftSerial1
#define MySerial2 MySoftSerial2
#define MySerial3 Serial3
char MySerialPort[] = "MySerial1";
void setup()
{
MySoftSerial1.begin(9600);
MySoftSerial2.begin(9600);
Serial3.begin(9600);
}
This function would be modified
void call_get_cells_v()
{
flush(); // flush first
uint8_t data[7] = {221, 165, 4, 0, 255, 252, 119};
MySerial.write(data, 7);
}
to read.
void call_get_cells_v()
{
flush(); // flush first
uint8_t data[7] = {221, 165, 4, 0, 255, 252, 119};
MySerialSwitch.write(data, 7);
}
I have been researching this post
How to define a SoftwareSerial object inside a class?
And this post
Writing First Library - Serial Stream Object
It’s my first attempt at creating a library, I think this is kind of what I am trying to achieve, I've done the reading on stream, references and pointers. I'm not quite clear yet. I would really appreciate some assistance.
class MySerialSwitch {
private:
Stream *_dev;
public:
MySerialSwitch(Stream *dev) : _dev(dev) {}
MySerialSwitch(Stream &dev) : _dev(&dev) {}
(char MySerialPort);
};
(int pos) {
_dev->write(char MySerialPort);
}