Created
March 28, 2019 04:58
-
-
Save notlmn/e1e1f451d3ed8b5eb242ec604cadd366 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Libraries | |
| import RPi.GPIO as GPIO | |
| from time import sleep, time | |
| GPIO.setwarnings(False) | |
| # GPIO Mode (BOARD / BCM) | |
| GPIO.setmode(GPIO.BOARD) | |
| # LED pins | |
| LED_1 = 24 | |
| LED_2 = 26 | |
| LED_3 = 32 | |
| GPIO.setup(LED_1, GPIO.OUT, initial=GPIO.LOW) | |
| GPIO.setup(LED_2, GPIO.OUT, initial=GPIO.LOW) | |
| GPIO.setup(LED_3, GPIO.OUT, initial=GPIO.LOW) | |
| # set GPIO Pins | |
| GPIO_TRIGGER = 12 | |
| GPIO_ECHO = 18 | |
| # set GPIO direction (IN / OUT) | |
| GPIO.setup(GPIO_TRIGGER, GPIO.OUT) | |
| GPIO.setup(GPIO_ECHO, GPIO.IN) | |
| def distance(): | |
| # set Trigger to HIGH | |
| GPIO.output(GPIO_TRIGGER, True) | |
| # set Trigger after 0.01ms to LOW | |
| sleep(0.00001) | |
| GPIO.output(GPIO_TRIGGER, False) | |
| StartTime = time() | |
| StopTime = time() | |
| # save StartTime | |
| while GPIO.input(GPIO_ECHO) == 0: | |
| StartTime = time() | |
| # save time of arrival | |
| while GPIO.input(GPIO_ECHO) == 1: | |
| StopTime = time() | |
| # time difference between start and arrival | |
| TimeElapsed = StopTime - StartTime | |
| # multiply with the sonic speed (34300 cm/s) | |
| # and divide by 2, because there and back | |
| distance = (TimeElapsed * 34300) / 2 | |
| return distance | |
| def led_on(pin): | |
| GPIO.output(pin, GPIO.HIGH) | |
| def led_off(): | |
| GPIO.output(LED_1, GPIO.LOW) | |
| GPIO.output(LED_2, GPIO.LOW) | |
| GPIO.output(LED_3, GPIO.LOW) | |
| # Have to be atleast 20cm away from the sensor | |
| # Anything more than that is completely ignored | |
| minimumProximity = 20 | |
| if __name__ == '__main__': | |
| wasBlocking = False | |
| personCount = 0 | |
| try: | |
| while True: | |
| dist = int(distance()) | |
| if wasBlocking == True: | |
| if dist > minimumProximity: | |
| # Person stopped blocking sensor | |
| wasBlocking = False | |
| personCount += 1 | |
| led_off() | |
| else: | |
| # The sensor is still being blocked | |
| else: | |
| if dist < minimumProximity: | |
| # Person started blocking sensor | |
| wasBlocking = True | |
| led_on(LED_1) | |
| else: | |
| # Nothing in front of the sensor | |
| led_off() | |
| print("Person count: %s" % personCount) | |
| sleep(0.5) | |
| # Reset by pressing CTRL + C | |
| except KeyboardInterrupt: | |
| print("Stopped by user...") | |
| GPIO.cleanup() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment