Serial output
Lesson #4—Getting your Arduino to write to youTheory
The baud rate is the speed of a communication system. Mathematically, a baud rate is the number of symbols per second that are transmitted. We use a binary code, so a “symbol” is a 1 or a 0.
A common serial baud rate is 9600 symbols per second. Using typical settings, a letter will consume 10 symbols, resulting in an effective speed of 960 letters per second. (There are 8 bits in a byte, plus the serial protocol uses one “start bit” to signal the beginning of a byte and one “stop bit” to mark the end of a byte, so 8+1+1=10 symbols per letter.)
Code
void setup() {
// put your setup code here, to run once:
// Set the baud rate
Serial.begin(9600);
}
// Create an integer variable called "counter" and
// initialise it to zero
int counter = 0;
void loop() {
// put your main code here, to run repeatedly:
// Increase counter
counter = counter + 1;
// Print out the value of the counter
Serial.print("Counter = ");
Serial.print(counter);
Serial.println();
// Reset when the counter reaches 15
if (counter == 15) {
Serial.println("Resetting ...");
counter = 0;
}
// Wait 500 ms
delay(500);
}
Once you have uploaded your program, open the “Serial Monitor” window in the Arduino program to see the messages being sent.
Save your work as lesson4. Each lesson should be saved into a separate file.
Topics for workshop discussion
- Variables (like
counter
) are named containers that hold a value. - The value of a variable is changed using an
=
sign. The=
does not imply an equation in the algebraic sense. - A single equals sign
=
is an instruction; a double equals sign==
is a question. A common mistake is to confuse these. println
(print line) ends the current line whereasprint
does not.
Exercise
- Make the message counter run down instead of up.
- Turn the LED on (see previous lesson) when the countdown timer reaches zero, keep it on for 3 seconds, then turn it off and restart the countdown.