Skip to content

Instantly share code, notes, and snippets.

@kwalseth
Created May 12, 2020 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwalseth/3830fdb0046bf7c4469e2a2d246595ab to your computer and use it in GitHub Desktop.
Save kwalseth/3830fdb0046bf7c4469e2a2d246595ab to your computer and use it in GitHub Desktop.
import board
import digitalio
import pulseio
import time
import neopixel
import busio
import adafruit_hcsr04
import math
import MOVEmotor
import displayio
import adafruit_imageload
display = board.DISPLAY
with open("/go.bmp", "rb") as bitmap_file:
bitmap = displayio.OnDiskBitmap(bitmap_file)
tile_grid = displayio.TileGrid(bitmap, pixel_shader=displayio.ColorConverter())
go = displayio.Group()
go.append(tile_grid)
display.show(go)
sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.P13, echo_pin=board.P14)
pixels = neopixel.NeoPixel(board.P8,4)
#define some colours to make life easier
RED = (255, 0, 0)
YELLOW = (255, 150, 0)
GREEN = (0, 255, 0)
CYAN = (0, 255, 255)
BLUE = (0, 0, 255)
PURPLE = (180, 0, 255)
#wrapper for the sonar to have try in. On error we will report a very short distance
def GetDistance():
try:
value = sonar.distance
except RuntimeError:
value = 1.0
return value
def BeepHorn():
#a beep beep
buzzer = pulseio.PWMOut(board.P0,duty_cycle=2 ** 15, frequency=500, variable_frequency=True)
time.sleep(0.5)
buzzer.deinit()
time.sleep(0.1)
buzzer = pulseio.PWMOut(board.P0,duty_cycle=2 ** 15, frequency=500, variable_frequency=True)
time.sleep(0.5)
buzzer.deinit()
#Program starts here, fist setup the motor driver
MOVEmotor.setupMotorDriver()
#now loop doing the main code.
while True:
display.show(go)
distanceToObject = GetDistance()
# print ("Distance",distanceToObject)
if(distanceToObject > 100): #clear run - go for it
display.show(go)
pixels.fill(GREEN)
pixels.show()
MOVEmotor.LeftMotor(255)
MOVEmotor.RightMotor(255)
elif(distanceToObject > 50): #approaching something, slow down
pixels.fill(CYAN)
pixels.show()
MOVEmotor.LeftMotor(100)
MOVEmotor.RightMotor(100)
elif(distanceToObject > 20): #try and turn away
pixels.fill(YELLOW)
pixels.show()
MOVEmotor.LeftMotor(100)
MOVEmotor.RightMotor(50)
else: #something in the way, stop and beep the horn
pixels.fill(RED)
pixels.show()
MOVEmotor.StopMotors()
#beep the horn
BeepHorn()
#Now try a different direction
MOVEmotor.LeftMotor(-75)
MOVEmotor.RightMotor(-75)
time.sleep(0.3)
MOVEmotor.LeftMotor(75)
time.sleep(0.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment