Sunday, 21 July 2013

Serial Communication - What, Where & How?

Serial Communication


The Induino R3 / Arduino Boards, provide a number of facilities for communicating with a computer, another Arduino, or other microcontrollers. The ATmega328 provides UART TTL (5V) serial communication, which is available on digital pins 0 (RX) and 1 (TX). A FT232RL IC on the board channels this serial communication over USB and appears as a virtual com port to the computer.  The Arduino software includes a serial monitor which allows simple textual data to be sent to and from the Arduino board. The RX and TX LEDs on the board will flash when data is being transmitted via the USB-to-serial chip. This Serial Communication channel is used by the Arduino IDE to program the microcontroller. We can make use of the same channel to send run-time data to the board from a connected computer / device or to send run-time data from the board to  a connected device (helpful in debugging).

Lets see how we can print some data from our Board to the Computer.  We will need a few functions to achieve this.

  • Serial.begin(buad rate) => The Serial.begin() function initiates a serial communication at the given baud rate. baud rate is the rate of data transfer in bits per second.  For communicating with the computer, use one of these rates: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200.  This function is called from within the setup() function.
  • Serial.print(value) => The Serial.print() function prints the given value back to the connected device. The value can be a string, character or a variable.
  • Serial.println(value) => The Serial.println() function is similar to the Serial.print() function, only that it prints a new line character at the end of the line.
Here's a slight modification to our last program - Button controlled Binary Counter. On every Button press we shall print the current counter value. To view the output of this program, you need to used the Arduino IDE's Serial Monitor (Click the Lonely Icon on the Top Right Side or go to Tools - > Serial Monitor). In the Serial Monitor window, ensure that the baud rate selected (at the bottom right corner) is the same as the one used in the program)


/*  Induino R3 User Guide - Program 3.0 - Button controlled Binary Counter with Serial Print
This sketch increases a 3 bit number every time a button is pressed by the user and shows the output on 3 LEDs   
 */  

 int i = 0;  
 char txt[]="The Current Value is : "; // A string stored in a character array
 void setup()  
 {  
  pinMode(11,OUTPUT);   // declare LED pins as output pins  
  pinMode(12,OUTPUT);  
  pinMode(13,OUTPUT);  
  pinMode(7,INPUT_PULLUP);// declare the Button as INPUT pin with internal Pull up enabled
  Serial.begin(9600); // initialize Serial Communication
  Serial.println("Starting the Program");// This will be printed only once
 }  
 void loop()  
 {  
  if(digitalRead(7)==0)  // if the button is pressed  
  {  
   if(i<7)        // if counter value is less than 7 or 3 bits  
    i++;        // increment counter value  
   else           
    i=0;        // reset counter to 0  
   Serial.print(txt); // Print Descriptive test from the character array
   Serial.println(i); // print the current value
   int a=i%2;      // calculate LSB   
   int b=i/2 %2;     // calculate middle bit  
   int c=i/4 %2;     // calculate MSB   
   digitalWrite(11,a);  // write LSB 
   digitalWrite(12,b);  // write middle bit  
   digitalWrite(13,c);  // write MSB  
   while(digitalRead(7)==0);  // wait till button is released to avoid incrementing the counter again  
   delay(100);         // small delay to avoid debounce  
  }  
 }

Now that was sending data to the computer, what if we wanted to receive data from the computer? 
Let's see how we can do this, first we would need a few more functions
  • Serial.available() => All Serial data coming into the microcontroller is stored in a serial buffer. The Serial.available() function returns the size of the available data in the Serial Buffer in BYTES. We can use this function to determine if there is incoming data or not. The Serial Buffer can hold upto 64 Bytes of Data
  • Serial.read() => The Serial.read() function reads 1 BYTE of data at a time and returns the BYTE value for the same.  The moment a piece of data leaves your computer / microcontroller it loses its variable type and is simply treated as a BYTE(ASCII) value. When you send 'A' from your computer / microcontroller, the corresponding ASCII value 65, is what is sent out. Depending upon the variable type you store it in, it can read as either a character or a number. The 65 when stored in a character variable will be stored as 'A' and when stored in an integer variable will be stored as 65. once the Serial.read() functions reads a byte of data that byte of data will be removed from the Serial Buffer.
Now let's modify our last program for an added Input coming from the Serial Port of our computer.  Let's say the user wants to change the current counter value of the binary counter, We cad do this by using Serial communication for input. Any time the user inputs a number between 0 & 7, we shall use it as the current counter value and display the same in the binary format using our binary counter.

Here's the outline of the logic

  • Keep checking for either button press / or data in the serial buffer.
  • On button press increase the counter and display the value on the leds
  • On serial data being received, read the byte, check if it is between 0 & & and then set the counter value to the value received. Finally display the counter value on the leds.

Here's the Program
/*  Induino R3 User Guide - Program 3.1 - Serial Input / Button controlled Binary Counter with Serial Print
 This sketch increases a 3 bit number every time a button is pressed by the user and shows the output on 3 LEDs   
 */

int i = 0;  
char txt[]="The Current Value is : "; // A string stored in a character array
void setup()  
{  
  pinMode(11,OUTPUT);   // declare LED pins as output pins  
  pinMode(12,OUTPUT);  
  pinMode(13,OUTPUT);  
  pinMode(7,INPUT_PULLUP);// declare the Button as INPUT pin with internal Pull up enabled
  Serial.begin(9600); // initialize Serial Communication
  Serial.println("Starting the Program");// This will be printed only once
}  
void loop()  
{  
  if(digitalRead(7)==0 || Serial.available()>0)  // if the button is pressed  or Serial data is received
  {
    if(digitalRead(7)==0) // if the button is pressed
    {  
      if(i<7)        // if counter value is less than 7 or 3 bits  
        i++;        // increment counter value  
      else           
        i=0;        // reset counter to 0  
      while(digitalRead(7)==0);  // wait till button is released to avoid incrementing the counter again               
      delay(100);         // small delay to avoid debounce  
}
    if(Serial.available()>0) // if Serial data is received
    {
      int val = Serial.read(); // read 1 byte of data and store in the integer variable val. if the user sent 1, the ascii value for 1 is 49 so val will have the value 49
      val = val - 48; // 48 is the ascii value for 0. So if we did receive a 0 subtracting 48 would make the value of val as 0, same is true for the remaining numbers
      if(val>=0 && val <=7)// Check if Val is in the range of 0 to 7, we can display only values in this range and ignore all other values
      {
        i = val; // assign the counter to the value received from the Serial Port
      }

    }
    Serial.print(txt); // Print Descriptive test from the character array
    Serial.println(i); // print the current value
    int a=i%2;      // calculate LSB   
    int b=i/2 %2;     // calculate middle bit  
    int c=i/4 %2;     // calculate MSB   
    digitalWrite(11,a);  // write LSB 
    digitalWrite(12,b);  // write middle bit  
    digitalWrite(13,c);  // write MSB  
    
  }  
}

With that we will stop our overview of Serial Communication. You can read more about other Serial functions and their usage here => http://arduino.cc/en/Reference/Serial


Thats It For This Part! Enjoy... and feel free to drop us an email with questions you might have -> info@simplelabs.co.in

Visit www.simplelabs.co.in for more interesting products

Back to List of Contents

2 comments:

  1. Thanks for explaining the serial port in detail. Found this post to be very useful!!

    ReplyDelete
  2. Excellent examples of concept code, and article generally very good and interesting framed, thank you for sharing such a useful information
    Richard Brown virtual data room providers

    ReplyDelete