Hello, I'd like to assign "names" to Serial Ports 1-4 on a Mega2560. The purpose is easily selecting thru the "serial monitor" any port as Tx and/or Rx . For example , sending "S1R4800" can stand for :Serial1, receiver, baudrate 4800 .
So I can easily go : S1.begin(4800) [standing for :Serial1.begin(4800) OR .end() OR read() etc]
I was rather anxious for an answer so I didnt check above correctly.
Rephrase : I want to enter at serial monitor an order in the form "S1R4800" . This will be read as a String or string array in order to mean and can be used as : S1 = Serial1, R=receive (for use in one function for all Serial ports), 4800= baudrate.
So, I think, I need a transfomation of String (or char) to be valid for Serial1 .
ok, the String example was an overreaction. But neither (S or string) solves my problem.
My project is a protocol com test adapter , that is from 232 - 485 w/ or w/o baud change or opposite, half or full duplex ...and so on - any combination, So it must be a flexible way to adopt to any enviroment. It is not difficult to copy/paste 3 times (4 total) the same function for Rx 3 (4) for Tx, it just in my belief is not the correct programming way,
So I was wondering / wandering if there can be something else.
You can have a variable that holds the currently desired serial port, and use that in function. In the code below just an index into an array of serial objects.
But there will be no getting around setting such a variable by parsing the input and recognizing which one that is to be.
From
const size_t PORTS_COUNT = 4;
const HardwareSerial *ports[PORTS_COUNT] = {
&Serial, &Serial1, &Serial2, &Serial3
};
void setup() {
for (size_t i = 0; i < PORTS_COUNT; i++)
ports[i]->begin(9600);
}
Then for example use port[portNjmber] after setting an int portNjmber to 1 anywhere you woukd have used Serial1
Don't use 'HardwareSerial *' type as all "Serial" ports on all boards are not of the HardwareSerial (i.e. UART) class. On a Teensy 3.6 for example, 'Serial' is an object of the 'usb_serial_class' class. Similar for SAMD and 32u4 boards. Use a 'Stream *' type instead.
Indeed it is. The inheritance structure is below. Print and Stream are abstract classes.
Classes that only need output (such as the various LCD classes) inherit directly from Print as they don't need the input capabilities provided by Stream.
The two-way "Serial" type classes inherit from Stream.
the solution I believe is #10, already marked, it is more clever than casting, but I cannot test it now (it is something completely new to me i dont have the time to spend for testing and perhaps i dont have the knowledge for testing something that goes too deep).
I will follow the casting, if I had followed from the beginning (String or string) I would have the sketch running already.
I hope it is clear