Cobbled some code together from a few places. This be it.
#! /usr/bin/python
# set lights based on ultrasonic sensor
# merge the adeept ultrasonic code w/ jamhat code
#JAM hat pin usage
# Component GPIO.BCM GPIO.BOARD GPIO Zero object Notes
# LED1 GPIO 5 Pin 29 lights_1.red
# LED2 GPIO 6 Pin 31 lights_2.red
# LED3 GPIO 12 Pin 32 lights_1.yellow
# LED4 GPIO 13 Pin 33 lights_2.yellow
# LED5 GPIO 16 Pin 36 lights_1.green
# LED6 GPIO 17 Pin 11 lights_2.green
# Button 1 GPIO 19 Pin 35 button_1 Connected to R8/R10
# Button 2 GPIO 18 Pin 12 button_2 Connected to R7/R9
# Buzzer GPIO 20 Pin 38 buzzer
# do the needful https://thepihut.com/blogs/raspberry-pi-tutorials/getting-started-with-the-jam-hat
#
# sudo apt-get update
# sudo apt-get install python3-gpiozero python-gpiozero
# https://github.com/adeept/Adeept_Ultimate_Starter_Kit_Python_Code_for_RPi/blob/master/14_distance.py
#
# if u r missing stuff, might want to run this: https://raw.githubusercontent.com/adeept/Adeept_RaspTank/master/setup.py
# for ultra, connect trigger to pin 16 (gpio23) and echo to pin 18 (gpio24)
# connect power to pin 4 and ground to pin 6
#
# for the ultrasonic sensor
# https://www.adeept.com/ultrasonic-sr04_p0047.html
# Power supply: 5V DC, quiescent current : <2mA,effectualangle: <15 ranging distance : 2cm~500 cm resolution : 0.3 cm
# 343 m/s * 39.37 inch/m = 13504 inches/s
import RPi.GPIO as GPIO
import time
from gpiozero import JamHat
from random import sample
def checkdist():
GPIO.output(23, GPIO.HIGH)
time.sleep(0.000015)
GPIO.output(23, GPIO.LOW)
while not GPIO.input(24):
pass
t1 = time.time()
while GPIO.input(24):
pass
t2 = time.time()
return (t2-t1)*13504/2
# batteries to power, turbines to speed
jamhat = JamHat()
jamhat.lights_1.blink()
time.sleep(0.5)
jamhat.lights_2.blink()
jamhat.buzzer.play('C4')
time.sleep(0.5)
#ready to move out
jamhat.off()
GPIO.setmode(GPIO.BCM)
#I guess jamhat sets to BCM?
GPIO.setup(23,GPIO.OUT,initial=GPIO.LOW)
GPIO.setup(24,GPIO.IN)
time.sleep(0.5)
print('Checking distance..')
dist = 999
try:
while True:
jamhat.off()
dist = checkdist()
print('Distance: %0.2f inches' %dist)
#print 'Distance: %0.2f m' %checkdist()
if dist > 20:
jamhat.lights_1.green.on()
jamhat.lights_2.green.on()
if dist > 10 and dist <=20:
jamhat.lights_1.yellow.on()
jamhat.lights_2.yellow.on()
if dist <=10:
jamhat.lights_1.red.on()
jamhat.lights_2.red.on()
jamhat.buzzer.play('C4')
time.sleep(0.5)
except KeyboardInterrupt:
GPIO.cleanup()