0
votes

I am programming on Arduino boards that have several serial ports (let us say for now Serial, Serial1 and Serial3). Each port is a separate object. For using a port, one needs to first initialize it with the begin() method (what I mean with need here is, to get it working fine). The problem is that, the corresponding objects are all available in the Arduino IDE by default, even if you do not declare / initialize them in your sketch, so one is not required to call the constructor and / or initialize a serial port for using it (what I mean here with required, is what should be done to avoid a compiler error). As a consequence, the following kind of code compiles fine, while there is a typo:

byte crrt_char;

void setup(){
  Serial.begin(115200);
  delay(100);

  Serial.println("booted");

  Serial3.begin(57600);
  // Serial1.begin(9600);
  delay(100);
}

void loop() {
  if (Serial3.available() > 0){
    crrt_char = Serial1.read();
    Serial.println(crrt_char, HEX);
    delayMicroseconds(5);
  }
}

(it should be Serial3 instead of Serial1 in the loop).

I have been bitten by this kind of bug and lost a lot of time debugging (in a more complex code of course) several times, and find it sad that the compiler does not save me (for me it looks like a job for a compiler to check for this kind of typo, isnt't it?). Any way I could get some compiler help for detecting this kind of error?

The Arduino core is available here:

https://github.com/arduino/ArduinoCore-avr

Would a possibility be to write my own Arduino core / variants without the serial ports pre-declared, so that I would need to declare them myself before I can use them?

1

1 Answers

1
votes

While it may seem unfair, what the compiler is doing is correct. The compiler must compile the code the way you have written it.

Though people get confused between the job of code assistance vs the job of code compiler, It's your job to ensure that the code is written correctly. It's the compilers job to confirm if the code follows proper syntax.

As for making a board variant and including it into an Arduino Core, you will have to make changes to the HardwareSerial.h file, to ensure that any un-necessary serial objects are not declared.

An easier solution would be to make a macro hold the Serial object you want to use like so

#define CONTROL_PORT    Serial
#define COMMUNICATION_PORT  Serial3

And in your code use CONTROL_PORT and COMMUNICATION_PORT in the following manner

CONTROL_PORT.begin(9600);
COMMUNICATION_PORT.begin(9600);

With this, you will never face a typo, and you can change Serial1 to Serial3 whenever you want. I hope this helps.