Skip to content Skip to sidebar Skip to footer

Calculating Revolutions Per Minute In Python From An Arduino

I'm trying to calculate rpm's in python via a reed switch from the arduino. i cant seem to get it right. can some one please help me get the code right. my results are not consiste

Solution 1:

For now, your code will output the average RPM since the reading started. If ser.read() returns one time for every rotation, you can do something like this to get the instantaneous rotation speed:

import serial
import time
ser = serial.Serial('/dev/ttyACM0', 9600) 
a = ser.read()
t0 = time.time()

while(a == ser.read()):
    t1 = time.time()
    try:
        print(1 / ((t1-t0)/60))
    except ZeroDivisionError:
        pass
    t0 = t1

If you take a look at your new code, you should realize that the variable a is not assigned any new value during the while loop. You only check if ser.read() is equal to the value it had before you entered the for loop. This means that if ser.read() takes another value than what it had prior to entering the while loop, the statement a == ser.read() will be False.

This code will work for both values of ser.read().

import serial
importtimeser= serial.Serial('/dev/ttyACM0', 9600) 
t0 = time.time()

while True:
    a = ser.read()
    ifa== b'2'ora== b'1':
        t1 = time.time()
        try:
            print(1 / ((t1-t0)/60))
        except ZeroDivisionError:
            passt0= t1
    else:
        break

Solution 2:

You may get a division by zero if your first read is too fast.

Post a Comment for "Calculating Revolutions Per Minute In Python From An Arduino"