Select Serial1 or Serial2 in function ?

Status
Not open for further replies.

Jp3141

Well-known member
I'm trying to write a program that will allow me to use different serial ports programmably, but I can't get it to work. Is this possible ?

Here's my stripped down code:
Code:
void setup() {
  Serial.begin(9600); while (!Serial);
  Serial1.begin(9600); Serial1.setTimeout(1000);
  Serial2.begin(9600); Serial2.setTimeout(1000);
}

void loop() {
  double fValue;
  fValue  = getSerialValue(Serial1, "READ?\n");
  fValue *= getSerialValue(Serial2, "READ?\n");
  Serial.print("Total = "); Serial.print(fValue);
  delay(1000);
} // loop

double getSerialValue(HardwareSerial WhichSerialPort, char* command) {
char zBuffer[80];

//Serial2.print(command);
//Serial2.readBytesUntil('\n', zBuffer, 79);
  WhichSerialPort.print(command);
  WhichSerialPort.readBytesUntil('\n', zBuffer, 79);
  return atof(zBuffer);
}

This compiles without errors, but doesn't run; when I hardwire Serial2 in the function, it runs.

What's the C trick to get this to work ?
 
Last edited:
What's the C trick to get this to work ?


maybe "Stream" would work like this.

Code:
void setup() {
  Serial.begin(9600); 
  while (!Serial);
  Serial1.begin(9600); 
  Serial1.setTimeout(1000);
  Serial2.begin(9600); 
  Serial2.setTimeout(1000);
}


void loop() {
  double fValue;
  fValue  = getSerialValue([B][COLOR=#ff0000]&Serial1[/COLOR][/B], "READ?\n");
  fValue *= getSerialValue([B][COLOR=#ff0000]&Serial2[/COLOR][/B], "READ?\n");
  Serial.print("Total = "); 
  Serial.print(fValue);
  delay(1000);
} // loop


double getSerialValue([B][COLOR=#ff0000]Stream *WhichSerialPort[/COLOR][/B], char* command) {
  char zBuffer[80];
  double ff;


  //Serial2.print(command);
  //Serial2.readBytesUntil('\n', zBuffer, 79);
  zBuffer[8]=0; // atof doesn't understand "+1.23450000E-06\n"
  WhichSerialPort->print(command);
  WhichSerialPort->readBytesUntil('\n', zBuffer, 79);
  return atof(zBuffer);
}

you can even use usb "Serial" this way also. haven't tested this code but i've used it in the past. hope it helps.

duff
 
Status
Not open for further replies.
Back
Top