Receive data from Arduino in Python

I am trying to receive the data from Arduino in Python.

The sensor is MPU6050. A part of the Arduino code shown correctly on the serial monitor is:

  // Temp
  float temp = mpu.readTemperature();
  Serial.print(" Temp = ");
  Serial.print(temp);
  Serial.println(" *C");

My problem is that I am trying to receive the data with this documentation: Python Language Tutorial => Read from serial port

import serial

ser = serial.Serial("/dev/ttyUSB0", 115200, timeout=0)

data = ser.readline()
print(data)

But, the only thing I receive is:

b''

I do not know what I'm doing wrong.

1 Like

Do you think that it might help if you posted your Arduino code ?

The easier you make it to read and copy the code the more likely it is that you will get help

Please follow the advice given in the link below when posting code

You're right. I apologize.

Arduino:

/*
    MPU6050 Triple Axis Gyroscope & Accelerometer. Temperature Example.
    Read more: http://www.jarzebski.pl/arduino/czujniki-i-sensory/3-osiowy-zyroskop-i-akcelerometr-mpu6050.html
    GIT: https://github.com/jarzebski/Arduino-MPU6050
    Web: http://www.jarzebski.pl
    (c) 2014 by Korneliusz Jarzebski
*/

#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;

void setup() 
{
  Serial.begin(115200);

  Serial.println("Initialize MPU6050");

  while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }
}

void loop()
{
  float temp = mpu.readTemperature();

  Serial.print(" Temp = ");
  Serial.print(temp);
  Serial.println(" *C");
  
  delay(500);
}


Python:

import serial

ser = serial.Serial("/dev/ttyUSB0", 115200, timeout=0)

data = ser.readline()
print(data)

Output:

b''

Your python code only reads once immediately after opening the port. However, opening the port resets the Arduino and the boot loader takes a few seconds before handing control over to your Arduino code. So it does not find anything to read.

For testing, set the timeout in the python code to e.g. 5 seconds.

Note:
I've just started with python so might be totally wrong.

1 Like

My tutorial on Arduino to Arduino/PC has complete Arduino sketches and python code to do this.
It sends a 'line' at a time in either direction and importantly for your sketch, it is tolerant of loop()s have delay( ) in them, as yours has.

I am in the process of simplifying the code so keep an eye on that page for updates.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.