0

I am using a DC motor attached with a 2000 ppm incremental encoder. I am using RPI to count the number of ticks, my code works fine but I am not able to calculate all the 2000 ticks. Any help would be appreciated. Following is the code

import RPi.GPIO as GPIO
import time
import serial

import smbus
import time
bus = smbus.SMBus(1)
time.sleep(1)
address = 0x04


GPIO.setmode (GPIO.BCM)
GPIO.setwarnings(True)
i=0
pin_A = 17
pin_B = 18

######################################################################
def writeNumber(value):
    bus.write_byte(address, value)
    return -1

def readNumber():
    number = bus.read_byte(address)

    return number
###################################################################
Encoder_Count = 0
A_Pos2=0
GPIO.setup (pin_A, GPIO.IN)
GPIO.setup (pin_B, GPIO.IN)
A_Pos = 0
A_Last = "00"
STATE = {"0001":1,"0010":-1,"0100":-1,"0111":1,"1000":1,"1011":-1, "1101":-1, "1110":1}     

def Encoder1(channel1):
    global Encoder_Count,A_Pos,A_Last,STATE
    now = str(GPIO.input(17)) + str(GPIO.input(18))
    key = A_Last + now
    if key in STATE:
            direction = STATE[key]
            A_Last = now
            A_Pos +=direction


GPIO.add_event_detect (pin_A, GPIO.BOTH, callback=Encoder1)  
GPIO.add_event_detect (pin_B, GPIO.BOTH, callback=Encoder1)
i=0
#while(i<10):
while(1):
        print A_Pos
        time.sleep(0.01)

GPIO.cleanup()
  • Does piscope show the ticks? If yes then use pigpio. – joan Sep 19 at 14:40
  • @Vaibhav Thacker, I am using the following quadrature encoder: raspberrypi.org/forums/…. I thought it should be easy to calculate the speed, using python time functions. Let me see if I can find you my time program later. – tlfong01 Sep 19 at 14:51
  • @Vaibhav Thacker, This is my time function to find the elapsed time between two events in mircoseconds or milliseconds. penzu.com/p/3f0aa9d3. So let me see what can I do. (1) Use Rpi GPIO pin to count 1,000 toggles. (2) Find the elapsed time. (3) Do some arithmetic, and find the speed. Isn't it that simple? But I have not tried it yet. Will try later. – tlfong01 Sep 19 at 14:58
  • @Vaibhav Thacker, My time measurement functions can measure elapsed time between two events. Now let me see how to find motor speed. (1) Get start time T1, (2) loop for 1000 Phase A pulses (same as revolutions), (3) Get finish time, (4) Find elapsed time in seconds, (5) Speed = 1000 revolutions / elapsed time. I don't understand what you mean by 2,000pm. Perhaps you can give me the web link of your motor encoder. – tlfong01 Sep 20 at 7:36
0

Question

How to measure the motor speed?

Answer

Update2019sep20hkt1641

Or if you are using an optical encoder with high resolution black and white lines, or slots. In this case the motor is moving at constant speed (AC induction motor or stepping motor), and you count the number of pulses to determine the precise position of the print head of a bubble jet, or 3D printer.

optical encoder

encoder output waveform

This is my time function to find the elapsed time between two events in mircoseconds or milliseconds. Let me see what can I do.

(1) Use Rpi GPIO pin to count 1,000 toggles.

(2) Find the elapsed time.

(3) Do some arithmetic, and find the speed.

Isn't it that simple? But I have not tried it yet. Will try later.

/ to continue, ...

References

(1) Geared Motor with Encoder Forum Discussion

(2) TT Motor 1/20 Gear Ration with A/B Phse Encoder - ¥24

(3) Python Timing Functions - tlfong01

Appendices

(A) Motor with Encoder

TT Gear Motor

(B) Encoder

Encoder Picture

(C) Python Timing Functions

https://penzu.com/public/3f0aa9d3

# ftime69.py  tlfong01 2019sep08hkt1158
# Rpi4B buster 2019jul10 python 3.7.3 Thronny 1.1

import  inspect
from    time     import   sleep
from    datetime import  datetime
import  fprint53 as      fprint

# ********************************************************************************
# ********************************************************************************

# *** Date Time Functions ***

def delaySeconds(secondsNum):
    sleep(secondsNum)
    return

def oneSecondDelay():
    delaySeconds(1)
    return

def tenMillionPasses():
    totalCount = 10000000
    for count in range(totalCount):
        pass
    return

def oneMillionPasses():
    totalCount = 1000000
    for count in range(totalCount):
        pass
    return

def oneThousandPasses():
    totalCount = 1000
    for count in range(totalCount):
        pass
    return

def printDateTimeNow():
    timeNowLong  = datetime.now()
    timeNowShort = str(timeNowLong)[0:16]
    fprint.printTitleString('timeNowLong',  fprint.indentFormat640, timeNowLong)
    fprint.printTitleString('timeNowShort', fprint.indentFormat640, timeNowShort)
    return

def printStartTimeFinishTimeDifferenceLong(startTime, finishTime):  
    elapsedTime = finishTime - startTime
    elapsedSeconds = elapsedTime.seconds
    elapsedMicroSeconds = (elapsedSeconds * 1000000) + elapsedTime.microseconds
    elapsedMilliSeconds = int(elapsedMicroSeconds / 1000)
    fprint.printTitleString('Start Time',           fprint.indentFormat640, startTime)
    fprint.printTitleString('Finish Time',          fprint.indentFormat640, finishTime)
    fprint.printTitleString('Elapsed Time',         fprint.indentFormat640, elapsedTime)    
    fprint.printTitleString('Elapsed Seconds',      fprint.indentFormat640, elapsedSeconds)    
    fprint.printTitleString('Elapsed MilliSeconds', fprint.indentFormat640, elapsedMilliSeconds)
    fprint.printTitleString('Elapsed MicroSeconds', fprint.indentFormat640, elapsedMicroSeconds) 
    return

def printStartTimeFinishTimeDifferenceMilliSeconds(startTime, finishTime):  
    elapsedTime = finishTime - startTime
    elapsedSeconds = elapsedTime.seconds
    elapsedMicroSeconds = (elapsedSeconds * 1000000) + elapsedTime.microseconds
    elapsedMilliSeconds = int(elapsedMicroSeconds / 1000)
    fprint.printTitleString('Elapsed MilliSeconds', fprint.indentFormat640, elapsedMilliSeconds)
    return

def printStartTimeFinishTimeDifferenceMicroSeconds(startTime, finishTime):  
    elapsedTime = finishTime - startTime
    elapsedSeconds = elapsedTime.seconds
    elapsedMicroSeconds = (elapsedSeconds * 1000000) + elapsedTime.microseconds
    elapsedMilliSeconds = int(elapsedMicroSeconds / 1000)
    fprint.printTitleString('Elapsed MicroSeconds', fprint.indentFormat640, elapsedMicroSeconds)
    return

def printFunctionElapseTime(function, functionName):
    fprint.printBeginExecFunction()
    printDateTimeNow()
    printElapsedTime()
    fprint.printEndExecFunction()
    return

# *** Test Functions ***

def testPrintDateTimeNow():
    fprint.printBeginExecFunction()
    printDateTimeNow()
    fprint.printEndExecFunction()
    return

def testPrintOneSecondElapsedTime():
    fprint.printBeginExecFunction()
    startTime = datetime.now()
    delaySeconds(1)
    finishTime = datetime.now()
    printStartTimeFinishTimeDifferenceLong(startTime, finishTime)
    fprint.printEndExecFunction()
    return

def testPrintTwoSecondsElapsedTime():
    fprint.printBeginExecFunction()
    startTime = datetime.now()
    delaySeconds(2)
    finishTime = datetime.now()
    printStartTimeFinishTimeDifferenceLong(startTime, finishTime)
    fprint.printEndExecFunction()
    return

def testPrintFunctionExecTimeLong(function):
    #fprint.printBeginExecFunction()
    startTime = datetime.now()
    function()
    finishTime = datetime.now()
    printStartTimeFinishTimeDifferenceLong(startTime, finishTime)
    #fprint.printEndExecFunction()
    return

def testPrintFunctionExecTimeMilliSeconds(function):
    #fprint.printBeginExecFunction()
    startTime = datetime.now()
    function()
    finishTime = datetime.now()
    printStartTimeFinishTimeDifferenceMilliSeconds(startTime, finishTime)
    #fprint.printEndExecFunction()
    return

def testPrintFunctionExecTimeMicroSeconds(function):
    #fprint.printBeginExecFunction()
    startTime = datetime.now()
    function()
    finishTime = datetime.now()
    printStartTimeFinishTimeDifferenceMicroSeconds(startTime, finishTime)
    #fprint.printEndExecFunction()
    return


def testPrintOneSecondDelayFunctionLong():
    fprint.printBeginExecFunction()
    testPrintFunctionExecTimeLong(oneSecondDelay)
    fprint.printEndExecFunction()
    return

def testPrintOneSecondDelayFunctionMilliSeconds():
    fprint.printBeginExecFunction()
    testPrintFunctionExecTimeMilliSeconds(oneSecondDelay)
    fprint.printEndExecFunction()
    return

def testPrintTenMillionPassesFunctionMilliSeconds():
    fprint.printBeginExecFunction()
    testPrintFunctionExecTimeMilliSeconds(tenMillionPasses)
    fprint.printEndExecFunction()
    return

def testPrintOneMillionPassesFunctionMicroSeconds():
    fprint.printBeginExecFunction()
    testPrintFunctionExecTimeMicroSeconds(oneMillionPasses)
    fprint.printEndExecFunction()
    return

def testPrintOneThousandPassesFunctionMicroSeconds():
    fprint.printBeginExecFunction()
    testPrintFunctionExecTimeMicroSeconds(oneThousandPasses)
    fprint.printEndExecFunction()
    return

def printOneLineTenTimes():
    printLine = 'abcxyz' 
    repeatCount = 10

    for i in range(10):
        print('         abcxyz')
    return

def testPrintPrintOneLineTenTimesFunctionMilliSeconds():
    fprint.printBeginExecFunction()
    testPrintFunctionExecTimeMilliSeconds(printOneLineTenTimes)
    fprint.printEndExecFunction()
    return

# ********************************************************************************
# ********************************************************************************

# *** Main Tests ***

def mainTests():
    #testPrintDateTimeNow()
    #testPrintOneSecondElapsedTime()
    #testPrintTwoSecondsElapsedTime()
    #testPrintOneSecondDelayFunctionLong()
    #testPrintOneSecondDelayFunctionMilliSeconds()
    #testPrintTenMillionPassesFunctionMilliSeconds()
    #testPrintOneMillionPassesFunctionMicroSeconds()
    #testPrintOneThousandPassesFunctionMicroSeconds()
    testPrintPrintOneLineTenTimesFunctionMilliSeconds()
    return

# ********************************************************************************
# ********************************************************************************

# *** Init/Main Functions ***

# *** Init Function ***

def init():
    pass
    return

#*** Main Function ***

def main():
    init()
    mainTests()    
    return

# ********************************************************************************
# ********************************************************************************

# *** Main ***

if __name__ == '__main__':
    main()

# *** End of Program ***

# ********************************************************************************
# ********************************************************************************

''' Sample Output 2019sep08hkt1208
>>> %Run ftime69.py

     ********************************************************************************

     Begin Execute Function testPrintPrintOneLineTenTimesFunctionMilliSeconds tlfong01 

       Function Name                           = testPrintPrintOneLineTenTimesFunctionMilliSeconds
         abcxyz
         abcxyz
         abcxyz
         abcxyz
         abcxyz
         abcxyz
         abcxyz
         abcxyz
         abcxyz
         abcxyz
       Elapsed MilliSeconds                    = 3

     End   Execute Function testPrintPrintOneLineTenTimesFunctionMilliSeconds tlfong01 

     ********************************************************************************

>>> 
'''

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.