I am trying to send integer from my Python program to Arduino MEGA. If I send 1, the LED should turn on and If I send 0 the LED should turn off.
I was able to write Python code correctly as I think. I have config the port and made serialWrite(val) function for send data to Arduino only if data is changed.
This not a full program. It has while loop. So, it writes data to Arduino rapidly. I used serialWrite(val) function to prevent that.
But, the LED never turns off, if I send 0. It turns on only. What are the problems in my code?
import serial as ser
prt = ser.Serial(
port='COM3',
baudrate=9600,
parity=ser.PARITY_NONE,
stopbits=ser.STOPBITS_ONE,
bytesize=ser.EIGHTBITS
)
preSerVal=0
#function for send data..data will send only val is changed
def serialWrite(val):
global preSerVal
if(not preSerVal == val):
prt.write(str(val)+'\r\n')
preSerVal=val
This is my Arduino program.
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
}
byte incomingByte;
void loop()
{
if (Serial.available() > 0) {
incomingByte = Serial.read();
if (incomingByte == '1') {
digitalWrite(13, HIGH);
} else if (incomingByte == '0') {
digitalWrite(13, LOW);
}
}
}