For one of my tests, I needed a communication using a serial port. I decided to use an Arduino board and the reason behind that is simple – you need to add only 3 lines of code to the default Arduino sketch to create a serial communication between the board and another serial device (most commonly a computer).

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available() > 0){
    Serial.write(Serial.read());
  } 
}

Above you can see the source code containing the two special functions part of every Arduino sketch. In the first function setup(), we need to configure the serial communication. This is done using the Serial library. In the example above, we set serial communication with a 9600 baud rate. All other serial configurations are left to their default values.

The second function is loop(). In this function, we add code that will be repeated on a loop. Here we will check if any data has been received on the serial communication channel. If data is available we will read it and send it back, thus creating an echo. To read and send back the data we use Serial.write(Serial.read()). To check if data is available we use Serial.available(). This must be done because we should send back only valid received data.

That is all – 3 lines of code added – easy and simple.

Was this post helpful?