It’s time for the classic programming example – hello, world. In this lesson, you’ll write a small program that repeatedly outputs the line “hello, world” in your Serial Monitor.
Setting up the connection in the sketch
You already know how to open the Serial Monitor in the sketch window (using the magnifying glass in the top right). However, before any data can appear there, you need to start it in your sketch as well – this is a one-time setup, which is why the code for this goes in the setup function:
void setup() {
Serial.begin(9600);
}
Here you extend the Serial function with the begin() command to establish the connection. Make sure to include the period between Serial and begin.
Between the round brackets, you provide the function with the baud rate – in our case 9600. As you learned in the previous lesson, this must match the setting in the Serial Monitor.
Displaying characters in the Serial Monitor
Now comes the interesting part. Enter the following code in the loop:
Serial.print("Hello, World!");
Serial.println();
delay(1000);
In the first line, you can see the .print() command. Between the brackets is the string “Hello, World!”. As you can see, this small greeting is enclosed in quotation marks – this is particularly important and a common source of errors.
If you remove the quotation marks for testing, you’ll receive an error message. This is because “Hello” would then be interpreted as a variable – and not as a string. We’ll cover the topic of variables in the next lesson.
The line below says Serial.println(); – this (“ln”) creates a new line in the Serial Monitor. If you didn’t do this, your Arduino would simply write the characters one after another.
However, you can also combine these two commands – the greeting and the new line – and save yourself a line of code:
Serial.println("Hello, World!");
Finally, in the loop you’ll find a delay of one second. Copy this complete sketch and upload it to your Arduino UNO (you can find it also for download in the Exercise Files tab):
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print("Hello, World!");
Serial.println();
delay(1000);
}
Does the greeting appear in your Serial Monitor?
In the next lesson, we’ll cover one of the most important topics: Variables 🙂