示例#1
0
    def __init__(self):
        # defining each item that belongs to our class
        self.timer = 0  # local variable as counter
        self.greenLED = digitalio.DigitalInOut(board.D10)  # Green LED
        self.redLED = digitalio.DigitalInOut(board.D11)  # Red LED
        self.yellowLED = digitalio.DigitalInOut(board.D12)  # Yellow LED
        # Opening Ceremony
        for led in [self.greenLED, self.yellowLED, self.redLED]:
            led.direction = digitalio.Direction.OUTPUT
            led.value = True
            time.sleep(2)
            led.value = False
            time.sleep(1)
        self.buzzer = pulseio.PWMOut(
            board.D13, variable_frequency=True)  # Buffer initiated
        # Buffer attributes - Start
        self.buzzer.frequency = 440
        self.OFF = 0
        self.ON = 2**15
        # Buffer attributes - End
        self.buzzer.duty_cycle = self.ON  # Turn on the buzzer
        time.sleep(1)
        self.buzzer.duty_cycle = self.OFF  # Turn off the buzzer
        self.sonar = adafruit_hcsr04.HCSR04(
            trigger_pin=board.D4,
            echo_pin=board.D2)  # Sensor placement on board

        print("Obstacle Detector Device is Working")
示例#2
0
def setup_sonar(ndx, trig, echo):
    global digital_pins, digital_objects, NUM_DIGITAL_PINS
    # If I try setting up a sonar on this location
    # more than once, this will fail... so, try...
    trig = numberToBoardPin(trig)
    echo = numberToBoardPin(echo)
    try:
        # Get the index of those board pins in the
        # board pin array.
        trigNdx = digital_pins.index(trig)
        # Us that index to deinit() those pins.
        digital_objects[trigNdx].deinit()
        # Remove them from the digital objects list.
        digital_pins.pop(trigNdx)
        digital_objects.pop(trigNdx)

        # Now, do the echo pin. Do these in order, because
        # I'm destructing the lists as I go.
        echoNdx = digital_pins.index(echo)
        # print("E ndx: {0}".format(echoNdx))
        digital_objects[echoNdx].deinit()
        digital_pins.pop(echoNdx)
        digital_objects.pop(echoNdx)

        # Update how many digital pins are in the list.
        NUM_DIGITAL_PINS = len(digital_pins)
    except:
        pass

    if sonar[ndx] is not None:
        sonar[ndx].deinit()
    sonar[ndx] = adafruit_hcsr04.HCSR04(trigger_pin=trig, echo_pin=echo)
示例#3
0
    def __init__(self):
        self.btm_dist_threshold = DIST_THRESHOLDS[0]
        self.top_dist_threshold = DIST_THRESHOLDS[0]
        self.brightness = BRIGHTNESSES[0]
        self.duration = DURATIONS[0]
        self.darkness_threshold = DARKNESS_THRESHOLDS[0]

        self.pixels = neopixel.NeoPixel(board.D10,
                                        74,
                                        brightness=self.brightness)
        self.timer = Timer(self.duration, self.turn_off_pixels)
        self.btm_sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.D9,
                                                echo_pin=board.D6)
        self.top_sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.D0,
                                                echo_pin=board.D1)

        self.pixels.fill((0, 0, 0))
        self.pixels.show()
示例#4
0
 def __init__(self, trigger: _LsPin, echo: _LsPin) -> None:
     try:
         import adafruit_hcsr04
     except ImportError:
         raise RuntimeError(
             'Adafruit_HCSR04 module is not installed. Run `apt install python3-adafruit-circuitpython-hcsr04` as root to install.'
         ) from ImportError
     self._sonar = adafruit_hcsr04.HCSR04(
         trigger_pin=DigitalInputOutput.lspin_to_libgpiod_pin(trigger),
         echo_pin=DigitalInputOutput.lspin_to_libgpiod_pin(echo))
示例#5
0
    def __init__(self):
        # Define i2c
        self._i2c = busio.I2C(board.SCL, board.SDA, frequency=100000)
        self._cutebot = 0x10
        self._i2c_rest = 0.1
        self._error_thresh = 12

        # Define sound
        self._buzzer = pulseio.PWMOut(board.P0, variable_frequency=True)

        # Define headlights
        self._RGB_RIGHT_HEADLIGHT = 0x04
        self._RGB_LEFT_HEADLIGHT = 0X08

        # Define neopixels
        self._rainbow_pixels = neopixel.NeoPixel(board.D15, 2)

        # Define motor states
        self._LEFT_MOTOR = 0x01
        self._RIGHT_MOTOR = 0x02
        self._BACKWARDS = 0x01
        self._FORWARDS = 0x02

        # Define servo
        self._servoMaxAngleInDegrees = 180
        self._SERVO_S1 = 0x05
        self._SERVO_S2 = 0x06

        # Define expansion pins
        self._p1 = AnalogIn(board.P1)
        self._p2 = AnalogIn(board.P2)

        # Define ultrasound sonar
        self._sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.D8,
                                             echo_pin=board.D12)

        # Define line tracking sensors
        # Left sensor
        self._leftLineTracking = DigitalInOut(board.D13)
        self._leftLineTracking.direction = Direction.INPUT
        self._leftLineTracking.pull = None
        # Right sensor
        self._rightLineTracking = DigitalInOut(board.D14)
        self._rightLineTracking.direction = Direction.INPUT
        self._rightLineTracking.pull = None

        # Reset cutebot
        self.motorsOff()
        self.lightsOff()
示例#6
0
    def initialize_input(self):
        import board
        import adafruit_hcsr04

        bcm_to_board = [
            board.D1, board.D2, board.D3, board.D4, board.D5, board.D6,
            board.D7, board.D8, board.D9, board.D10, board.D11, board.D12,
            board.D13, board.D14, board.D15, board.D16, board.D17, board.D18,
            board.D19, board.D20, board.D21, board.D22, board.D23, board.D24,
            board.D25, board.D26, board.D27
        ]

        if self.pin_trigger and self.pin_echo:
            self.sensor = adafruit_hcsr04.HCSR04(
                trigger_pin=bcm_to_board[self.pin_trigger - 1],
                echo_pin=bcm_to_board[self.pin_echo - 1])
示例#7
0
    def initialize(self):
        import board
        import adafruit_hcsr04

        bcm_to_board = [
            board.D1, board.D2, board.D3, board.D4, board.D5, board.D6,
            board.D7, board.D8, board.D9, board.D10, board.D11, board.D12,
            board.D13, board.D14, board.D15, board.D16, board.D17, board.D18,
            board.D19, board.D20, board.D21, board.D22, board.D23, board.D24,
            board.D25, board.D26, board.D27
        ]

        if self.pin_trigger and self.pin_echo:
            self.sensor = adafruit_hcsr04.HCSR04(
                trigger_pin=bcm_to_board[self.pin_trigger - 1],
                echo_pin=bcm_to_board[self.pin_echo - 1])
        else:
            self.logger.error("Must set trigger and enable pins")
示例#8
0
    def __init__(self):
        self.greenLED = digitalio.DigitalInOut(board.D10)
        self.redLED = digitalio.DigitalInOut(board.D11)
        self.yellowLED = digitalio.DigitalInOut(board.D12)
        for led in [self.redLED, self.greenLED, self.yellowLED]:
            led.direction = digitalio.Direction.OUTPUT
            led.value = True
            time.sleep(1)
            led.value = False
            time.sleep(1)
        self.buzzer = pulseio.PWMOut(board.D13, variable_frequency=True)
        self.buzzer.frequency = 440
        OFF = 0
        ON = 2**15
        self.buzzer.duty_cycle = ON
        time.sleep(1)
        self.buzzer.duty_cycle = OFF
        self.sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.D4,
                                            echo_pin=board.D2)

        print("Obstacle Detector Device is Working")
        self.startParking()
示例#9
0
# Distance Censor
# Lily Wielar
# sensing distance from object to monitor and correlate light color on metroexpress to distance - https://www.rapidtables.com/web/color/RGB_Color.html

import time  # adding time libraries
import board  # adding board libraries
import neopixel  # adding neopixel libraries
import simpleio  # adding simpleio libraries
import adafruit_hcsr04  # add adafruit distance censor library
sonar = adafruit_hcsr04.HCSR04(
    trigger_pin=board.D6,
    echo_pin=board.D7)  # sonar equals distance sensor with pins D6 and D7
dot = neopixel.NeoPixel(board.NEOPIXEL, 1,
                        brightness=.1)  #dot equals metroexpress board led

red = 0  # variable red
green = 0  # variable green
blue = 0  # variable blue

while True:

    try:  #attempt....
        sonarValue = sonar.distance  # sonarvalue equals the distance object is from censor
        print(sonarValue)  # serial monitor prints value/distance
        if sonarValue < 5:  #if the distance is less than 5...
            dot.fill((255, 0, 0))  # led is red
        if sonarValue > 35:  #if the distance is greater than 35...
            dot.fill((0, 255, 0))  # led is green
        if sonarValue <= 20 and sonarValue > 5:  #if distance is between 5 and 20...
            red = simpleio.map_range(
                sonarValue, 6, 20, 255, 0
示例#10
0
文件: code.py 项目: dnkorte/mini_bot
# setup beeper
beeper = digitalio.DigitalInOut(board.A5)
beeper.direction = digitalio.Direction.OUTPUT
beeper.value = False

# create a PWMOut object on Pin D12 and D11
pwmL = pulseio.PWMOut(board.D12, frequency=50)
pwmR = pulseio.PWMOut(board.D11, frequency=50)

# Create a servo object, left_servo.
left_servo = servo.ContinuousServo(pwmL)
right_servo = servo.ContinuousServo(pwmR)

# create object for sonar device
sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.D10, echo_pin=board.D7, timeout=1.0)

# setup for NeoPixels (RGB) ########################################################
NUMPIXELS = 7
ORDER = neopixel.GRB
neopixels = neopixel.NeoPixel(board.D5, NUMPIXELS, brightness=0.2, auto_write=False, pixel_order=ORDER)

# startup delay
for i in range(5):
    neopixels[i+2] = (255, 255, 0)
    neopixels.show()
    beep(0.25)
    time.sleep(0.75)

# user is ready, so turn off all the neopixels 
for i in range(NUMPIXELS):      
示例#11
0
# Sensor values
warnDistance = int(lout.readConfig(config, "warnDistance"))
readTime = float(lout.readConfig(config, "readTime"))

# Email Data
sendGridAPI = str(lout.readConfig(config, "sendGridAPI"))
from_email = str(lout.readConfig(config, "OpenSump_email"))
alertRecipients = lout.readConfig(config, "alertRecipients")
emailSubject = str(lout.readConfig(config, "emailSubject"))
emailContent = str(lout.readConfig(config, "emailContent"))

enabled = True
warn = False
timeLimit = False
emailSendTime = DT.datetime.now()
sonar = adafruit_hcsr04.HCSR04(trigger_pin=txPin, echo_pin=rxPin)

lout.log(config, startTime=startTime, startup=True)

while enabled:
    currentTime = DT.datetime.now()
    sensorValue = stateChecker(sonar, warnDistance, readTime)

    # Because apparently Python thinks "any string" = True
    if sensorValue == True and timeLimit:
        warn = True
        lout.log(config, currentTime, "SENSOR TRIPPED")

    if warn:
        currentTime = DT.datetime.now()
        for email in alertRecipients:
示例#12
0
 def __init__(self, sonarTriggerPin = None, sonarEchoPin = None):
     self.s1 = adafruit_hcsr04.HCSR04(sonarTriggerPin, sonarEchoPin)
     super().__init__()
示例#13
0
import time
import board
import busio
import neopixel
import adafruit_hcsr04
from simpleio import map_range

NEOPIXEL_PIN = board.NEOPIXEL
NUMBER_OF_PIXELS = 1

#i2c = busio.I2C(board.SCL, board.SDA)
#sensor = adafruit_vl53l0x.VL53L0X(i2c)
sensor = adafruit_hcsr04  # shorthand for adafruit_hcsr04 to just sensor
sonar = adafruit_hcsr04.HCSR04(
    trigger_pin=board.D7, echo_pin=board.D10)  # sets up pins for the sensor
timeout = 10  # so that the code doesn't timeout and not upload

#for i in range(NUMBER_OF_PIXELS):
#strip[i] = (0, 0, 0)
#strip.show()
#time.sleep(0.1)
#strip[i] = (0, 0, 0)
# strip.show()
dot = neopixel.NeoPixel(
    board.NEOPIXEL,
    1)  # establishes the neopixel on the board as a changeable "LED"

while True:
    try:
        distance = sonar.distance  #distance is now sonar distance
        print(
import time
import board
import neopixel
import adafruit_hcsr04
import simpleio
ultrasonic = adafruit_hcsr04.HCSR04(trigger_pin=board.D6, echo_pin=board.D5)
neopixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=.1)

r = 0
b = 0
g = 0

while True:
    try:
        dist = ultrasonic.distance
        print(dist)
        if dist <= 20:
            r = simpleio.map_range(dist, 0, 20, 255, 0)
            b = simpleio.map_range(dist, 5, 20, 0, 255)
            g = simpleio.map_range(dist, 20, 35, 0, 255)
        else:
            r = simpleio.map_range(dist, 0, 20, 255, 0)
            b = simpleio.map_range(dist, 20, 35, 255, 0)
            g = simpleio.map_range(dist, 20, 35, 0, 255)
        neopixel.fill((int(r), int(g), int(b)))
        print(dist)
    except RuntimeError:
        print("Retrying!")
    time.sleep(.1)
示例#15
0
import time
# import datalogger
import math
import board
import adafruit_hcsr04
from adafruit_circuitplayground import cp

sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.A2, echo_pin=board.A1)
pixels = cp.pixels
pixels.brightness = 0.3
pixels.show()
pixels.fill((0, 0, 0))

# ------------------------------------------------------------------------------- #
# Other functions
# ------------------------------------------------------------------------------- #
def alarm():
    while not cp.button_b:
        cp.play_tone(262, 1)
        pixels.fill((255, 0, 0))
        time.sleep(0.1)
        pixels.fill((0, 0, 255))
        time.sleep(0.1)
    pixels.fill((0, 0, 0))

def sentry_check():
    # print("sentry check")
    x, y, z = cp.acceleration
    time.sleep(0.05)
    acc_x = abs(x/9.8)
    acc_y = abs(y/9.8)
示例#16
0
# 9/11/19

import board  #pylint: disable-msg=import-error
import time  #pylint: disable-msg=import-error
import digitalio  #pylint: disable-msg=import-error
import adafruit_bus_device  #pylint: disable-msg=import-error
import adafruit_hcsr04  #pylint: disable-msg=import-error
import neopixel  #pylint: disable-msg=import-error
import simpleio  #pylint: disable-msg=import-error

r = 0  #Red Green and Blue variables for the RGB LED on the board
g = 0
b = 0

sonar = adafruit_hcsr04.HCSR04(
    trigger_pin=board.D12,
    echo_pin=board.D11)  #This is how you get HC-SR04 on Adafruit
dot = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=.1)

while True:

    try:  #Essentially works as an if/else statement for Distance Sensor
        # If it can read it then it will print the distance, otherwise it will print "Popeyes"
        print((sonar.distance, ))  #Prints the distance in the Serial Monitor
        if sonar.distance <= 20:  #I used 20 because the green both goes up and comes down from 35 to 20

            r = simpleio.map_range(
                sonar.distance, 0, 20, 255,
                0)  # Mapping the LED for the distance and the RGB
            b = simpleio.map_range(sonar.distance, 5, 20, 0, 255)
            g = simpleio.map_range(sonar.distance, 20, 35, 0, 255)
import time
import board
import adafruit_hcsr04
from adafruit_circuitplayground.express import cpx

# This line creates the distance sensor as an object.
sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.D9,
                               echo_pin=board.D6,
                               timeout=0.1)
pixels = cpx.pixels
pitchMultiplier = 300  # Change this value to modify the pitch of the theremin.


def wheel(pos):
    # Input a value 0 to 255 to get a color value.
    # The colours are a transition r - g - b - back to r.
    if pos < 0 or pos > 255:
        return (0, 0, 0)
    if pos < 85:
        return (255 - pos * 3, pos * 3, 0)
    if pos < 170:
        pos -= 85
        return (0, 255 - pos * 3, pos * 3)
    pos -= 170
    return (pos * 3, 0, 255 - pos * 3)


while True:
    try:
        handDistance = int(sonar.distance)
        print("Distance:", handDistance)
示例#18
0
# declare sensors and servos
# the mic input
mic = audiobusio.PDMIn(board.MICROPHONE_CLOCK,
                       board.MICROPHONE_DATA,
                       sample_rate=16000,
                       bit_depth=16)

# Record an initial sample to calibrate. Assume it's quiet when we start.
samples = array.array('H', [0] * NUM_SAMPLES)

# Servos(servo1 controles head, servo2 controles arm)
servo1_position = servo2_position = servo3_position = Vspeed(False)

# read sonar to control blush
sonar = adafruit_hcsr04.HCSR04(trigger_pin=(board.A2), echo_pin=(board.A3))

# the blush on drive 1
led = crickit.drive_1
led_brightness = Vspeed(True)

# motion
while True:
    mic.record(samples, len(samples))
    magnitude = normalized_rms(samples)
    magnitude_sum = 0
    try:
        print("distance is: ", sonar.distance)
        print("mag is: ", magnitude)

        while sonar.distance < inti_dis:
示例#19
0
# import statements
import time
import board
import adafruit_hcsr04
#Change the pins
sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.D3,
                               echo_pin=board.D4,
                               timeout=1.0)  # set pins for sonar
#Use this to check the distance
while True:
    try:
        print(sonar.distance)  # print the distance read for sonar
    except RuntimeError:
        print("Retrying!")  # if there is an error print error message
    time.sleep(1.0)  # sleep for 1 second
示例#20
0
import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import subprocess
import threading
import time
import board
import adafruit_hcsr04
import math
import RPi.GPIO as io
import atexit
import random

sonar_right = adafruit_hcsr04.HCSR04(trigger_pin=board.D5, echo_pin=board.D6)
sonar_left = adafruit_hcsr04.HCSR04(trigger_pin=board.D13, echo_pin=board.D19)

debug = False

frame_map = {
    "blink": 2,
    "angry": 4,
    # "test": 6,
    "test2": 3,
    "bored": 5,
    "excited": 3,
    "sad": 5,
    "sleepy": 4,
    "shaky": 6,
    # "spiral": 3
示例#21
0
#If we are allowed to use this additional library
#import time
#import board
import adafruit_hcsr04
#Change the pins
sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.A3, echo_pin=board.A4)
#Use this to check the distance
#sonar.distance

import board

import simpleio


# Define pin connected to piezo buzzer.
PIEZO_PIN = board.A1
NOTE_B0  =31
NOTE_C1  =33
NOTE_CS1 =35
NOTE_D1  =37
NOTE_DS1 =39
NOTE_E1  =41
NOTE_F1  =44
NOTE_FS1 =46
NOTE_G1  =49
NOTE_GS1 =52
NOTE_A1  =55
NOTE_AS1 =58
NOTE_B1  =62
NOTE_C2  =65
NOTE_CS2 =69
import sys
import time
import board
import busio
import adafruit_tca9548a
import adafruit_tcs34725
import adafruit_hcsr04
from adafruit_bus_device.i2c_device import I2CDevice

#gpio definitions
LEFT_US_PIN_PAIR = [board.D19,board.D26]
RIGHT_US_PIN_PAIR = [board.D16,board.D20]

if __name__ == "__main__":
    #setup
    left_us = adafruit_hcsr04.HCSR04(trigger_pin=LEFT_US_PIN_PAIR[0], echo_pin=LEFT_US_PIN_PAIR[1])
    right_us = adafruit_hcsr04.HCSR04(trigger_pin=RIGHT_US_PIN_PAIR[0], echo_pin=RIGHT_US_PIN_PAIR[1])

    try:
        while 1:
            #us info
            try:
                time.sleep(1)
                left_dist = left_us.distance
            except RuntimeError:
                left_dist = -1.0
            try:
                time.sleep(1)
                right_dist = right_us.distance
            except RuntimeError:
                right_dist = -1.0
示例#23
0
import board
import time
import digitalio
import adafruit_hcsr04 #This is the file we needed to add into our lib folder to make the sensor work
sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.D8, echo_pin=board.D9) #Saying which pins the distance sensor is connected to
import neopixel #Library for the onboard neopixel LED
led = neopixel.NeoPixel(board.NEOPIXEL, 1) #Setting up the neopixel
led.brightness = 0.3 #Setting the correct brightness for the neopixel
r = 255 #Starting the LED at red
g = 0
b = 0

while True:
    try: #You have to put "try" so that the code doesn't just stop when the hcsr04 doesn't get a distance
        distance = int(sonar.distance) #A new variable named distance is used for all the led work so that even if we don't 
                                       #get a new distance in any give loop, the led will still work
        print((sonar.distance)) #Printing the distance every second
        time.sleep(.1)
        print(r,g,b) #Printing my color variables so I can make sure they're working right
        led.fill((r, g, b)) #Using my r, g, and b variables to light up the LED
    except RuntimeError: #If there is an error with the distance sensor, it just prints retrying and keeps going 
        #print("Retrying!")
        pass
    if distance <= 5: #When the distance is less than 5 the LED is red
        r = 255
        b = 0
        g = 0
    if distance <= 20 and distance > 5: #When the distance is between 5 and 20, the red goes down slowly as the blue goes up
        r = 255 - (17*distance)
        b = 0 + (17*distance)
        g = 0
示例#24
0
# Libraries
import time
import board
import adafruit_hcsr04
import neopixel

pixel_pin = board.NEOPIXEL  # pin used to drive the neopixel
num_pixels = 1  # number of pixels being used | in this case (1)

pixels = neopixel.NeoPixel(
    pixel_pin,
    num_pixels,
    brightness=0.3,
    auto_write=False,
)  # defines pixels
sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.D9,
                               echo_pin=board.D10)  # calculates the distance


# This function calculates the distance and sets up the color according to distance
def color(distance, target, range):
    return int(max(255 - 255 * abs(((distance - target) / range)), 0))


# distance varitables
# it assigns a specific distance number for each color to take effect
redTarget = 5
blueTarget = 20
greenTarget = 35
colorRange = 15

while True:
示例#25
0
import time
import board  #pylint: disable-msg=import-error
import neopixel  #pylint: disable-msg=import-error
import adafruit_hcsr04  #pylint: disable-msg=import-error
import adafruit_fancyled.adafruit_fancyled as fancy  #pylint: disable-msg=import-error
from myfunction import mapp
from constrain import clamp

dot = neopixel.NeoPixel(
    board.NEOPIXEL,
    1)  #create a neopixel object at pin neopixel that is only one led long
sonar = adafruit_hcsr04.HCSR04(
    trigger_pin=board.D4, echo_pin=board.D3
)  #create a distance sensor object with a trigger pin(the one making the sound) at 4 and an echo pin (the one receiving) at 3

while True:
    try:  #do this unless there is an error
        color = fancy.CHSV(
            int(round(mapp(clamp(sonar.distance, 5, 35), 5, 35, 255, 85))),
            255, 50)
        #↑↑↑ take the distance value and make the minimum 5cm and the max 35cm, then map the distance value in its range to a range from 255 to 85,
        #↑↑↑ then set the hue component of "color" equal to it. Saturation is permenantly 255 and value is always 50
        packed = color.pack(
        )  #turn hue, saturation, and value into one number called "packed"
        dot.fill(packed)  #make the led turn whatever color packed is
    except RuntimeError:  #if there is an error do this (with the ultrasonic sensor this usually means something is too far away)
        print("Retrying!")
    time.sleep(0.1)
    #mapp is defined like this
    '''def mapp(x,in_min,in_max,out_min,out_max): 
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min'''
示例#26
0
import board
import digitalio
import time
import adafruit_hcsr04

ledGreen = digitalio.DigitalInOut(board.D7)
ledYellow = digitalio.DigitalInOut(board.D8)
ledRed = digitalio.DigitalInOut(board.D9)
buzzer = digitalio.DigitalInOut(board.D11)

ledGreen.direction = digitalio.Direction.OUTPUT
ledYellow.direction = digitalio.Direction.OUTPUT
ledRed.direction = digitalio.Direction.OUTPUT
buzzer.direction = digitalio.Direction.OUTPUT

distanceSensor = adafruit_hcsr04.HCSR04(trigger_pin=board.D4,
                                        echo_pin=board.D2)


class Init_State(State):
    def __init__(self):
        print("“Obstacle Detector Device is Working.")
        ledGreen.value = True
        time.sleep(2)
        ledGreen.value = False
        time.sleep(2)
        ledYellow.value = True
        time.sleep(2)
        ledYellow.value = False
        time.sleep(2)
        ledRed.value = True
        time.sleep(2)
示例#27
0
# wiring
# Trig  ----  GPIO27
# Echo  ----  GPIO17

# sudo apt install libgpiod2
# pip install adafruit-circuitpython-hcsr04

import time
import board
import adafruit_hcsr04

sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.D27, echo_pin=board.D17)

while True:
    try:
        print((sonar.distance, ))
    except RuntimeError:
        print("Retrying!")
    time.sleep(0.1)
示例#28
0
# Meg Gist
# CircuitPython Distance Sensor
import time
import board
import adafruit_hcsr04
import neopixel
import simpleio
radishBat = adafruit_hcsr04.HCSR04(trigger_pin=board.D3, echo_pin=board.D2)
# "radishBat" being the distance sensor
candyCorn = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=.1)
# "candyCorn" being the NeoPixel
r = 0
b = 0
g = 0
# [0, ... , 20]
# [255, ... , 0]
while True:
# So turns out it's literally a function
    try:
        dist = radishBat.distance
        # The color of the NeoPixel changes depending on the distance of the sensor
        if dist <= 20:
            # Syntax (using domain and range in respect to treating like a function):
            # map_range(x(in this case, distance), domain min, domain max, range min, range max)
            r = simpleio.map_range(dist, 0, 20, 255, 0)
            b = simpleio.map_range(dist, 5, 20, 0, 255)
            g = simpleio.map_range(dist, 20, 35, 0, 255)
        else:
            r = simpleio.map_range(dist, 0, 20, 255, 0)
            b = simpleio.map_range(dist, 20, 35, 255, 0)
            g = simpleio.map_range(dist, 20, 35, 0, 255)
示例#29
0
# Initialize the camera and start it for image capturing
pygame.camera.init()
cameras = pygame.camera.list_cameras()
print(cameras)
cam = pygame.camera.Camera(cameras[0], (640, 480))
cam.start()

# Create a font object to hold text
pygame.font.init()
d1 = pygame.font.Font(None, 50)

# Create the pygame surface (unsure what this does)
frame = pygame.Surface((640,480))

# initialize the distance sensor for proper GPIO pin release
with hcsr.HCSR04(trigger_pin=board.D16, echo_pin=board.D20) as sonar:
    while True:
        # Handles events
        for event in pygame.event.get():
            # If the program was ended then exit the application
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    sys.exit()
                elif event.key == pygame.K_f:
                    pygame.display.toggle_fullscreen()
                
        # Gets an image and puts it on the previously created surface
        cam.get_image(frame)
        
示例#30
0
import time
import board
import adafruit_hcsr04

sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.GPIO2, echo_pin=board.GPIO3)

while True:
    print((sonar.distance, ))
    time.sleep(1)