Receiving from computer

To receive data over the Arduino serial port you need two commands: Serial.available() and Serial.read().

Example 3.7

In this example, you will turn the on-board LED on or off by sending an ‘H’ or ‘L’ to the Arduino board from the serial monitor.

Materials

  • 1 Arduino Uno board

Instructions

  1. Upload the code below.
  2. Open the serial monitor.

Result

In the the top of the serial monitor there is a text input box with a send button next to it. You should type ‘H’ in the input box and click the send button. The on-board LED should now turn on. Similarly, you should send ‘L’ and the LED should turn off. Note that it will only work with uppercase letters.

New commands

  • Serial.available(): returns the number of bytes waiting to be read from the serial port.
  • Serial.read(): reads the incoming serial data. You only need to read if there are bytes available.

How it works

  • The variables ledPin and incomingByte are declared. incomingByte will be used to hold the incoming serial data.
  • In setup(), the serial communication is initialized with the speed 9600 bits per second.
  • Pin 13 is configured as an output.
  • You only want to read from the serial port if there is data coming through. So first thing that happens in loop() is to check if the number of bytes waiting to be read is greater than 0.
  • If the number of bytes waiting is not greater than 0, the program skips the code inside the curly brackets. Since there is no other code to be executed after this if statement, the program jumps to the beginning of loop().
  • If the number of bytes is greater than 0, the serial data is read and stored in incomingByte.
  • If incomingByte is equal to ‘H’, the on-board LED is turned on.
  • If incomingByte is equal to ‘L’, the on-board LED is turned off.
  • loop() continues to loop.

Learn by doing

  • Check any of the examples in File -> Examples -> EducationShield-> Help. Almost all of them make use of the serial port.
  • Take two 9V batteries and make one Arduino control another. The Arduino that receives signals should have the code above in it. The Arduino sending signals should send out “H” or ”L” alternately.