I am working on an Arduino project, that would use HardwareSerial object reference stored in a class and call methods on it. However, there is problem with writing output using the reference.
Minimal use case to demonstrate behavior is in following files:
main.ino
#include <Arduino.h>
#include "testclass.h"
TestClass testClassInstance(Serial);
void setup() {
}
void loop() {
testClassInstance.print("Hi There\r\n");
delay(1000);
}
testclass.h
#ifndef TESTCLASS_H
#define TESTCLASS_H
#include <Arduino.h>
class TestClass {
public:
TestClass(HardwareSerial &serial);
void print(const char * text);
private:
HardwareSerial _serial;
};
#endif
testclass.cpp
#include "testclass.h"
TestClass::TestClass(HardwareSerial &serial) : _serial(serial) {
_serial.begin(9600);
_serial.print("Initializing\r\n");
}
void TestClass::print(const char *text) {
_serial.print(text);
}
After reset, there are only two characters sent: "In"
In the example above, initialization is done before setup() method and Serial's state is probably reset before calling it. Having changed that to dynamic allocation in setup method did not change this behavior as well.
modification of main.ino
TestClass *testClassInstance;
void setup() {
testClassInstance = new TestClass(Serial);
}
There might be problem with passing the reference to Serial, but in that case I would expect to not have any output at all.
Any help is greatly appreciated.