Exemple #1
0
import numpy as np
import sys

os.putenv('SDL_VIDEORIVER', 'fbcon')
os.putenv('SDL_FBDEV', '/dev/fb1')
os.putenv('SDL_MOUSEDRV', 'TSLIB')
os.putenv('SDL_MOUSEDEV', '/dev/input/touchscreen')

GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(6, GPIO.OUT)
GPIO.setup(19, GPIO.OUT)
ultrasonic2 = DistanceSensor(echo=13, trigger=4)
ultrasonic1 = DistanceSensor(echo=26, trigger=5)
ultrasonic3 = DistanceSensor(echo=16, trigger=24)

pygame.init()
pygame.camera.init()
#pygame.mouse.set_visible(False)
BLACK = 0, 0, 0
WHITE = 255, 255, 255
RED = 255, 0, 0
GREEN = 0, 255, 0

screen = pygame.display.set_mode((320, 240))
size = width, height = 320, 240
my_font = pygame.font.Font(None, 20)
Exemple #2
0
#!/usr/bin/python
# coding=utf-8

from gpiozero import DistanceSensor, LED
from time import sleep, time

sensor_outer = DistanceSensor(21, 20)
sensor_inner = DistanceSensor(26, 19)
led = LED(16)
status = 'off'
led.off()

while True:
    distance_inner = sensor_inner.distance * 100
    distance_outer = sensor_outer.distance * 100
    print('Distance outer', distance_outer, 'cm')
    print('Distance inner', distance_inner, 'cm')
    print('-------------------' * 2)
    if distance_outer < 45:
        if status == 'off':
            status = 'on'
            led.on()
        else:
            status = 'off'
            led.off()
        sleep(2)
    sleep(0.2)
Exemple #3
0
from gpiozero import DistanceSensor
import numpy as np
import random
import pandas as pd
import RPi.GPIO as GPIO
import time
import csv

#  Pins Setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.OUT)
GPIO.setup(18, GPIO.OUT)
q = GPIO.PWM(4, 50)
p = GPIO.PWM(18, 50)
ultrasonic = DistanceSensor(echo=20, trigger=21)
p.start(10)
q.start(10)

print("Started the motors")

# Declaring Variables
global currentHandPosition
currentHandPosition = 0
global currentArmPosition
currentArmPosition = 0
global oldDistance
oldDistance = ultrasonic.distance
time.sleep(1)
global currentDistance
currentDistance = oldDistance
global lastAction
Exemple #4
0
# CamJam EduKit 3 - Robotics
# Worksheet 6 - Measuring Distance

import time  # Import the Time library
from gpiozero import DistanceSensor  # Import the GPIO Zero Library

# Define GPIO pins to use on the Pi
pinTrigger = 17
pinEcho = 18

sensor = DistanceSensor(echo=pinEcho, trigger=pinTrigger)

print("Ultrasonic Measurement")

try:
    # Repeat the next indented block forever
    while True:
        print("Distance: %.1f cm" % (sensor.distance * 100))
        time.sleep(0.5)

# If you press CTRL+C, cleanup and stop
except KeyboardInterrupt:
    print("Exiting")
Exemple #5
0
from gpiozero import DistanceSensor
from time import sleep

sensor = DistanceSensor(echo=18, trigger=17)
while True:
    print('Distance:', sensor.distance * 100)
    sleep(1)
Exemple #6
0
###Import all libraries here
import subprocess
import PiMotor
import time
import sys
from test_sensor import *
from gpiozero import LED, DistanceSensor, Button
from signal import pause

#Define custom pins for UT, led, button
sensor = DistanceSensor(6, 5, max_distance=1, threshold_distance=0.2)
led = LED(20)
button = Button(21)

#Assign motors
m1 = PiMotor.Motor("MOTOR1", 1)  #front left
m2 = PiMotor.Motor("MOTOR2", 1)  #font right
m3 = PiMotor.Motor("MOTOR3", 1)  #rear right
m4 = PiMotor.Motor("MOTOR4", 1)  #rear left


#driving function
def forward(speed):
    m1.forward(speed)
    m2.reverse(speed)
    m3.forward(speed)
    m4.reverse(speed)
    print("Forward")


def reverse(speed):
Exemple #7
0
 def __init__(self):
     self._sensor = DistanceSensor(15, 14, max_distance=4)
Exemple #8
0
from gpiozero import MotionSensor, Servo, DistanceSensor, Buzzer, LED, LightSensor, MCP3008
from RPLCD.i2c import CharLCD
import _thread
import time
import requests
import json

# 感測器
pir = MotionSensor(18)
pir_led = LED(20)  # pir led
servo = Servo(25)
sensor = DistanceSensor(23, 24)  # echo, trig
buzzer = Buzzer(21)
servo_led = LED(16)
cds_sensor = LightSensor(17)
relay = LED(26)
lm35 = MCP3008(channel=1)
lcd = CharLCD('PCF8574', address=0x3f, port=1, backlight_enabled=True)
pot = MCP3008(0)

# 感測器初始狀態
servo.min()
relay.on()
lcd.clear()

# 變數定義
firebase_url = 'https://iotfb-fc0b9.firebaseio.com/'
smartcontrolobj = {"cds_relay": "on", "relay": "off"}
smartobj = {
    "pir": "off",
    "servo": "off",
Exemple #9
0
from gpiozero import DistanceSensor
from time import sleep

sensor = DistanceSensor(17, 27)

while True:
    print('Distance to nearest object is', sensor.distance, 'm')
    sleep(1)
Exemple #10
0
def main():
    """Main loop interface to run the game.

    Runs the game with each cycle in the loop being a single frame.
    In each iteration, all data required to display the frame is
    computed.
    Some events will be triggered asynchrounously after a given amount
    of seconds.

    Returns:
        Nothing. But game will be run on a new window.
    """
    sensor = DistanceSensor(echo=17,
                            trigger=4,
                            max_distance=MAX_DISTANCE,
                            threshold_distance=0.2)

    # Initialize game tools.
    pygame.init()
    screen = pygame.display.set_mode((WINDOWS_WIDTH, WINDOWS_HEIGHT))
    clock = pygame.time.Clock()

    # Initialize variables.
    tardis = Tardis()
    daleks = pygame.sprite.Group()
    stars = pygame.sprite.Group()
    running = True

    # Create event to spawn daleks.
    NEWDALEK = pygame.USEREVENT + 1
    pygame.time.set_timer(NEWDALEK, 1500)

    # Create event to spawn stars.
    NEWSTAR = pygame.USEREVENT + 2
    pygame.time.set_timer(NEWSTAR, 500)

    # Game loop.
    while running:

        # Handle events.
        for event in pygame.event.get():
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    running = False
            elif event.type == QUIT:
                running = False
            elif event.type == NEWDALEK:
                dalek = Dalek()
                daleks.add(dalek)
            elif event.type == NEWSTAR:
                star = Star()
                stars.add(star)

        # Black background.
        screen.fill((0, 0, 0))

        # Generate next frame for each object.
        tardis.update(sensor.distance)
        daleks.update()
        stars.update()

        # Draw on screen each object.
        # Order is important to keep z-index.
        for star in stars:
            screen.blit(star.image, star.rect)
        for dalek in daleks:
            screen.blit(dalek.image, dalek.rect)
        screen.blit(tardis.image, tardis.rect)

        # Detect collisions (TARDIS 💥 Dalek)
        if pygame.sprite.spritecollideany(tardis, daleks):
            running = False

        # Draw everything onto the screen.
        pygame.display.flip()
        # Update a given number (FPS) of times per second.
        clock.tick(FPS)
Exemple #11
0
from gpiozero import DistanceSensor
from time import sleep

sensor1 = DistanceSensor(echo=17, trigger=4)
sensor2 = DistanceSensor(echo=22, trigger=11)

while True:
    x = sensor1.distance
    y = sensor2.distance
    print(x)
    print(y)
    sleep(1)
Exemple #12
0
from gpiozero import DistanceSensor, LED
from signal import pause
from time import sleep

sensor = DistanceSensor(echo=17,
                        trigger=4,
                        max_distance=1,
                        threshold_distance=0.1)
led = LED(16)

sensor.when_in_range = led.on
sensor.when_out_of_range = led.off

pause()
Exemple #13
0
说明:通过超声波传感器测距,并在OLED上显示。
'''

from gpiozero import DistanceSensor

#导入luma相关库,oled lib
from luma.core.render import canvas
from luma.oled.device import ssd1306

from time import sleep

#初始化oled,I2C接口1,oled地址是0x3c
device = ssd1306(port=1, address=0x3c)

#初始化超声波传感器:echo=15 , trig =14
sensor = DistanceSensor(echo=15, trigger=14)

while True:
    
    #将单位变成cm
    distance = sensor.distance *100
    
    #显示结果保留2位小数
    with canvas(device) as draw:
        draw.text((0, 0),  '01Studio', fill="white")
        draw.text((0, 15), 'Distance test:', fill="white")
        draw.text((0, 35), str("%.2f"%distance)+' CM' , fill="white")

    print('Distance to nearest object is %.2f'%distance, 'CM')
    
    sleep(0.5) #采集间隔
Exemple #14
0
import alsaaudio
from gpiozero import DistanceSensor
from time import sleep

sensor3 = DistanceSensor(echo=22, trigger=11)
m = alsaaudio.Mixer('PCM')

val = .5
nval = .5

while True:
    if (sensor3.distance < 1):
        nval = (sensor3.distance)

        while (((nval - val) > 0.1) or ((val - nval) > 0.1)):
            if ((nval - val) > 0.1):
                nval = nval - 0.1

            if ((val - nval) > .1):
                nval = nval + 0.1

        vol = round(((val) * 100) + 30)
        if (vol > 100):
            vol = 100
        m.setvolume(vol)

        val = nval
        sleep(.01)

    else:
from gpiozero import LED, Button, DistanceSensor
from time import sleep

led = LED(21)
#piezo = LED(12)
#button = Button(16)
#
#button.when_pressed = piezo.off
#button.when_released = piezo.on

#while True:
#    if button.is_pressed:
#        led.off()
#    else:
#        led.on()

distanceMeters = DistanceSensor(trigger=18, echo=14, threshold_distance=0.15)

while True:
    distanceInches = distanceMeters.distance * 39.37
    distanceInches = round(distanceInches, 1)

    print('Distance: ', distanceInches, 'in')

    distanceMeters.when_in_range = led.on
    distanceMeters.when_out_of_range = led.off

    sleep(.1)
Exemple #16
0
from gpiozero import DistanceSensor
from time import sleep
from decimal import Decimal, ROUND_HALF_UP
import sys

import tm1637

display = tm1637.TM1637(CLK=20, DIO=21, brightness=7)
display.Clear()

MAX_DISTANCE = 2  # value in meter
sensor = DistanceSensor(echo=24, trigger=23, max_distance=MAX_DISTANCE)

print('\n\nDisplay distance in mm on the 4-digit 7-segment LED.')
print('Be sure to supply 3.3V (not 5V) to the LED module.')
print(
    'OK to supply 5V to the Supersonic Distance Sensor but you need dividing resistors to receive Echo.'
)
print(
    'GPIO connection:\n\tSupersonic Distance Sensor (Trigger=23, Echo=24)\n\tLED Module (CLK=20, DIO=21)\n\n\n'
)

while True:
    distance_mm = sensor.distance * 1000  #  make it in mm
    distance = Decimal(str(distance_mm)).quantize(Decimal('0'),
                                                  rounding=ROUND_HALF_UP)

    data = [0, 0, 0, 0]
    if distance_mm >= MAX_DISTANCE * 1000:
        data = [14, 14, 14, 14]  # EEEE: out of range
    else:
Exemple #17
0
from gpiozero import DistanceSensor, Motor, Button
from time import sleep, time

FMsensor = DistanceSensor(echo=21, trigger=20)

#min distance is 1ft 30cm

high = 0.6
low = 0.1
ok = 0.1337
limit = 5
tot = 10000
waiter = 0.005


def Ds():
    avg = 0.0
    cnt = 0.0
    for x in range(0, 10):
        tmp = FMsensor.distance
        if cnt == limit:
            return avg / x
        if tmp < high and tmp > low:
            avg += tmp
        else:
            cnt += 1
            x -= 1
        sleep(0.00001)
    return avg / 10

Exemple #18
0
# File that makes the RoboCar push boxes out of an arena
# It uses the Motors and LineSensors modules, as well as the sleep function
import Motors
import LineSensors
from gpiozero import DistanceSensor
from time import sleep

# The max_distance is set to 4 so it reads further than 1 m.
# The trigger is connected to GPIO14 and the echo to GPIO15
sensor = DistanceSensor(15, 14, max_distance=4, queue_len=5)

turn_counter = 0  # counter to calculate how much the car has turned
radius = 50  # radius in cm around the car for detection

# On a continuous loop...
while True:
    sleep(0.1)
    distance = sensor.distance * 100  #turn the distace to cm.
    if turn_counter == 5:
        radius + 10  #increase the radius 10 cm.
        turn_counter = 0  # reset the turn counter to 0
    if distance > radius:
        turn_counter = turn_counter + 1
        Motors.right()
    elif distance < radius:
        Motors.forward()
        # If any of the sensors detects a line...
        if LineSensors.isSomeDetected():
            Motors.stop()
            Motors.reverse()
            sleep(1.5)
from gpiozero import DistanceSensor
import os
#loading model
from keras.models import load_model
import numpy as np
from collections import deque
import RPi.GPIO as gpio
import time

cnn = load_model("garbage1.h5")
ultrasonic = DistanceSensor(echo=17, trigger=4, threshold_distance=0.5)

def init():
    #12,16,20,21 -drivermoter 1 gripper moter    12,16 gripper      20,21 up or down control
    #6,13,19,26 .   drivermoter 2 movement moter            6,13 left 19,26 right wheel
    #2,3             ultra sonic sensor
    gpio.setmode(gpio.BCM)
    gpio.setup(2,gpio.OUT)
    gpio.setup(3,gpio.OUT)
    gpio.setup(6,gpio.OUT)
    gpio.setup(12,gpio.OUT)   
    gpio.setup(13,gpio.OUT)
    gpio.setup(16,gpio.OUT)
    gpio.setup(19,gpio.OUT)
    gpio.setup(20,gpio.OUT)
    gpio.setup(21,gpio.OUT)
    gpio.setup(26,gpio.OUT) 
# move foreward()
def moveforward():
    t = 0.5     #time setting
Exemple #20
0
    right_sensor_echo = 26
    right_sensor_trigger = 19
    left_sensor_echo = 6
    left_sensor_trigger = 13
    colorsensor_s0 = 25
    colorsensor_s1 = 8
    s2 = 16
    s3 = 12
    out = 25
    signal = 25

    GPIO.setup(signal, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(12, GPIO.OUT)
    GPIO.setup(16, GPIO.OUT)

    front_ultrasonic = DistanceSensor(front_sensor_echo, front_sensor_trigger)
    right_ultrasonic = DistanceSensor(right_sensor_echo, right_sensor_trigger)
    left_ultrasonic = DistanceSensor(left_sensor_echo, left_sensor_trigger)

    #this allows the color sensor to shoot out certain rays and capture the incident light to determine the color that is seen.
    #different colors can be determined using their RGB code (red, green, blue and black are used in this instance)
    def loop():
        temp = 1
        GPIO.output(s2, GPIO.LOW)
        GPIO.output(s3, GPIO.LOW)
        time.sleep(0.3)
        start = time.time()
        for impulse_count in range(NUM_CYCLES):
            GPIO.wait_for_edge(signal, GPIO.FALLING)
        duration - time.time() - start
        red = NUM_CYCLES / duration
Exemple #21
0
from gpiozero import DistanceSensor
from time import sleep

from pythonosc import osc_message_builder
from pythonosc import udp_client

sensor = DistanceSensor(echo=22, trigger=27)
sense = DistanceSensor(echo=24, trigger=23)
sender = udp_client.SimpleUDPClient('127.0.0.1', 4559)

while True:
    pitch = round(sensor.distance * 100 + 30)
    volume = sense.distance
    sender.send_message('play_this', [pitch, volume])
    sleep(.1)
Exemple #22
0
from gpiozero import DistanceSensor
from time import sleep

sensor = DistanceSensor(23, 24)

while True:
    print("The distance to nearest object is ", sensor.distance, 'm')
    sleep(1)
Exemple #23
0
from gpiozero import DistanceSensor
from time import sleep

from pythonosc import osc_message_builder
from pythonosc import udp_client

sensor = DistanceSensor(echo=17, trigger=4)
sender = udp_client.SimpleUDPClient('127.0.0.1', 4559)

val = .1
nval = .1
while True:
    if (sensor.distance != 1.0):
        nval = (sensor.distance)

        #pitch = round(sensor.distance * 100 + 30)
        #if (pitch <= 80) :
        #sender.send_message('/play_this', pitch)
        while (((nval - val) > 0.1) or ((val - nval) > 0.1)):
            if ((nval - val) > 0.1):
                nval = nval - 0.1

            if ((val - nval) > .1):
                nval = nval + 0.1

        pitch = round(val * 100 + 30)
        if (pitch <= 80):
            sender.send_message('/play_this', pitch)

            val = nval
        sleep(.01)
import time # Import the Time library 

# Distance Variables
HowNear = 0.25
ReverseTime = 0.75
TurnTime = 0.75

# Set the default speed for the motors
DefaultSpeed = 0.4
#DefaultSpeed = 1

# set up our devices
robot = CamJamKitRobot()
redled = LED(23)
blueled = LED(24)
sensor = DistanceSensor(18, 17, max_distance=2, threshold_distance=HowNear)

# Define our functions

# Return True if the ultrasonic sensor sees an obstacle
def IsNearObstacle(localHowNear):
	Distance = Measure()
	print("IsNearObstacle: "+str(Distance))
	if Distance < localHowNear:
		return True
	else:
		return False

# Take a distance measurement
def Measure():
	Distance = sensor.distance
from gpiozero import DistanceSensor
from gpiozero import Robot
from gpiozero.pins.pigpio import PiGPIOFactory
from time import sleep
import math


#Remote GPIO pin setting
#For Rpi 4B
factory1 = PiGPIOFactory(host='192.168.1.3')

#For RPi Zero
factory2 = PiGPIOFactory(host='192.168.1.3')

#connected to raspberry pi 4B
sensor1 = DistanceSensor(echo=18, trigger=26, factory=factory1)
sensor2 = DistanceSensor(echo=16, trigger=20, factory=factory1)

while True:
    print('Distance 1 : ', sensor1.distance * 100)
    print('Distance 2 : ', sensor2.distance * 100)
    sleep(5)
    r1 = sensor1.distance * 100
    r2 = sensor2.distance * 100

    x1 = r1 * math.cos(math.radians(90 - 90))
    z1 = r1 * math.sin(math.radians(90 - 90))
    y1 = 0.0

    x2 = r2 * math.cos(math.radians(90 - 40))
    z2 = r2 * math.sin(math.radians(90 - 40))
Exemple #26
0
 def __init__(self):
     self.front_sensor = DistanceSensor(echo = 22, trigger = 27)
     #self.back_sensor = DistanceSensor(echo = , trigger = )
     self.robot = Robot(left=(6,12), right=(5,13))
     self.move()
Exemple #27
0
from gpiozero import DistanceSensor, Buzzer
import picamera
import time

sensor = DistanceSensor(echo=24, trigger=23)
buzzer = Buzzer(3)
time.sleep(5)
print('Waiting for sensor to settle')

while True:
    d = sensor.distance
    print('Sensing...')

    if d <1:
        print('WARNING! Object detected {} meter away'.format(d))
        buzzer.beep(0.08, 0.08, 1)

    time.sleep(2)
Exemple #28
0
import time
from enum import Enum

from gpiozero import DistanceSensor

ultrasonic = DistanceSensor(echo=17, trigger=4)


class RangeBand(Enum):
    FAR = 1
    MEDIUM = 2
    NEAR = 3


def find_range_band():
    """Calculate the range band, as measured by the ultrasonic sensor"""
    print(ultrasonic.distance)
    if ultrasonic.distance > 0.8:
        return RangeBand.FAR
    elif ultrasonic.distance > 0.4:
        return RangeBand.MEDIUM
    else:
        return RangeBand.NEAR


while True:
    range_band = find_range_band()
    print(ultrasonic.distance, range_band)
    time.sleep(0.2)
Exemple #29
0
from gpiozero import LED, DistanceSensor
from gpiozero.pins.pigpio import PiGPIOFactory
import time
from signal import pause

remote_factory = PiGPIOFactory(host='172.20.10.11')

led = LED(26)
sensor = DistanceSensor(18, 17, max_distance=1, threshold_distance=0.2)


def init():

    led.on()
    time.sleep(0.05)
    led.off()
    time.sleep(0.05)
    led.on()
    time.sleep(0.05)
    led.off()
    time.sleep(0.05)
    led.on()
    time.sleep(0.05)
    led.off()
    time.sleep(0.05)
    led.on()
    time.sleep(1)
    led.off()


#init()
Exemple #30
0
import time
import cv2

from motors import move_left,move_right,move_forward,move_reverse,stop

from gpiozero import AngularServo,DistanceSensor
from gpiozero.pins.pigpio import PiGPIOFactory



# Initialise servos
pigpio_factory = PiGPIOFactory()

servolr = AngularServo(25,pin_factory = pigpio_factory)
servotd = AngularServo(18,pin_factory = pigpio_factory)
ultrasonic = DistanceSensor(echo=4, trigger=27,pin_factory = pigpio_factory)

servolr_now = 0
servotd_now = 0
servolr.angle = servolr_now
servotd.angle = servotd_now
time.sleep(2)
print("initialised servos")

# Constants
cx = -1 # Have to change sign because this servo rotates in the wrong direction
cy = 1

Kp = 80
Kd = 10