0
votes

i am trying to send some integer values from Python to Arduino using the serial port, Python code seems to be working because i see the TX LED flicker on the Ardunio board, but still my LED connected to the 12th pin does not light up, Arduino code also seems to be working because when i open the serial port of the IDE of Arduino and i send '1' the LED lights up so i think there is some kind of incompatibility between the data sent by Python and the type Arduino expecting. Python Code:

ser = serial.Serial('COM3', 9600)
time.sleep(1)
ser.write('1'.encode())

Arduino Code:

void setup() {
Serial.begin(9600);
pinMode(12,OUTPUT);
}

void loop() {
int X;
if (Serial.available()>0)
{
  X = Serial.read();
  if(X == '1')
  {
    digitalWrite(12,HIGH);
    }
  else if(X == '0')
  {
    digitalWrite(12,LOW);
    }
}
}

so my questions are:

1)_what seems to be the problem in the codes?

2)_what type of data does Arduino expect to get from the serial port?

3)_what is the best way to send an integer value over 255 from Python to Arduino? is this a proper way ?

ser = serial.Serial('COM3', 9600)
S = 102
time.sleep(1)
data = [int(x)for x in str(S)]
for d in data:
    c = bytes(str(d), "ascii")
    ser.write(c)
2
try doing a Serial.write(X) and reading it back in python... also try try using Serial.readString ... i think what Serial.read gets is ord('1') or 48 .. where as readString gets "1" (maybe...)Joran Beasley
so i tried reading the data back in Python and what ever i send i read back b'\xff' but when i read it with Serial.readString() in Python i read back b'-\r'AbuAlkasim
@JoranBeasley what do you sir think ?AbuAlkasim
hmm i might get a chance this weekend to pull out my arduino and give it a shot ... remind me on sat (you know how to reach me (via various channels))Joran Beasley
i will remind you sir, thank you.@JoranBeasleyAbuAlkasim

2 Answers

0
votes

I think you are messing up with the types Serial.read gives you byte , you need to convert it into char to compare.

try

   X = atoi((char)Serial.read())

Reading the byte -> converting it to char -> converting into int

Then you can use if conditions as

if (X == 1)
0
votes

i defined X at the beginning of the script as a char and the problem was solved.