int ledPin = 13; // Built in LED on Arduino
int incomingData; // To hold value of data coming through COM port
void setup(){
pinMode(ledPin, OUTPUT); // Set ledPin to output
Serial.begin(9600); // Setup serial with baud rate of 9600 (this must be same on Roborealm)
}
void loop(){
// Wait until there is new data available at COM port
if (Serial.available() > 0){
// Read the value and store in incomingData
incomingData = Serial.read();
}
Serial.println(incomingData);
// If the value of the data is greater than 0 then turn on LED
if (incomingData > 0){
digitalWrite(ledPin, HIGH);
}
else {
digitalWrite(ledPin, LOW);
}
}
If I type 0 in the serial monitor and hit send, it returns the value 48. If I type 1 it returns 49 and so on. Does anyone know whats wrong?
When you send a 0 from Serial, you are sending an ASCII 0.
Since you are reading this into an int variable, the Arduino treats it as it's hex value. Search Google ascii table to see the hex value for each character.
What you need to do is capture the incoming serial data to a char variable. Then convert it to an integer using the atoi() function.
Something like:
int ledPin = 13; // Built in LED on Arduino
//thurston - changed the incoming variable type to char
char incomingData; // To hold value of data coming through COM port
void setup(){
pinMode(ledPin, OUTPUT); // Set ledPin to output
Serial.begin(9600); // Setup serial with baud rate of 9600 (this must be same on Roborealm)
}
void loop(){
// Wait until there is new data available at COM port
if (Serial.available() > 0){
// Read the value and store in incomingData
incomingData = Serial.read();
}
Serial.println(incomingData);
//thurston - the next line converts the character "0" to a number 0
int numericVal = atoi(incomingData);
// If the value of the data is greater than 0 then turn on LED
//thurston - change the reference to the number 0 instead of the character 0.
if (numericVal > 0){
digitalWrite(ledPin, HIGH);
}
else {
digitalWrite(ledPin, LOW);
}
}
I'm pretty new to C (I've worked in Python and PHP in the past) and these "tricks" keep blowing my mind.
I'll have to play around with that a bit to see if I can cut a few more bytes out of one of my projects.