You can use Serial.read()
to get data from the Arduino serial port.
The following example shows how to use a computer to control an LED on your Arduino. We will use the on-board LED so all you need to do is to upload following code:
int ledPin=13; int incomingByte; void setup() { Serial.begin(9600); pinMode(ledPin,OUTPUT); } void loop() { if(Serial.available()>0){ incomingByte=Serial.read(); If(incomingByte==’H’){ digitalWrite(ledPin, HIGH); } If(incomingByte==’L’){ digitalWrite(ledPin,LOW); } } }
Open the serial monitor from Tools -> Serial Monitor. There’s a text input box with a Send button next to it. Type “H” in the input box, click the send button – you should see the on-board LED turn on. Similarly type “L” and send – the LED will turn off. Make sure you are using upper case.
The commands used above:
Serial.available()
: Checks if there are any signals coming from the serial port. Returns eithertrue
orfalse
.Serial.read()
: Reads a byte from the serial port.
We only want to read from the serial port if there is data coming through. So first we check for data with Serial.available
. If there is something to read, we read it with Serial.read()
and store it inincomingByte
. We then check if incomingByte
equals to ‘H’ or ‘L’ and turn the LED on or off accordingly.
Experiment Further
- Check any of the examples in File -> Examples -> BasicEducationShield-> Help. Almost all of them make use of the serial port. For example, the breath light program is controlled with the data from the serial port.
- If you have two 9V batteries, 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.