Introduction
The Serial port (UART or USART) of Arduino is used to communicate with your computer (or any other capable devices) for debugging, readings or commands sending.
To see more details about the whole process take a look at the link above.
Examples
All the code below is based on the Hello World! example : Blinking a LED with Arduino .
Example for using print/println functions
The code below shows the LED status (on or off).
//the pin on which you connect the anode (+) of the LED byte ledPin = 13; //our on/off switch byte state = LOW; //this function runs only once (after reset) void setup(){ //open the serial port and set data rate to 9600 bps Serial.begin(9600); //set the pin we use to OUTPUT so we can power-up the LED pinMode(ledPin, OUTPUT); //send our status Serial.println("Program started."); Serial.print("The LED connected to GND and PIN "); Serial.print(ledPin, DEC); Serial.println(" will start to blink!"); } //this function runs continuosly (after setup) void loop(){ //toggle our switch (if off make it on and vice-versa) if (state == LOW){ state = HIGH; } else { state = LOW; } //toggle the LED based on our switch above digitalWrite(ledPin, state); //send the LED status Serial.print("The LED is : "); if (state == LOW){ Serial.println("OFF"); } else { Serial.println("ON"); } //sleep for 3000 ms = 3 seconds delay(3000); }
Example for using read function
The code below waits for a command from the Arduino's IDE Serial Monitor to turn on or off the LED.
//used to store what we receive int incomingData = 0; //the pin on which you connect the anode (+) of the LED byte ledPin = 13; //this function runs only once (after reset) void setup(){ //open the serial port and set data rate to 9600 bps Serial.begin(9600); //set the pin we use to OUTPUT so we can power-up the LED pinMode(ledPin, OUTPUT); //send our status Serial.println("Program started."); Serial.print("The LED connected to GND and PIN "); Serial.print(ledPin, DEC); Serial.println(" will be on if you send '1' or off if you send anything else!"); } //this function runs continuosly (after setup) void loop(){ //look if we have data if (Serial.available() > 0) { //get the sent data incomingData = Serial.read(); Serial.print("We received : "); Serial.println(incomingData, BYTE); Serial.print("The LED is : "); //49 = ASCII code for '1' if (incomingData == 49){ digitalWrite(ledPin, HIGH); Serial.println("ON"); } else { digitalWrite(ledPin, LOW); Serial.println("OFF"); } Serial.println(); } }
The output (as seen on the Serial Monitor) should be like this :
Program started. The LED connected to GND and PIN 13 will be on if you send '1' or off if you send anything else! We received : 5 The LED is : OFF We received : 1 The LED is : ON