Sometimes you really need to use the Serial port (UART or USART) of Arduino to communicate with your computer (or other devices) for debugging or readings.
Arduino uses digital pins 0 (RX, receive) and 1 (TX, transmission) for Serial communication with all devices and the USB cable for communication with the computer (and the built-in Serial Monitor from the Arduino IDE).
The code for doing this is pretty simple, you just need to initialize the serial port and set the baud rate (symbols per second) like this : Serial.begin(9600); and then receive/transmit using the next functions : print, println and write. For official documentation on this click here.
As an example .. I wrote 2 small programs that does this :
– the first one : uses the Hello World! from the previous post and it outputs to the Serial Monitor the current status of the LED using print and println functions.
– the second one : is fully based on the first example but it also receives data from the computer to turn on/off the LED using the read function.
You can see their code on Tutorialpedia.
To start the Serial Monitor from Arduino IDE .. just click the last button from the option’s bar and set the baud rate to match your own baud rate used while initializing with Serial.begin(). After pressing the Serial Monitor button a new black area will appear where you can send data to your Arduino board or see the output of it.