Here are some code examples of how to use different sensors on the robot.
At the top of your code, you need to import all the libraries that will be needed, and set up constants for the pins used for the sensors, and also global variables which will be used to store the state of the sensors.
Then for each sensor, you create a subroutine which is run in its own thread, continually checking the state of the sensor, and updating a global variable with its state, and perhaps calling a special subroutine when the value of the sensor changes.
In another part of your program, you will have a while True loop which checks what the sensors are doing, and makes decisions about how to respond.
Standard code for the start of your program
#==============================================
# Start of robot programs
#==============================================
# first, imnport all the libraries needed
# this first one allows us to talk to the microbit
from lib import microbit_comms as mbt
# this is for the motors
from lib import piconzero as picon
# this is for the sonar sensor
from lib import hcsr04 as sonar
# time, so we can sleep
import time
import threading
#==============================================
# this next section sets up the sensors
# this will be the same for all the programs you write
#
# SENSOR SETUP
#
# define the pins used
BUMPER_L = 15
BUMPER_R = 13
LF_LEFT = 12
LF_CENTRE = 11
LF_RIGHT = 7
# and the motors
MOTOR_LEFT = 1
MOTOR_RIGHT = 0
# enable comms with the pins
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
# set them as inputs
GPIO.setup(BUMPER_L, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(BUMPER_R, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(LF_LEFT, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(LF_CENTRE, GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(LF_RIGHT, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
# constants
FWD = 127
REV = -128
STOP = 0
BUMPER_HIT = 0
BUMPER_NOT_HIT = 1
# global variables
l_speed = STOP
r_speed = STOP
l_bumper_hit = BUMPER_NOT_HIT
r_bumper_hit = BUMPER_NOT_HIT
lf_status = 7
quit = False
distance = 0
#==============================================
# END OF SETUP
#==============================================
Code to make the motors work
#=======================================================
# Functions to detect if the bumpers are hit
# you need to finish these off...
#=======================================================
def LeftBumperIsHit():
# To Do - you put code in here to
# detect if the left bumper is hit
# and return True or False
return False # default assumes not hit
def RightBumperIsHit():
# To Do - you put code in here to
# detect if the right bumper is hit
# and return True or False
return False # default assumes not hit
#=======================================================
# This subroutine will notice if a new motor value has been
# set, and SO LONG AS THE BUMPER IS NOT HITTING SOMETHING
# set the motor to that value
#=======================================================
def Motors():
global l_speed
global r_speed
old_l = 0
old_r = 0
while True:
# check every 100th of a second
time.sleep(0.01)
if old_l != l_speed:
# check the bumper if we have been asked to
# go forwards
if l_speed > 0 and LeftBumperIsHit():
print("Can't set left motor speed to", l_speed, "because left bumper is hit")
else:
picon.setMotor(MOTOR_LEFT, l_speed)
print("New left motor speed is ", l_speed)
old_l = l_speed
if old_r != r_speed:
# check the bumper if we have been asked to
# go forwards
if r_speed > 0 and RightBumperIsHit():
print("Can't set right motor speed to", r_speed, "because right bumper is hit")
else:
picon.setMotor(MOTOR_RIGHT, r_speed)
print("New right motor speed is ", r_speed)
old_r = r_speed
#======================================================
# Here we make a thread to run the motors function
#=======================================================
motorThread = threading.Thread(target=Motors)
motorThread.start()
#======================================================
# Now enter a while loop waiting for the
# user to press a letter
#=======================================================
while True:
choice = input("Enter a letter").lower()
if choice == "f":
# forwards
l_speed = FWD
r_speed = FWD
elif choice == "r":
# right
l_speed = REV
r_speed = FWD
elif choice == "q":
# quit
l_speed = STOP
r_speed = STOP
quit = True
break
# TO DO
# add extra keys for
# left turn
# backwards
# gentle turns
# manouvres (e.g. drive a square pattern)
else:
# stop
l_speed = STOP
r_speed = STOP
print("Program finished")
Code to monitor the bumpers
#==============================================
# functions to react when the bumpers are hit
#==============================================
def ReactToLeftBumperHit():
print( "Left bumper has hit")
# TO DO
# make it do something
# e.g. go obackwards and do a turn
def ReactToRightBumperHit():
print( "Right bumper has hit")
# TO DO
# make it do something
# e.g. go obackwards and do a turn
#==============================================
# Code to detect when bumpers have been hit
#==============================================
def Bumpers():
global l_bumper_hit
global r_bumper_hit
global quit
old_l_bumper = l_bumper_hit
old_r_bumper = r_bumper_hit
print("Starting to monitor bumpers")
while not quit:
# check every 100th of a second
time.sleep(0.01)
x = GPIO.input(BUMPER_L)
if x != old_l_bumper:
l_bumper_hit = x
old_l_bumper = x
if l_bumper_hit == BUMPER_HIT:
ReactToLeftBumperHit()
x = GPIO.input(BUMPER_R)
if x != old_r_bumper:
r_bumper_hit = x
old_r_bumper = x
if r_bumper_hit == BUMPER_HIT:
ReactToRightBumperHit()
#==============================================
# Start monitoring the bumper state
#==============================================
bumperThread = threading.Thread(target=Bumpers)
bumperThread.start()
Code to monitor the line follower
#==============================================
# Code to react when line follower changes
#==============================================
def LineFollowerChange():
global lf_status
print("Line follower status has changed:")
print(" Left: ", (lf_status & 4) == 0)
print(" Middle: ", (lf_status & 2) == 0)
print(" Right: ", (lf_status & 1) == 0)
#==============================================
# Code to monitor the line follower sensors
#==============================================
def LineFollower():
global quit
global lf_status
current_status = lf_status
while not quit:
time.sleep(0.01)
current_status = (GPIO.input(LF_LEFT) * 4) + (GPIO.input(LF_CENTRE) * 2) + GPIO.input(LF_RIGHT)
if current_status != lf_status:
lf_status = current_status
LineFollowerChange()
linefollowerThread = threading.Thread(target = LineFollower)
linefollowerThread.start()
Show a pattern on the microbit
#=====================================
# display an image on the microbit
#=====================================
def ShowPattern(pat):
mbt.ShowPattern(pat)
# example of using it
# each set of 0s and 1s is a row of lights
# on the microbit screen
ShowPattern("00100:00100:11111:00100:00100")
Use the Sonar distance detector
#======================================
# Use the distance sensor. If it detects
# something closer than the threshold,
# run a function
def ObjectNearby():
global distance
print("There is something within 10cm: ", distance)
# TO DO
# you decide what to do about it
def CheckDistance():
global quit
global distance
threshold = 10 #10 cm
in_range = False
while not quit:
time.sleep(0.01)
distance = round(sonar.getDistance(),0)
if distance <= threshold:
if not in_range:
ObjectNearby()
in_range = True
else:
in_range = False
sonarThread = threading.Thread(target=CheckDistance)
sonarThread.start()
Here is the code for the libraries used, which are in the 'lib' folder. You shouldn't need to change these, but it is here just in case...