Serial output

Theory

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

Exercise

  1. Make the message counter run down instead of up.
  2. 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.

This work is licensed under a Creative Commons Attribution 4.0 International License. For comments or corrections, please contact [email protected].