Using Serial object within a library class

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 {
    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);
    String _stateName;
    int _stateId;


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?


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.


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

class Context{
    Context(HardwareSerial* serial){
      stream = serial;

    void send(const char* mssg){
    Stream* stream;

Context myInstance(&Serial);

void setup() 
  myInstance.send("Testing, 1, 2, 3");

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