OK, here we go. This first bit is the simple if/then program. It works, but as I said it's not very precise and it needs to complete each move before it can react to the next input, which is not ideal. 'Goto()' is just the function that drives the stepper motor to a particular bearing (this works fine).
Code: Select all
import RPi.GPIO as GPIO, sys, threading, time, os
#use physical pin numbering
GPIO.setmode(GPIO.BOARD)
IR_N = 7 #GPIO 4 GPCLK0
IR_NE = 11 #GPIO 17
IR_E = 13 #GPIO 27
IR_SE = 15 #GPIO 22
IR_S = 16 #GPIO 23
IR_SW = 18 #GPIO 24
IR_W= 19 #GPIO 10 MOSI
IR_NW= 26 #GPIO 7 CE1
# Set stepper pins as output
for pin in StepPins:
GPIO.setup(pin,GPIO.OUT)
GPIO.output(pin, False)
#set up IR pins as inputs
#GPIO 4 pin 7 is IR north
GPIO.setup(IR_N, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(IR_NE, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(IR_E, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(IR_SE, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(IR_S, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(IR_SW, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(IR_W, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(IR_NW, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
def track():
if GPIO.input(IR_N):
print ("North")
goto(0)
if GPIO.input(IR_NE):
print ("North East")
goto(45)
if GPIO.input(IR_E):
print ("East")
goto(90)
if GPIO.input(IR_SE):
print ("South East")
goto(135)
if GPIO.input(IR_S):
print ("South")
goto(180)
if GPIO.input(IR_SW):
print ("South West")
goto(225)
if GPIO.input(IR_W):
print ("West")
goto(270)
if GPIO.input(IR_NW):
print ("North West")
goto(315)
else:
stop(0)
# Start main loop
while True:
track()
This next bit was abortive attempt to use callbacks. It resulted in random behaviour, I suspect because I had several functions all trying to drive the motor to different places.
Code: Select all
def IRdetect(bearing):
print("Target bearing %i" %bearing)
goto(bearing)
# Set IR detect events. Don't really understand what lambda does, but it allows me to pass an argument (bearing) to a callback function
GPIO.add_event_detect(IR_N, GPIO.FALLING, callback=lambda x: IRdetect(0), bouncetime =300)
GPIO.add_event_detect(IR_NE, GPIO.FALLING, callback=lambda x: IRdetect(45), bouncetime =300)
GPIO.add_event_detect(IR_E, GPIO.FALLING, callback=lambda x: IRdetect(90), bouncetime =300)
GPIO.add_event_detect(IR_SE, GPIO.FALLING, callback=lambda x: IRdetect(135), bouncetime =300)
GPIO.add_event_detect(IR_S, GPIO.FALLING, callback=lambda x: IRdetect(180), bouncetime =300)
GPIO.add_event_detect(IR_SW, GPIO.FALLING, callback=lambda x: IRdetect(225), bouncetime =300)
GPIO.add_event_detect(IR_W, GPIO.FALLING, callback=lambda x: IRdetect(270), bouncetime =300)
GPIO.add_event_detect(IR_NW, GPIO.FALLING, callback=lambda x: IRdetect(315), bouncetime =300)
Submarine communication systems engineer and amateur robot enthusiast.