I am trying to do a simple serial communication control via sending a char and using it as an if condition, the arduino part is below
char incomingchar;
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
// Serial.write("g"); // does not work when I explicitly write here either as opposed to through python.
}
void loop() {
if (Serial.available()) {
// read the incoming char:
incomingchar = Serial.read();
if (incomingchar=="g"){
Serial.println("hello world!");}
else{
Serial.println(incomingchar);
}
}
}
And here is the Python code:
import serial;
ser=serial.Serial('COM3',9600,timeout=1)
ser.write(b'g')
When I run this, the python program returns a '1', and so does the arduino program in the serial monitor.
Note, if I directly set Serial.write('g'), it simply types out 'g' in the monitor and does nothing else from the loop.
1 Answer 1
You declare incomingchar
as a char
. In your if
you compare that char to a string (double quotes) incomingchar=="g"
. I think you want to compare it to a char
(single quotes) like this:
if ( incomingchar == 'g' ) {
// do something
}
-
Hi Mazaryk, I made the change, it works now (albeit in a different paradigm where serial monitor or Arduino IDE is not open) I think the issue was also that python can't access the port if you have arduino or serial monitor open, so it was preventing me from really testing it. If someone knows how to get over that, would be much appreciated.ha554an– ha554an2017年04月28日 00:23:59 +00:00Commented Apr 28, 2017 at 0:23
setup
doesn't work is because that would be written to the output wire, and you're reading from the input wire.