Tuesday 17 May 2016

Arduino Tutorial # 8 - The Serial Monitor to send and receive data




Introduction




Arduino IDE uses serial communication to communicate between your PC and Adruino broad via USB. The serial monitor acts as a terminal that can be use to send and receive serial data. 


What is Serial Data transfer?


The word serial means "one after the other". The serial data transfer is when we transfer data one bit at a time.

Data is passed back and forth between the computer and Arduino that consist series of "1's" and "0's".

A single bit is either a zero or a one.
8 bits = 1 byte
1024 bytes (8192 bits)  =  1 Kilobyte (KB).
1024 KB (1048576 bytes) = 1 Megabyte (MB)
1024 MB   = 1 Gigabyte (GB)


We already used serial communication before when we program the Arduino with USB. You may notice that the "TX" and "RX" LED lights in Arduino board flashers while uploading a sketch to Arduino and that indicates the serial communication between Arduino and PC.

Serial Monitor



The serial monitor is the terminal that communicates between the computer and your Arduino. You can use it to  send and receive text messages, for debugging sketchers and also to control the Arduino from a keyboard.

You can open the serial monitor by clicking the icon on the far right of your Arduino IDE. Arduino must be connected to PC to activate serial monitor.




Control LED with Serial Monitor - sending data to serial monitor


Let 's see how to on and off LED by sending command from serial monitor. 

Parts you will need

1X breadboard
1XArduino board (i am using Uno)
1XLED
1X220 ohm resistor
Jumper wires



Connect the components are per the below breadboard setup.





Upload the code given below,



char c; // declare "char" variable

void setup(){
pinMode(2,OUTPUT); // define pin 2 as output
pinMode(3,OUTPUT); // define pin 3 as output
Serial.begin(9600); // starts serial communication
}

void loop()
{
if (Serial.available()>0) // 
send data only when you receive data
{
c = Serial.read() - '0'; // read the character from serial monitor
Serial.flush();
digitalWrite(c,!digitalRead(c));
}
}


Now open the serial monitor and type "2"and press send. LED connected to pin 2 will turn on and if you send "2" again it will turn off. You can do the same to other LED by typing "3".


Let's talk about the code


We have declare a "char" variable called "c". The "char" stands for character and it can hold a single character. In setup(), we define pin 1 and 2 as outputs

The command Serial.begin(9600);  will start serial communicator so that the arduino can send commands through USB. "9600" called "baud rate" of the connection and this is how fast that we send data. We can change it to higher value but it should be changed in serial monitor to the same value. 




In the loop(), 


if (Serial.available()>0)

Everything that happens inside the loop is contained within an 'if' statement. So unless the call to the built-in Arduino function 'Serial.available()' is 'true' then nothing else will happen.

Serial.available() will return 'true' if data has been send to the Arduino and is there ready to be processed. Incoming messages are held in what is called a buffer and Serial.available() returns true if that buffer is Not empty.

If a massage received,

c = Serial.read() - '0'; 

This line reads the character from the serial port. The charterers are represented with numeric codes in the ASCII table. The zero is represented by 48 and the number 2 by 50. So we just have to subtract the character 2 from the 0 to get an integer value.


digitalWrite(c,!digitalRead(c));


Then we use "c" value to read the port and flip it to negation. For example if the "c" value is "2" digitalWrite will give the command to port 2 and at that time if the port 2 LED is "LOW" it will make "HIGH" or if it is "HIGH" it will make "LOW".


You can add upto 9 LED's in this setup by adding pinMode(X,OUTPUT);   to the code. Change the "X" to output pin.


That's all about sending command to arduino by using Serial Monitor.

Download the sketch - Download



Control LED with Serial Monitor - receiving data to serial monitor


You can use the below sketch to same breadboard setup and receive data to serial monitor.



int greenPin = 2; // declare greenPin variable
int redPin= 3;// declare redPin variable
char rx_byte = 0;// declare "char" variable

void setup() {
  Serial.begin(9600);// starts serial communication
  pinMode(greenPin, OUTPUT);// define greenpin  as output
  pinMode(redPin, OUTPUT);  // define redpin  as output
}


void loop() {
  if (Serial.available() > 0) {    // is a character available?
    rx_byte = Serial.read(); 
  
    switch (rx_byte) {
      
      case '1':
        digitalWrite(greenPin, HIGH);
        digitalWrite(redPin, LOW);
        Serial.println("GREEN LED is ON");
      break;
      
      case '2':
        digitalWrite(greenPin, LOW);
        digitalWrite(redPin, HIGH);
        Serial.println("RED LED is ON");
      break;
      
      case '3':
        digitalWrite(greenPin, HIGH);
        digitalWrite(redPin, HIGH);
        Serial.println("Both LED's are ON");
      break;
      
      case '4':
        digitalWrite(greenPin, LOW);
        digitalWrite(redPin, LOW);
        Serial.println("Both LED's are OFF");
      break;
      
      case '5':
        Serial.println("------- MENU -------");
        Serial.println("1. Switch RED LED on.");
        Serial.println("2. Switch GREEN LED on.");
        Serial.println("3. both LED's trun on");
        Serial.println("4. both LED's trun off");
        Serial.println("5. This menu.");
        Serial.println("--------------------");
      break;
      
      default:
        Serial.println("Invalid option");
      break;
    } // end: switch (rx_byte)
  } // end: if (Serial.available() > 0)
}



First part is to declare our variables. Hope you cloud able to understand in setup() function easily (if you follow my tutorial series).




void loop() {

  if (Serial.available() > 0) {    // is a character available?
    rx_byte = Serial.read(); 


Here if (Serial.available() > 0) we are checking a character available or not and read the character from the serial port rx_byte = Serial.read();


We are using a new statement called "switch" , Switch statement is similar to using if with multiple else-if constructs. switch is used in conjunction with "break".
Using switch instead of multiple else-if constructs is easier to read and has more flexibility. Below image shows the structure of switch statement.





In our sketch, the switch statement is placed inside an if statement in the main loop. The switch statement will only run if a new character is received from the Serial Monitor window.

When a character is received from the Serial Monitor window, the switch statement will check for a matching case value. If the character '1' is received, then the GREEN LED is switched on and the "GREEN LED is on" message displayed in the Serial Monitor window.

If '2' is received, the RED LED is switched on. '3' both the LED's switched on. "4" 
both the LED's switched off and "5" displays a menu of the options available in the sketch.

If any character is sent that does not match the characters in any of the case statements, then the code in the default part of the switch body is run which displays "invalid option".
The "break" statement is used to break out of the body of the switch statement. And "break" can also be used to break out of any loop such as a "while" or "for" loop. 

Download the sketch - Download

No comments:

Post a Comment