Using Serial object within a library class

Hello
I tried to use a Serial to print off a message (like for example when it's printed after being initialised).
However, it only printed one character and nothing else.
Here's what the code looks like for the header of a class.

#ifndef Context_h
#define Context_h
#include "Arduino.h";

class Context {
public:
    Context() {Serial.begin(9600); Serial.println("I am alive");}
    String getSelectedStateName();
    int getSelectedStateId();
    void setStateName(String name);
    void setStateId(int id);
    bool isSerialBufferNonEmpty();
    int getSerialBufferSize();
    char readCharFromSerial();
    void printToSerial(String message);
private:
    String _stateName;
    int _stateId;
};

#endif

The point of the class is to allow state classes (i.e. that are part of the state pattern), to use it to send messages back to the main .ino script.
So I am curious, is it possible to use Serial within library classes?

thanks for reading!

is it possible to use Serial within library classes?

Yes.

The problem is in the code you didn’t post.

1 Like

You're calling begin in your constructor. There's a good reason that the Serial object saves that step for later in setup. The hardware isn't ready until after init() runs. Make yourself a begin method that you can call from setup and put the call to begin in there.

sure...

It may be easier to pass a pointer to the Serial object into the class, for example:

class Context{
  public:
    Context(HardwareSerial* serial){
      stream = serial;
    }

    void send(const char* mssg){
      stream->print(mssg);
    }
    
  private:
    Stream* stream;
};

Context myInstance(&Serial);

void setup() 
{
  Serial.begin(9600);
  myInstance.send("Testing, 1, 2, 3");
}

void loop() {
  // put your main code here, to run repeatedly:

}