Home » Arduino – Serial Communication

Arduino – Serial Communication

The Arduino boards, and I believe this applies to all of them, even though I have used only two so far (the UNO and the MEGA), allow for Serial Communication. In the Arduino programming IDE, this is referred to as the Serial Monitor.
clip_image002Users often use this to ‘PRINT’ different values from the board, like certain numbers, monitor outputs, or just print statements. What it is not normally used for, is inputting commands, parameters and information in to Arduino. This means that say you can send a command ‘ON’ to turn a unit ON which is controlled by the Arduino, take in your name, or take in a command and parameters and perform an operation for you, say addition.

The beauty of the process is that anyone with a Serial Communication software, like Putty, HyperTerminal, Telnet, etc can use this to talk to the Arduino board, and they don’t even require the Arduino IDE. As long as they know what Serial port and baud rate the Arduino board appears at, they can talk to it. Or, alternatively, software like Processing could be used to send and receive commands using this interface, set up a GUI, and what not. The possibilities become endless depending on how much effort the programmer is willing to put in.

In short, the user can send ASCII commands to the boards, and the board can response as required.

The example code achieves three different functions:
1. Takes in a command, and responds with a set response to that cable. This can be a request for information, request for help.
2. Takes in a command and a parameter, and saves/processes that parameter and returns a set response to that command and parameter.
3. Takes in a command and parameter(s), and performs an operation on the parameter(s) and returns the result.

The code begins with declaring a few variables. These obviously depend on the requirement of the code.

// Command line variables
 String command; // String input from command prompt
 String temp1,temp2; // temporary strings
 char inByte; // Byte input from command prompt
 char carray[6]; // character array for string to int // manipulation
 int a,b,c; // temporary numbers

For the setup () method, setup the serial link with a baud rate of 9600. This could include a start up command like the one that has been commented out, or something that indicates the commands available.

void setup(){

   Serial.begin(9600);
   // Serial.println("Hello, enter your name!");

}

The first thing to check for is if there is an input in the command. This can be checked by using the Serial.available() command. If there is an input, this value is greater than one, indicating the number of bytes available. When nothing is there, this returns -1. This will be the first check in loop().

The second thing to do is to check for any Carriage Return/Line Feed to make sure that the command inserted has actually been inserted. Alternatively, this could be ignored and certain characters could achieve certain outputs. However, to input full words, parameters etc, it is advisable to check for the incoming character as being a CR or NL.

The idea is to concatenate all the characters that are sent to the Serial interface, and there is an option to choose to include only certain characters, or ignore certain characters. This can be done by using an if/else command. The following lines check if there is an input, and then concatenate the characters fed into a string called ‘command’.

void loop(){

   // Input serial information:
   if (Serial.available() > 0){
   inByte = Serial.read();
   // only input if a letter, number, =,?,+ are typed!
   if ((inByte >= 65 && inByte <= 90) || (inByte >=97 && inByte <=122) || (inByte >= 48 &&     inByte <=57) || inByte == 43 || inByte == 61 || inByte == 63) {
   command.concat(inByte);

           }
 }// end serial.available

Next, check if NL/CR are entered, and process the command entered. inByte is the character fed into the serial. Clear that first and then proceed to rest of the code.

// Process command when NL/CR are entered:
 if (inByte == 10 || inByte == 13){

   inByte = 0;

Respond to the different commands available. First, as an example, respond every time the user enters ‘hey’.

// Respond to a command:
 if (command.equalsIgnoreCase("hey")){

   Serial.println("hello there!");

}

Secondly, if the command is not that, check for the next command. This is slightly more complicated, where the customer enters a command in the form of ‘a+b’, the Arduino judges that this is an addition command, takes and stores values a and b as numbers, adds them, and then returns the output. This command uses the following commands:

StringName.substring(x,y) or StringName.substring(x) which converts and returns a substring from index x to y, or from index x to end of string.

StringName2.toCharArray(charArrayName,x), which converts StringName2 to a character array of the name charArrayName of the length x.

Atoi(charArrayName) which converts characters in a character array to integer.

Following is the code to perform that function:

// Perform a function because of a command:
 else if(command.indexOf('+') > 0){

   temp1 = command.substring(0,command.indexOf('+'));
   temp2 = command.substring(command.indexOf('+')+1);
   temp1.toCharArray(carray,6);
   a = atoi(carray);
   temp2.toCharArray(carray,6);
   b = atoi(carray);
   c = a + b;
   Serial.print("The sum of ");
   Serial.print(a,DEC);
   Serial.print(" and ");
   Serial.print(b,DEC);
   Serial.print(" is ");
   Serial.println(c,DEC);

}

Next is a command where if the user enters a command in the form of ‘my name is xyz’, the system responds with a ‘Hello, xyz!’ This checks if the command started with the phrase ‘my name is’ or ‘mynameis’ (because we are not storing spaces in the string), and stores the name value in a temporary string, and then returns the name with a Hello in front of it. This value could be stored and used for other purposes if required.

else if (command.startsWith("mynameis")){

   temp1 = command.substring(8);
   Serial.print("Hello, ");
   Serial.println(temp1);

}

Also, it is very important, to return a phrase that indicates to the user that an invalid command was sent, so the input is acknowledged. This should be done with a bunch of if else clauses to make sure that if none of the commands is input, this automatically displays. This could return something like a bunch of command options, helps, or just an error message.

else {

   if (!command.equalsIgnoreCase("")){

      Serial.println("Invalid argument.");

   }

}

Finally clear the String buffer, and be ready to start the process again.

command = "";

This should explain various usage of the serial interface, and by adapting the above commands, the user can code in their own requirements, and use the Serial port of the Arduino to great advantage.

Reference:

http://arduino.cc/en/Reference/StringToCharArray (String to Char Array)
http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#ga3a1fe00c1327bbabc76688a7a1d73370 (Atoi)

If you found this article and would like to support me by making a donation, do get in touch 🙂 

Related Posts

3 thoughts on “Arduino – Serial Communication

    1. I guess a good way would be to start with one character and see if you can display that. Enter a character via PC and then make it display from a variable where you store it. If you already have text you want scrolling, just add it to a variable and display and manipulate it as you want.

Leave a Reply

Your email address will not be published. Required fields are marked *