1

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)
2
  • 3
    this question may be more relevant to the rasberry-pi page or code review Commented Jan 17, 2017 at 16:46
  • Thanks @Aaron. I will seek out there as well. I'm a nooby~ Commented Jan 17, 2017 at 16:56

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Aaron, this is very educative! :)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.