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.
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();
Serial, Serial1, Serial2 and Serial3 are all instances of the HardwareSerial class. You could create an array of HardwareSerial objects containing the instances:
PaulS:
Serial, Serial1, Serial2 and Serial3 are all instances of the HardwareSerial class. You could create an array of HardwareSerial objects containing the instances:
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.