Change in logic in sensor not breaking 'while' loop?
Posted: Wed Sep 18, 2019 4:20 am
Hello, I am currently a beginner at Python coding thus I apologise if there is a basic/obvious solution to this. I want to code a program that runs 2 motors forwards simultaneously for 3 seconds, then backwards for 3 seconds. In addition, I've added a photoelectric sensor (WT160-F172) that will act as a collision detector for the motors. I can only get the sensor to stop the motors and continue running forwards (how i want it to work) when the loop is infinite (no time.sleep) . When i make it the finite loop i want (3 seconds front and 3 second back), i do not know how to get the sensor to function during the loop, the sensor only affects the motors between two said finite loops. I'm on python 3 and raspberry pi 3.
There is evidently a wrong usage of the loop functions in this code thus any help would be appreciated.
Code: Select all
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) GPIO.setup(7,GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #photoelectric sensor GPIO.setup(11,GPIO.OUT) GPIO.setup(12,GPIO.OUT) GPIO.setup(13,GPIO.OUT) GPIO.setup(15,GPIO.OUT) try: while True: print("Sensor Value:") value = GPIO.input(7) print(value) if (value == 0): print("Move forward") GPIO.output(11,False) GPIO.output(12,True) GPIO.output(13,True) GPIO.output(15,False) time.sleep(3) print("Move backward") GPIO.output(11,True) GPIO.output(12,False) GPIO.output(13,False) GPIO.output(15,True) time.sleep(3) elif (value == 1): print("Obstacle detected") GPIO.output(11,False) GPIO.output(12,False) GPIO.output(13,False) GPIO.output(15,False) except KeyboardInterrupt: pass finally: GPIO.cleanup()