Search code examples
c++objectarduinoinstance-variables

Storing class instance in new variable causes weird behavior (Arduino Serial)


I was just trying to create a new variable to store the Serial object in that the Arduino provides by default.

Now here is what I don't understand:

Why is the output of this first code only 334

HardwareSerial SerialB = Serial;

void setup() {
  SerialB.begin(115200);
  SerialB.print(0x33, HEX);
  SerialB.print(0x44, HEX);
  SerialB.print(0x55, HEX);
}

void loop() {
  //do nothing
}

And the output of this second code is 334455

void setup() {
  Serial.begin(115200);
  Serial.print(0x33, HEX);
  Serial.print(0x44, HEX);
  Serial.print(0x55, HEX);
}

void loop() {
  //do nothing
}

Why does the first code stop while printing the second byte? What am I misunderstanding here? Shouldn't both codes result in the same output?


Solution

  • As dfri said, you were making another HardwareSerial instance, with disastrous results.

    Just use a reference. It's like a pointer, except the dot notation is used instead of having to use the arrow notation:

    HardwareSerial & SerialB = Serial; // an alias, not a new instance
    
    void setup() {
      SerialB.begin(115200);
      SerialB.print(0x33, HEX);
    

    Note the ampersand.