When you put the Serial.begin
in the constructor and declare the Command
object at file scope, the Serial.begin
will occur before setup()
. Not recommended, perhaps not allowed.
If you do that, the compiler has to figure out that the Serial
instance must be constructed before the Command
instance is constructed. It can't always figure out the correct order.
In general, this is why you see many classes with a begin
or init
method. This allows the construction of file-scope instances to take place in any order, before setup
. Then setup
does the Command.begin()
, which finally calls Serial.begin
, long after Serial
has been constructed.
Also, using SerialEvent
is no better than doing the polling in loop()
. If you're busy doing something else, SerialEvent
does not get called. If you need to handle characters in the background, in the RX interrupt, you might want to take a look at a modified version for the Serial
object(s) I posted, NeoHWSerial. You can attach a routine to be called whenever a character is received.