Controlling the Arduino over serial
In the Serial output recipe, we've seen how easy it is to print some data from Arduino to the computer. However, this can work the other way. In the serial monitor window in the Arduino IDE, we can write a string and send it to Arduino.
Here, you will learn what to do with that string and how you can use it to control things.
Getting ready
There is just one ingredient needed to implement this recipe—an Arduino board connected to a computer via USB.
How to do it…
Connect Arduino to the computer so that we can start programming it. The following code will start the built-in LED when it receives an 'a'
. It will stop the LED when it receives an 'x'
, and will blink it for a specified amount of time when it receives 'b'
followed by a number from 1 to 9, such as 'b4'
:
int led = 13; void setup(){ pinMode(led, OUTPUT); Serial.begin(9600); } void loop(){ if (Serial.available()){ char com = Serial.read(); // Act according to the value received if (com...