Mega - using Serial, Serial1, Serial2 and Serial3

Hello,

I am a self-taught programmer, so I'm hoping there is an easy and obvious solution for my problem, but I cannot find one anywhere.

I have a single "master" Mega talking with multiple Mega boards using the serial pins. Each "slave" is identical and I am hoping to simplify the code. Is there an easy way to redefine the following commands:

switch "board" {
case "0":
Serial.print(...); break;
case "1":
Serial1.print(...); break;
case "2":
Serial2.print(...); break;
default:
}

Basically, I'm looking for something like the following:

Serial(board).print(...);

I'm sure I could write my own functions to give the effect of mySerialPrint(board, value), but I was hoping for an obvious answer.

Thanks,
Greg

Hello,

I would use switch...case. I don't see your problem with it. But, your code has some errors as I see it:

switch(board) {  //change the " to ( and )
case "0":  //do only use "0" if board is a variable of the type string or char. If it's an int, use just 0 (without the ")
   Serial.print(...); break;
case "1":  //ditto
   Serial1.print(...); break;
case "2":  //ditto again
   Serial2.print(...); break;
default:
}

No, there is no such function like Serial(board).print();

Jan

Serial, Serial1, Serial2 and Serial3 are all instances of the HardwareSerial class. You could create an array of HardwareSerial objects containing the instances:

HardwareSerial hs[4] = {Serial, Serial1, Serial2, Serial3};

Then, use them:

hs[1].print(someValue);

This would send someValue to Serial1.

PaulS:
Serial, Serial1, Serial2 and Serial3 are all instances of the HardwareSerial class. You could create an array of HardwareSerial objects containing the instances:

HardwareSerial hs[4] = {Serial, Serial1, Serial2, Serial3};

Then, use them:

hs[1].print(someValue);

This would send someValue to Serial1.

Thank you for the solution. I knew there had to be something very simple, and this is what I was trying to figure out. I knew of the software serial class, but did not know of the HardwareSerial.

Jan - The reason to not use the above code is that with the growing numbers of these popping up, including read(), write() and available(), it is becoming very bloated and hard to read my code to do simple things.

Thanks again,
Greg