What board are you using please?
I’m assuming from the use on Arduino.h
that you are using the Arduino framework, but it also looks like you are using some kind of RTOS as well. Can you post your platformio.ini
please.
When posting code, you can easily do it by enclosing the code parts in three back ticks like this:
```
Serial.begin(9600);
// Some other code here...
```
Those are not the same character as the single quote by the way, in case the font in your browser makes it look the same. 
On an Arduino Uno, Serial
is part of the library. When Arduino.h
is included, that file includes a number of other files, one of which is HardwareSerial.h
which defines the structure of a HardwareSerial class.
Also, it runs this code:
#if defined(UBRRH) || defined(UBRR0H)
extern HardwareSerial Serial;
#define HAVE_HWSERIAL0
#endif
Which will work fine on an Arduino Uno and declares Serial
to be an object of the HardwareSerial
class which will be found somewhere else. The actual code for the class is compiled into the library which is linked with your sketch code to create the final binary file for uploading.
So for the Uno, Serial
is known about and is already a global object. This is why executing Serial.begin(9600);
in setup()
works even though you didn’t specifically declare what Serial
is.
If you are using a different board, the code in HardwareSerial.h
for your board will show something similar and should end up defining a global object of type HardwareSerial
named Serial
.
Now, the gibberish you report when you don’t execute a global initialisation is most likely down to the fact that if you don’t call Serial.begin()
and pass a baud rate, the USART will not be correctly initialised. (Unless your board’s version of HardwareSerial::begin()
defines a default baud rate, the Uno doesn’t.
Your code should work fine without needing a global to be declared and initialised. Does the following work for your board?
#include "Arduino.h"
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println("Hello World!");
delay(1000);
}
So, in summary (because I do tend to go on and on a bit!):
- Please tell us your board details;
- Please post your
platformio.ini
file;
- Are you using some form of RTOS?
Cheers,
Norm.