Sunday 25 January 2015

7. Serial communication from a computer or external device from an Arduino


PC to Arduino communication


This post describes on how a PC or any other wireless or wired device is going to send a message to a Arduino.This will explain a serial communication of a PC-Arduino & a Bluetooth-Arduino.


PC communication with a Arduino (Receiving serial data in Arduino)

It is easy to receive 8-bit values ,because at Serial functions use 8 bit values.The following sketch receives a digit from the computer and blinks the LED based on the number which is pressed on the computer's keyboard.


int ledpin=13;
int blinkRate=0;

void setup()
{
  Serial.begin(9600);   //STARTS THE SERIAL COMMUNICATION
  pinMode(13,OUTPUT);   //ACTIVATES THE ONBOARD LED
}
void loop()
{
  if(Serial.available())
  {
    char ch=Serial.read();
    if(isDigit(ch))   //if it is a number bw 0 to 9 (checks the ascii value
    {
      blinkRate(ch-'0');  //entered number's ASCII value is converted to number
      blinkRate=blinkRate*100;
    }
    digitalWrite(13,HIGH);
    delay(blinkRate);
    digitalWrite(13,LOW);
    delay(blinkRate);
  }
}
      

Descriptoin

The above sketch gets an input from the serial communication and converts it to no of seconds to blink.

Step 1:  check whether Serial connection is avail by Serial.available().
Step 2:  Read the input .
Step 3: The read input will be in ASCII so convert it to numeric value.
Step 4: Convert the numeric value to seconds to notice the blink( if we dont convert then the blinks will be soo fast that it wont be visible with our eyes instead we need a high frame rate camera to see it).
Step 5:Use the blink sketch and blink the LED with respect to the BlinkRate of number.




No comments:

Post a Comment