简体   繁体   中英

raspberry pi python gpio timer

Hi I'm learning to code python on raspberry pi 3 model B. and playing around with GPIO. My script makes a LED turns on when the receiving input==1 and turn off when input!=1. I also want to record the time when LED is turned on and time when it's turned off. (start time and end time). I end up using multiple if/elif condition, but I'm sure there are better ways of doing this. Please enlighten me!

import RPi.GPIO as GPIO
import time
GPIO.cleanup()
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11,GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.setup(7,GPIO.OUT)
GPIO.output(7,0) #set ping 7 to be 0 at default
CatchTime = True
startTime = []
startTimeRead = []
endTime = []
try:
        while True:
                time.sleep(0.25)
                if (GPIO.input(11) ==1)and CatchTime==True :  #start counting
                        GPIO.output(7,1)
                        print(time.ctime())
                        startTime.append(time.time())
                        startTimeRead.append(time.ctime())
                        CatchTime = False
                elif (GPIO.input(11) ==1)and CatchTime != True : #within count
                        GPIO.output(7,1)
                        print(time.ctime())
                elif (GPIO.input(11) !=1) and CatchTime != True : #end of count
                        GPIO.output(7,0)
                        CatchTime = True
                        endTime.append(time.time())
                else:   #steady not count
                        GPIO.output(7,0)
                        CatchTime = True

except KeyboardInterrupt:
    GPIO.cleanup()


print('start time:',startTimeRead)
print('end time:',endTime)

Generally the better way to do it would be to create interrupt functions for the rising and falling events. what you're doing now is referred to as busy waiting while polling for an input. Interrupts are generally cleaner and more reliable. Computerphile has a nice overview on interrupts in general (more from the computer aspect of things), and a quick google search found this tutorial on how to use gpio interrupts with the rasberry-pi.

I'd recommend looking at this post (Raspberry Pi- GPIO Events in Python) on the Raspberry Pi SO. That solution shows how to use events so you don't have to run a constant loop - it will just notify you when there is a change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM