Exemple #1
0
def runDist():
    '''
  Distance Sensor Play Area
  '''
    from gpiozero import DistanceSensor
    from time import sleep

    #distSensor = DistanceSensor(echo=13, trigger=6, max_distance=2, queue_len=10)
    #distSensor = DistanceSensor(echo=19, trigger=26, max_distance=2, queue_len=10)

    leftDistSensor = DistanceSensor(echo=27,
                                    trigger=17,
                                    max_distance=2,
                                    queue_len=10)
    rightDistSensor = DistanceSensor(echo=22,
                                     trigger=18,
                                     max_distance=2,
                                     queue_len=10)

    try:
        while True:
            print('Left Distance: ', leftDistSensor.distance * 100)
            print('Right Distance: ', rightDistSensor.distance * 100)
            sleep(0.1)
    except KeyboardInterrupt:
        pass
    finally:
        exit(0)
Exemple #2
0
    def __init__(self, pins, db_filename, timeout):
        '''
        Args:
            pins (dict): a dict that contains info about the pins that the sensors are connected to.
                         should be of form:
                         {
                            "ingress": {
                                "trigger": 17,
                                "echo": 18
                            },
                            "egress": {
                                "trigger": 22,
                                "echo": 23
                            }
                        }
            db_filename (str): database filename
            timeout (float): when a sensor is tripped, how long to wait for the second sensor to trip
        '''
        self.ingress_sensor = DistanceSensor(
            echo=pins['ingress']['echo'], trigger=pins['ingress']['trigger'])
        self.egress_sensor = DistanceSensor(echo=pins['egress']['echo'],
                                            trigger=pins['egress']['trigger'])
        self.db = dbh.DB_Handler(db_filename)
        self.timeout = timeout

        self.ingress_floor = 1  # in meters
        self.egress_floor = 1  # in meters
        self.init_distance()
Exemple #3
0
 def __init__(self):
     '''
 Initializes all the sensors we want to consume data from
 '''
     # I2C bus readers
     self.adc = Adafruit_ADS1x15.ADS1115()
     self.imu = BNO055.BNO055()
     if not self.imu.begin():
         raise RuntimeError(
             'Failed to initialize IMU! Is the sensor connected?')
     # Distance sensors
     self.leftDistSensor = DistanceSensor(
         echo=Constants.DIST_LEFT_ECHO_PIN,
         trigger=Constants.DIST_LEFT_TRIGGER_PIN,
         max_distance=Constants.DIST_MAX_DISTANCE,
         queue_len=Constants.DIST_QUEUE_LENGTH)
     self.rightDistSensor = DistanceSensor(
         echo=Constants.DIST_RIGHT_ECHO_PIN,
         trigger=Constants.DIST_RIGHT_TRIGGER_PIN,
         max_distance=Constants.DIST_MAX_DISTANCE,
         queue_len=Constants.DIST_QUEUE_LENGTH)
     # Sensor values (-0 means that the sensor is not reading data)
     self.steeringPotValue = -0
     self.leftTachValue = -0
     self.rightTachValue = -0
     self.leftDistance = -0
     self.rightDistance = -0
     self.heading = -0
     self.roll = -0
     self.pitch = -0
     self.sysCal = -0
     self.gyroCal = -0
     self.accelCal = -0
     self.magCal = -0
Exemple #4
0
    def __init__(self, motorhat_addr=0x6f):
        # Setup the motorhat with the passed in address
        self._mh = Raspi_MotorHAT(addr=motorhat_addr)

        self.left_motor = self._mh.getMotor(1)
        self.right_motor = self._mh.getMotor(2)

        # Setup the Leds
        self.leds = leds_led_shim.Leds()
        # Set up servo motors for pan and tilt.
        self.servos = Servos(addr=motorhat_addr, deflect_90_in_ms=1)

        # Setup The Distance Sensors
        self.left_distance_sensor = DistanceSensor(echo=17,
                                                   trigger=27,
                                                   queue_len=2)
        self.right_distance_sensor = DistanceSensor(echo=5,
                                                    trigger=6,
                                                    queue_len=2)

        # Setup the Encoders
        EncoderCounter.set_constants(self.wheel_diameter_mm,
                                     self.ticks_per_revolution)
        self.left_encoder = EncoderCounter(4)
        self.right_encoder = EncoderCounter(26)

        # ensure the motors get stopped when the code exits
        atexit.register(self.stop_all)
def main():
    ''' Main function '''
    sensor = DistanceSensor(echo=ECHO, trigger=TRIGGER)
    sensor.when_in_range = report_too_close
    sensor.when_out_of_range = report_ok
    while True:
        print(f"Distance: {sensor.distance*10}cm")
        time.sleep(2)
Exemple #6
0
class Sonar:
    def __init__(self, echo_pin, trigger_pin):
        self.sensor = DistanceSensor(echo=echo_pin, trigger=trigger_pin)

    def get_distance(self):
        return self.sensor.distance * 100

    def stop(self):
        self.sensor.close()
Exemple #7
0
 def get_values(self, count, time_span=0.001):
     GPIO.setmode(GPIO.BCM)
     sensor = DistanceSensor(echo=RPiGPIOPin(self.echo_port),
                             trigger=RPiGPIOPin(self.trigger_port),
                             threshold_distance=self.threshold,
                             max_distance=self.max_distance)
     values = np.array(
         [self.get_value(sensor, time_span) for _ in range(count)])
     sensor.close()
     return values
Exemple #8
0
    def run(self):
        '''
        Loop through each document in the lot's collection and
        track the changes within the spaces.
        '''
        availableSpots = 0

        for sensor in self.collection.find_one()['sensors']:

            sensorClass = DistanceSensor(echo=sensor['echo'],
                                         trigger=sensor['trigger'],
                                         max_distance=0.06,
                                         threshold_distance=0.005)
            sensor[
                "isVacant"] = False if sensorClass.distance < 0.0254 else True

            if sensor["isVacant"] == True:
                availableSpots += 1

            self.collection.update_one(
                {
                    'lotName': self.lotName,
                    'sensors._id': sensor['_id']
                }, {'$set': {
                    'sensors.$.isVacant': sensor["isVacant"]
                }})

            sensorClass.close()

        self.collection.update_one(
            {'lotName': self.lotName},
            {'$set': {
                'availableSpots': availableSpots
            }})

        print('Total available spaces in lot is: {}'.format(availableSpots))
        print('{}: {}'.format(
            self.collection.find_one()["sensors"][0]["_id"],
            self.collection.find_one()["sensors"][0]["isVacant"]))
        print('{}: {}'.format(
            self.collection.find_one()["sensors"][1]["_id"],
            self.collection.find_one()["sensors"][1]["isVacant"]))
        print('{}: {}'.format(
            self.collection.find_one()["sensors"][2]["_id"],
            self.collection.find_one()["sensors"][2]["isVacant"]))
        print('{}: {}'.format(
            self.collection.find_one()["sensors"][3]["_id"],
            self.collection.find_one()["sensors"][3]["isVacant"]))
        print('{}: {}'.format(
            self.collection.find_one()["sensors"][4]["_id"],
            self.collection.find_one()["sensors"][4]["isVacant"]))
        print('{}: {}'.format(
            self.collection.find_one()["sensors"][5]["_id"],
            self.collection.find_one()["sensors"][5]["isVacant"]))
Exemple #9
0
def main():
    # ピン設定
    factory = PiGPIOFactory()
    # sensor = DistanceSensor(PIN_ECHO, PIN_TRIG, max_distance=1, threshold_distance=0.1, pin_factory=factory)
    # sensor = DistanceSensor(PIN_ECHO, PIN_TRIG, max_distance=1, threshold_distance=0.2, pin_factory=factory)
    sensor = DistanceSensor(PIN_ECHO, PIN_TRIG, max_distance=1, threshold_distance=0.3, pin_factory=factory)
    # sensor = DistanceSensor(PIN_ECHO, PIN_TRIG, max_distance=1, threshold_distance=0.7, pin_factory=factory)
    # sensor = DistanceSensor(PIN_ECHO, PIN_TRIG, max_distance=1, threshold_distance=0.4, pin_factory=factory)
    led = LED(PIN_LED1, pin_factory=factory)

    sensor.when_in_range = led.on
    sensor.when_out_of_range = led.off
    pause()
Exemple #10
0
 def __init__(self):
     self.humidify_water_level_sensor = Button(
         self.HUMIDIFY_WATER_LEVEL_PIN)
     self.distance_sensor = DistanceSensor(
         trigger=self.RANGING_MODULE_TRIGGER_PIN,
         echo=self.RANGING_MODULE_ECHO_PIN)
     self.cpu_temperature_sensor = CPUTemperature()
    def gpioInit(self):
        self.vrChannel = MCP3008(channel=7)
        self.distanceSensor = DistanceSensor(23, 24)
        self.servo = AngularServo(18, min_angle=-45, max_angle=45)
        self.servo.angle = 0.0

        Timer(1, self.gpioAutoUpdate).start()
Exemple #12
0
    def __init__(self, motorhat_addr=0x6f):
        # Setup the motorhat with the passed in address
        self._mh = Raspi_MotorHAT(addr=motorhat_addr)

        # get local variable for each motor
        self.left_motor = self._mh.getMotor(1)
        self.right_motor  = self._mh.getMotor(2)

        # Setup The Distance Sensors
        self.left_distance_sensor = DistanceSensor(echo=17, trigger=27, queue_len=2)
        self.right_distance_sensor = DistanceSensor(echo=5, trigger=6, queue_len=2)

        # Setup the Leds
        self.leds = leds_led_shim.Leds()
        # ensure the motors get stopped when the code exits
        atexit.register(self.stop_all)
Exemple #13
0
def run(publish):
    sensor = DistanceSensor(echo=20, trigger=21, max_distance=10)
    while True:
        print('Value: ', sensor.value)
        print('Distance: ', sensor.distance, ' / ', sensor.max_distance)
        publish('obstacle', {'distance': sensor.value})
        sleep(0.1)
 def __init__(self,
              echo_pin=17,
              trigger_pin=4,
              max_dist=2,
              threshold_dist=1,
              pub_topic="immerse/auth"):
     self.ultrasonic = DistanceSensor(echo=echo_pin,
                                      trigger=trigger_pin,
                                      max_distance=max_dist,
                                      threshold_distance=threshold_dist)
     self.ultrasonic.when_in_range = self.__person_detected
     self.ultrasonic.when_out_of_range = self.__person_not_detected
     self.pub_topic = pub_topic
     self.timer = Timer(3.0, self.shutdownCountoff)
     # self.client = mqtt.Client()
     # self.client.username_pw_set(user, password = psw)
     # self.client.tls_set(ca_certs = "../ca.crt")
     # self.client.connect(host,port,keepalive=60,bind_address="")
     # self.client.publish(self.pub_topic, "{\"State\": \"OFF\"}", qos=1, retain=True)	# Do MQTT Stuff to tell the mirror to shut off
     publish.single(self.pub_topic,
                    "{\"State\": \"OFF\"}",
                    hostname=self.host,
                    port=self.port,
                    retain=True,
                    qos=1,
                    auth={
                        "username": self.user,
                        "password": self.psw
                    },
                    tls={"ca_certs": "../ca.crt"})
Exemple #15
0
def HCSR04(name, pin_tri, pin_echo):
    try:
        sensor = DistanceSensor(echo=pin_echo, trigger=pin_tri, max_distance=1, threshold_distance=0.3)

        return {"distance": sensor.distance, "unit": "meter"}
    except:
        return 'Couldn\'t read from Distance Sensor'
def control(spip):
    sensor = DistanceSensor(echo=17, trigger=4,threshold_distance=0.5)
    sensor2 = DistanceSensor(echo=23,  trigger=24,threshold_distance=0.5)
    # make sure that sonic pi is listening to port 4559
    sender = udp_client.SimpleUDPClient(spip,4559)

    while True:
        try:
            r1 = (sensor.distance* 100) #send numbers in range 0->100
            r2 = (sensor2.distance* 100)
            sender.send_message('/play_this',[r1,r2]) #sends list of 2 numbers
            print("r1:",round(r1,2),"r2:",round(r2,2))
            sleep(0.06)
        except KeyboardInterrupt:
            print("\nExiting")
            sys.exit()
Exemple #17
0
    def __init__(self):

        self.remote_factory = PiGPIOFactory(host='192.168.0.10')

        self.sensor = DistanceSensor(echo=24,
                                     trigger=18,
                                     pin_factory=self.remote_factory,
                                     max_distance=3.0)
Exemple #18
0
def car_stop(dist_gpios, buz_gpio):
    x, y = dist_gpios
    dist_sensor = DistanceSensor(x, y)
    buz = Buzzer(buz_gpio)
    while True:
        if dist_sensor.distance <= 1.5:
            buz.on()
        else:
            buz.off()
Exemple #19
0
def start_sensor():
    config = read_global_config('sensor')
    try:
        if config:
            d_sensor = DistanceSensor(
                echo=24,
                trigger=23,
                max_distance=config.get('max_distance'),
                threshold_distance=config.get('threshold'),
                queue_len=(config.get('delay') * 40))
            d_sensor.when_in_range = wakeup
            d_sensor.when_out_of_range = standby
            logging.info('Sensor Enabled ....')
            return d_sensor
        kill_app("No configuration exists!")
    except Exception as e:
        logging.error("loading sensor failed, check configuration!")
        raise e
Exemple #20
0
 def update(cls, is_running, share_value):
     from gpiozero import DistanceSensor
     sensor = DistanceSensor(echo=18, trigger=4, max_distance=5)
     try:
         while is_running.is_set():
             share_value.value = sensor.distance
             time.sleep(1 / 60)
     except KeyboardInterrupt as e:
         pass
Exemple #21
0
def ping():
    TRIG = 4
    ECHO = 17

    ultrasonic = DistanceSensor(ECHO, TRIG)

    distance_m = ultrasonic.distance

    return distance_m
Exemple #22
0
    def __init__(self, remote_address):

        # set PINs on BOARD
        log.debug("Initializing Distance...")
        log.debug("> echo 1 pin: " + str(_conf['echo_1_pin']))
        log.debug("> trig 1 pin: " + str(_conf['trig_1_pin']))
        log.debug("> echo 2 pin: " + str(_conf['echo_2_pin']))
        log.debug("> trig 2 pin: " + str(_conf['trig_2_pin']))

        # using DistanceSensor
        rem_pi = PiGPIOFactory(host=remote_address)
        self.distance1 = DistanceSensor(echo=_conf['echo_1_pin'],
                                        trigger=_conf['trig_1_pin'],
                                        pin_factory=rem_pi)
        self.distance2 = DistanceSensor(echo=_conf['echo_2_pin'],
                                        trigger=_conf['trig_2_pin'],
                                        pin_factory=rem_pi)
        log.debug("...init done!")
Exemple #23
0
class RoPiDistance:

    # initialization
    def __init__(self, remote_address):

        # set PINs on BOARD
        log.debug("Initializing Distance...")
        log.debug("> echo 1 pin: " + str(_conf['echo_1_pin']))
        log.debug("> trig 1 pin: " + str(_conf['trig_1_pin']))
        log.debug("> echo 2 pin: " + str(_conf['echo_2_pin']))
        log.debug("> trig 2 pin: " + str(_conf['trig_2_pin']))

        # using DistanceSensor
        rem_pi = PiGPIOFactory(host=remote_address)
        self.distance1 = DistanceSensor(echo=_conf['echo_1_pin'],
                                        trigger=_conf['trig_1_pin'],
                                        pin_factory=rem_pi)
        self.distance2 = DistanceSensor(echo=_conf['echo_2_pin'],
                                        trigger=_conf['trig_2_pin'],
                                        pin_factory=rem_pi)
        log.debug("...init done!")

    # is close
    def is_close(self):
        distance1 = (self.distance1.distance * 100) < _conf['SAFETY_DISTANCE']
        distance2 = (self.distance2.distance * 100) < _conf['SAFETY_DISTANCE']
        log.debug("> is close ?" + str(distance1 or distance2))
        return distance1 or distance2

    # get distance 1
    def get_distance1(self):
        log.debug("> Distance 1: " + str(self.distance1.distance * 100))
        return self.distance1.distance * 100

    # get distance 2
    def get_distance2(self):
        log.debug("> Distance 2: " + str(self.distance2.distance * 100))
        return self.distance2.distance * 100

    # terminate
    def terminate(self):
        log.debug("Distance termination...")
        self.distance1.close()
        self.distance2.close()
Exemple #24
0
def getDistance():
    with warnings.catch_warnings():
        try:
            pinTrigger = 17
            pinEcho = 18
            sensor = DistanceSensor(echo=pinEcho, trigger=pinTrigger)
            return sensor.distance
        except:
            return -1
    return -1
Exemple #25
0
def get_distance():
    measurements = []
    # Trying to set max_distance to 2m, default is 1m
    sensor = DistanceSensor(echo=17, trigger=27)
    for i in range(5):
        dist = sensor.distance  # Initial value in m
        measurements.append(dist)
        sleep(0.25)
    result = statistics.mean(measurements) * 100  # Convert to cm
    return result  # Returns result in cm
Exemple #26
0
 def __init__(self, config: dict):
     super().__init__("distancesensors")
     self.sensors = {}
     self.state = {}
     for name, sensor in config['distancesensors'].items():
         self.sensors[name] = DistanceSensor(
             sensor['echo'],
             sensor['trigger'],
             max_distance=sensor['max_distance'],
             pin_factory=PiGPIOFactory())
         self.state[name] = {"distance": -1}
Exemple #27
0
    def __init__(self, speed: float = 1):
        self.speed = speed
        self.diff = 0.04

        self.forward_right_motor = Motor(forward=12, backward=16)
        self.backward_right_motor = Motor(forward=21, backward=20)

        self.forward_left_motor = Motor(forward=23, backward=18)
        self.backward_left_motor = Motor(forward=24, backward=25)

        self.sensor = DistanceSensor(13, 6)
Exemple #28
0
 def __init__(self,
              max_distance=3,
              threshold_distance=0.01,
              echo=17,
              trigger=18):
     self._echo = echo
     self._trigger = trigger
     self.ultrasonic = DistanceSensor(echo=self._echo,
                                      trigger=self._trigger,
                                      max_distance=max_distance,
                                      threshold_distance=threshold_distance)
def publisher_proximity():

    sensor = DistanceSensor(trigger=23, echo=24)
    distance = sensor.distance * 100
    sensor = None

    distanceStr = '%.1f' % distance
    datetimeStr = datetime.datetime.now().strftime('%Y-%m-%d+%H:%M:%S')

    queryUrl = 'https://esteban-233722.appspot.com/raspberry/proximity/' + datetimeStr + "/" + distanceStr
    return urllib.request.urlopen(queryUrl).read(1000)
Exemple #30
0
 def __init__(self, level='lvl0'):
     #instantiating all the motors and sensors on the bot
     self.robot = Robot(left=MOTOR_L, right=MOTOR_R)
     self.sonic = DistanceSensor(echo=SONIC_ECHO, trigger=SONIC_TRIG)
     self.ir_l = MCP3008(IR_L)
     self.ir_r = MCP3008(IR_R)
     self.button = MCP3008(BTN)
     self.bz = TonalBuzzer(BZ)
     self.led = RGBLED(R, G, B)
     #creating custom variables
     self.speed = self.get_speed(level)
from gpiozero import DistanceSensor, LED
from signal import pause

sensor = DistanceSensor(23, 24, max_distance=1, threshold_distance=0.2)
led = LED(16)

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

pause()