Receiving Serial Data in Arduino

Posted by Unknown on Monday, August 04, 2014 with No comments
You want to receive data on Arduino from a computer or another serial device; for
example, to have Arduino react to commands or data sent from your computer.


It’s easy to receive 8-bit values (chars and bytes), because the Serialfunctions use 8-bit values. This sketch receives a digit (single characters 0 through 9) and blinks the
LED on pin 13 at a rate proportional to the received digit value:

/*
* SerialReceive sketch
* Blink the LED at a rate proportional to the received digit value
*/
const int ledPin = 13; // pin the LED is connected to
int blinkRate=0; // blink rate stored in this variable
void setup()
{
Serial.begin(9600); // Initialize serial port to send and receive at 9600 baud
pinMode(ledPin, OUTPUT); // set this pin as output
}
void loop()
{
if ( Serial.available()) // Check to see if at least one character is available
{
char ch = Serial.read();
if( isDigit(ch) ) // is this an ascii digit between 0 and 9?
{
blinkRate = (ch - '0'); // ASCII value converted to numeric value
blinkRate = blinkRate * 100; // actual rate is 100ms times received digit
}
}
blink();
}
// blink the LED with the on and off times determined by blinkRate
void blink()
{
digitalWrite(ledPin,HIGH);
delay(blinkRate); // delay depends on blinkrate value
digitalWrite(ledPin,LOW);
delay(blinkRate);
}
Upload  the sketch and send messages using the Serial Monitor. Open the Serial Monitor
by clicking the Monitor icon and type a digit in the text box at the top
of the Serial Monitor window. Clicking the Send button will send the character typed
into the text box; if you type a digit, you should see the blink rate change


Categories: