Python Forum

Full Version: Not receiving serial data from arduino
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys. So, I am trying to receive serial data from my Arduino Uno.
The Arduino sends the heading from a magnetometer over serial, but the Python code does not receive it.
This is my Python code:
import serial

Arduino = serial.Serial("COM3", baudrate = 9600) # serial device
angle = 0
Compass() #This function draws the compass 

while (True):
    
    try:
        flushInput()
        angle = Arduino.readline()
        angle = angle.strip()
        angle = int(angle)
        compasspointer.settiltangle(-angle+90)  #update heading
        print(angle)
    except:
        pass
My Arduino code:

void setup()
{
Serial.begin(9600);
}

int heading=105;//just a value
void loop()
{
Serial.println(heading);
thanks for your help!
First thing, did you try to receive data with Arduino Serial Monitor, does it work fine there?
Another thing is you should catch your exception and print it.
Also you may want to print angle before you use strip(). It may look something like "105\n105\n105\n105\n105\n105\n". Even if you use strip(), it can't be converted to integer like that. But, as said, if this error happens you can't know, because you don't catch the exception.

    except as e:
        print(e)
Thank you very much. I caught an exception and saw that it was receiving 'b[value]\r\n
Then I googled and found that I should have decoded the data.
Now the code looks:
Arduino = serial.Serial("COM3", baudrate = 9600) # serial device
angle = 0

Compass()
while (True):
    
    try:
        angle = Arduino.readline()
        print(angle.decode('utf-8'))
        angle = int(angle)
        compasspointer.settiltangle(angle) 
    except:
        pass
Thank you very much. This is the second time I am interacting with python code. I am using C/C++ but I can't deny that when you need to write something fast, python is the best way to go
I am glad you got it working, and thanks for posting your solution!
I regret not mentioning decoding earlier, since not too long ago I had almost same issue because of that.