MPU6050 +Arduino+Python

I am trying to read the ouput of MPU6050 connected to Arduino using Python so that I could do vibration measurement of the motor. I am able to split and also convert the string to float and get all 6 values (Ax,Ay,Az,Gx,Gy,Gz) but im not able to plot it using matplotlib and also the code also stops executing with some errors like:

ValueError: could not convert string to float: '1.01.05\r\n'

or

IndexError: list index out of range

Please Help!!! I am a beginner, I am not sure if I am wrong..Thanks in advance

import serial
import matplotlib.pyplot as ply
import numpy 
import pylab as py
from drawnow import *

 ACCX=[]
 ACCY=[]


 arduinodata=serial.Serial('COM3',9600) #port name and baud rate

 ply.ion()


 def makeplotting():

    ply.ylabel('ACCX (°/sec)')
    ply.xlabel('Time')
    ply.plot(ACCX)


 while True:
    while(arduinodata.inWaiting()==0):
            pass
    arduinostring=arduinodata.readline()
    arduinostring=str(arduinostring,encoding="utf-8")
    dataArray=arduinostring.split(',')        
    accxtemp=float(dataArray[0])
    ACCX.append(accxtemp)
    drawnow(makeplotting)

Is there a Python forum where you could ask this question?

I am a beginner, I am not sure if I am wrong

Python runtime seems to think you are wrong.

Meenakshichowdhary:
ValueError: could not convert string to float: '1.01.05\r\n'

Can you tell us what number you would expect this to be converted to?

I would recommend that the first thing you do is to look at the output from the Arduino in the Serial monitor and ensure it is as you expect i.e. in the correct format.

When you are satisfied it is being output in the correct format, write your Python program to read the incoming data and just print it in the console, don't try and do anything else with it.

When you are satisfied that Python is receiving what you expect it to, then start doing stuff with it.

I would also increase the baud rate significantly (in the Python program and the Arduino program). Your current rate might be an issue if you are trying to output a lot of data.

In the future you should also post both Python and Arduino programs, but if your problem is really with the Python program then a Python forum might be a better choice (as suggested previously).

The MPU-9250 is a better version of the MPU-6050.
What do you want to measure ? Vibrations up to 20 Hz ? Is that useful ?
The MPU-6050 and the MPU-9250 are not very suitable to measure vibrations of a motor.

Which Arduino board do you use ? I suggest to use an Arduino board with a USB CDC interface for high speed data to the computer. I think that the Arduino Leonardo, Micro, Pro Micro, Due, Zero, M0, MKR1000 have that.

@bms001
Thanks for your reply.
I have already checked with serial monitor and it seems to be working fine. I get output in serial plotter as well. When i try to print in python, it works for a while then stops.

@Koepel
I am trying to measure the vibrations of motor (for now i am just using a DC 12V Fan just for experiment)
I am using Arduino Uno.
I have read about MPU 9250 but i probably dont need the magnetometer.

The MPU-9250 accelerometer and gyro are better than the MPU-6050, you don’t have to use the magnetometer :wink:
Some modules of the MPU-6050 have the wrong capacitor, making it noisy. The MPU-9250 does not have that specific capacitor.

I have made a first script with Python, and need to learn a lot. So I can’t help with Python.

This problem is on the Python side in that it appears that you are losing characters on the serial input. This is likely due to updating the plot on each input sample which can be pretty slow. If plotting runs slower than the rate of serial data into the serial input buffer, it will overflow and characters will be lost.

One solution might be to update the display less frequently, e.g. every 10th sample

while True:
    for k in range(10):
        while(arduinodata.inWaiting()==0):
            pass
        arduinostring=arduinodata.readline()
        arduinostring=str(arduinostring,encoding="utf-8")
        dataArray=arduinostring.split(',')       
        accxtemp=float(dataArray[0])
        ACCX.append(accxtemp)
    drawnow(makeplotting)

A more robust approach would be to create multiple threads, one for receiving data over serial and one for periodic plotting, but something like the above should be sufficient to get a quick visualization of the data.

Meenakshichowdhary:
@bms001
Thanks for your reply.
I have already checked with serial monitor and it seems to be working fine. I get output in serial plotter as well. When i try to print in python, it works for a while then stops.

What do you mean by 'stops'. Are you referring to the original errors you posted, or something else?

Have you done this?

bms001:
When you are satisfied it is being output in the correct format, write your Python program to read the incoming data and just print it in the console, don't try and do anything else with it.

When I say read and nothing else, I mean just using readline() and then print the data to console without splitting or anything else.

Have you done this?

bms001:
I would also increase the baud rate significantly (in the Python program and the Arduino program). Your current rate might be an issue if you are trying to output a lot of data.

@Meenakshichowdhary, show us also your sketch. This: “1.01.05\r\n”, is not okay.

@Koepel
I have ordered another accelerometer (ADXL345) and may I will also try with that and but thats secondary.
I have also tried using different MPU 6050 so that I am sure that its not the sensors fault as well but its the same.

@bms001
Check this image attached, It starts executing the program and out of no way some weird value comes up and the program stops executing
and
Yes, I was able to read the values without splitting and check the second image for the same.

Meenakshichowdhary:
@Koepel
I have ordered another accelerometer (ADXL345) and may I will also try with that and but thats secondary.
I have also tried using different MPU 6050 so that I am sure that its not the sensors fault as well but its the same.

Did the accelerometer generate the string '1.01.05\r\n' ?
No.
Is the accelerometer likely to be the cause of this particular problem?
Same answer.

Meenakshichowdhary:
...
Yes, I was able to read the values without splitting and check the second image for the same.

If this ran fine (under the same conditions as the problem code) and you checked that every line was ok (you haven't actually said if you did this or not) then it would suggest that the problem is on the receiver side in some way.

However, I would still recommend posting the actual sketch (or a minimal version of it) that is producing this output.

So far, my guess is that the problem is most likely this:

MrMark:
This problem is on the Python side in that it appears that you are losing characters on the serial input. This is likely due to updating the plot on each input sample which can be pretty slow. If plotting runs slower than the rate of serial data into the serial input buffer, it will overflow and characters will be lost.

How frequently are you outputting data from the Arduino?
If you slow it down, does that make a difference?
If you slow down the plotting rate (as suggested by @MrMark), does that make a difference?
Can you try reading the input lines (without processing them) as you've done for readline.png but include the plotting code (and maybe some dummy data to plot) so that you can see the effect of the delay from plotting on the received data?

@TolpuddleSartre
Yes, its the output from accelerometer

Meenakshichowdhary:
@TolpuddleSartre
Yes, its the output from accelerometer

I don't believe that, unless "1.01.05\r\n" is some sort of version or revision string.

I tried to change the baud rate, still the same.

The accerelometer is reading some values as shown in the image attached, thats causing the problem.

readline image is the ouput of what the sensor gives as ouput before even processing them.
Thing to notice is all this works fine in Arduino IDE serial monitor and plotter.

Thats the complete code:

import serial
import matplotlib.pyplot as ply
import numpy   #used for mathematical operations
import pylab as py
from mpl_toolkits.mplot3d import Axes3D
from drawnow import *

ACCX=[]
ACCY=[]
ACCZ=[]


arduinodata=serial.Serial('COM3',9600) #port name and baud rate

fig = ply.figure()
ax = Axes3D(fig)
ply.ion()
count=0

def makeplotting():
        
        ply.subplot(311)
        ply.ylabel('ACCX (°/sec)')
        ply.xlabel('Time')
        ply.plot(ACCX)
        
        ply.subplot(312)
        ply.ylabel('ACCY (°/sec)')
        ply.xlabel('Time')
        ply.plot(ACCY)
        
        ply.subplot(313)
        ply.ylabel('ACCZ (°/sec)')
        ply.xlabel('Time')
        ply.plot(ACCZ)


   

while True:
        while(arduinodata.inWaiting()==0):
                pass
        arduinostring=arduinodata.readline()
        arduinostring=str(arduinostring,encoding="utf-8")
        dataArray=arduinostring.split(',')

        accxtemp=float(dataArray[0])
        ACCX.append(accxtemp)
        accytemp=float(dataArray[1])
        ACCY.append(accytemp)
        accztemp=float(dataArray[2])
        ACCZ.append(accztemp)

@TolpuddleSartre

I have attached the output that I got now just with a different value but gives the same error.If i am not wrong, I think its reading from accelerometer

Meenakshichowdhary:
@TolpuddleSartre
Yes, its the output from accelerometer

Is it? I think the point @TolpuddleSatre is making is that it's not from the MPU, it is from the Arduino. The MPU does not send any information that should be interpreted as a text string. It sends data to Arduino which is presumably stored as a number, and then converted to character representation within the Serial.print() function.
So if there is a problem with the data being sent, it is probably something to do with the Arduino code or set up, which you still have not provided any information about.

Can you try the suggestions and answer the questions from my last post?

@bms001
I am using 9600 baud rate
I have also tried to change the baud rate but makes no difference