def __init__(self): GPIO.setmode(GPIO.BCM) self.s = DistanceSensor(18, 16) GPIO.setup(pin_buzz, GPIO.OUT) self.stop() GPIO.setup(pin_button, GPIO.IN, pull_up_down=GPIO.PUD_UP) for i in range(1, 10): self.distance = self.s.distance() print("Distance setup completed.") self.button = False self.lock = _thread.allocate_lock()
def read_distance_sensor(): """ Read the detected range by the distance sensor. Uses the :py:meth:`~distance_sensor.DistanceSensor.read_range_single` method. :returns: The distance to the object as measured in millimeters. Range is up to 2.3 meters. :rtype: int :raises OSError: When there's trouble reaching the sensor. :raises ImportError: If this module is run from a firmware that doesn't have the :py:mod:`distance_sensor` module. """ global _DS if _DS is None: from distance_sensor import DistanceSensor _DS = DistanceSensor() return _DS.read_range_single()
class Automation(): def __init__(self): GPIO.setmode(GPIO.BCM) self.s = DistanceSensor(18, 16) GPIO.setup(pin_buzz, GPIO.OUT) self.stop() GPIO.setup(pin_button, GPIO.IN, pull_up_down=GPIO.PUD_UP) for i in range(1, 10): self.distance = self.s.distance() print("Distance setup completed.") self.button = False self.lock = _thread.allocate_lock() def beep(self): GPIO.output(pin_buzz, GPIO.HIGH) def stop(self): GPIO.output(pin_buzz, GPIO.LOW) def off(self): self.lock.acquire() self.button = True self.stop() self.lock.release() def on(self): self.lock.acquire() self.button = False self.lock.release() def run(self): try: while True: if not GPIO.input(pin_button): self.lock.acquire() self.button = self.button ^ True self.lock.release() self.stop() while not GPIO.input(pin_button): time.sleep(0.5) if not self.button: cur_dist = self.s.distance() delta = self.distance - cur_dist if (delta > 20): self.beep() except KeyboardInterrupt: self.stop() GPIO.cleanup()
def setup(): global joystick, mouse_control, scroll_control, distance_sensor GPIO.setmode(GPIO.BOARD) joystick = Joystick(7, 0, 1) mouse_control = Potentiometer(2) scroll_control = Potentiometer(3) distance_sensor = DistanceSensor(35, 37)
def __init__(self, MotorE, MotorA, MotorB, servo_pin, trigger, echo,green,yellow,red,distance_timer): GPIO.setwarnings(False) self.distance_timer = distance_timer self.dcmotor = DCMotor(MotorE, MotorA, MotorB) self.servomotor = ServoMotor(servo_pin) self.distancesensor = DistanceSensor(trigger,echo) self.green = green self.yellow = yellow self.red = red GPIO.setup(self.green,GPIO.OUT) GPIO.setup(self.yellow,GPIO.OUT) GPIO.setup(self.red,GPIO.OUT)
from distance_sensor import DistanceSensor from csv_ext import to_csv sensor = DistanceSensor() sensor.setup() try: while True: distance = sensor.calculate_distance() to_csv(distance) except KeyboardInterrupt: sensor.close() print('interrupted!')
class Roomba: def __init__(self, MotorE, MotorA, MotorB, servo_pin, trigger, echo,green,yellow,red,distance_timer): GPIO.setwarnings(False) self.distance_timer = distance_timer self.dcmotor = DCMotor(MotorE, MotorA, MotorB) self.servomotor = ServoMotor(servo_pin) self.distancesensor = DistanceSensor(trigger,echo) self.green = green self.yellow = yellow self.red = red GPIO.setup(self.green,GPIO.OUT) GPIO.setup(self.yellow,GPIO.OUT) GPIO.setup(self.red,GPIO.OUT) def red_ON(self): GPIO.output(self.red,GPIO.HIGH) def red_OFF(self): GPIO.output(self.red,GPIO.LOW) def yellow_ON(self): GPIO.output(self.yellow,GPIO.HIGH) def yellow_OFF(self): GPIO.output(self.yellow,GPIO.LOW) def green_ON(self): GPIO.output(self.green,GPIO.HIGH) def green_OFF(self): GPIO.output(self.green,GPIO.LOW) def cleanup(self): GPIO.setup(self.green,GPIO.LOW) GPIO.setup(self.yellow,GPIO.LOW) GPIO.setup(self.red,GPIO.LOW) self.servomotor.cleanup() self.dcmotor.cleanup() self.distancesensor.cleanup() GPIO.cleanup() def reverse_turn(self,direction = 1): self.dcmotor.stop() self.servomotor.turn(direction*50) time.sleep(0.5) while True: print("reverse") self.dcmotor.change_speed(100) self.dcmotor.backward() time.sleep(0.8) self.dcmotor.stop() dist = self.distancesensor.get_distance() if dist > 60: break self.servomotor.turn(0) time.sleep(0.5) self.dcmotor.change_speed(90) self.dcmotor.forward() def random_turn(self): LAG = 0.4 if (random.random() < 0.5): direction = +1 else: direction = -1 print("turning") self.dcmotor.change_speed(90) while True: dist = self.distancesensor.get_distance() if dist > 100: time.sleep(LAG) print("turn complete") self.servomotor.turn(0) self.dcmotor.change_speed(80) print(self.servomotor.angle) break elif 80 < dist <= 100: self.servomotor.turn(direction*10) elif 60 < dist <= 80: self.servomotor.turn(direction*30) elif 40 < dist <= 60: self.servomotor.turn(direction*50) elif dist <= 20: print("stopped while turning") self.dcmotor.stop() self.reverse_turn(direction) break time.sleep(self.distance_timer)
def index(): sensor = DistanceSensor() """Video streaming home page.""" return render_template('index.html', distance=sensor.measure_distance())
from distance_sensor import DistanceSensor LEFT_FRONT_MOTOR = 5 LEFT_REAR_MOTOR = 26 RIGHT_FRONT_MOTOR = 13 RIGHT_REAR_MOTOR = 6 robby = Robot(left=(13,6), right=(5,26)) GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(LEFT_FRONT_MOTOR, GPIO.OUT) GPIO.setup(LEFT_REAR_MOTOR, GPIO.OUT) GPIO.setup(RIGHT_FRONT_MOTOR, GPIO.OUT) GPIO.setup(RIGHT_REAR_MOTOR, GPIO.OUT) camera = Camera() camera.initialize() frame = camera.take_frame() distance_sensor = DistanceSensor() client_socket = socket.socket() client_socket.connect(('192.168.137.1', 8000)) connection = client_socket.makefile('rwb') try: while True: frame = camera.take_frame() size = len(frame) distance = distance_sensor.distance() connection.write(struct.pack('<L', int(distance))) connection.write(struct.pack('<L', size)) connection.write(frame) connection.flush()
def on_message(client, userdata, message): # check the topic if message.topic == piTopic: # read from the topic message = json.loads(message.payload.decode()) # time has been set if message['type'] == TIME_SET: # type 1: 'set alarm at sunrise' if message['nature'] == SUNRISE: wakeup_datetime = t.sunrise() # type 2: 'set alarm at time ___' elif message['nature'] == AT: message_time = message['time'] wakeup_datetime = t.timeAt(message_time) # confirm time print("wake up date time: ", wakeup_datetime) # while user is sleeping, i.e. alarm hasn't gone off yet # monitor temperature and humidity of room counter = 1 temperature_data.clear() humidity_data.clear() time_data.clear() while datetime.now() < wakeup_datetime: if datetime.now() > wakeup_datetime - timedelta(seconds=20): led.increment_LED() if counter == 40: print('counter equals 20') # appending to arrays for chart display # temperature data temp = temperature.read() temperature_data.append(temp) # humidity data humid = humidty.read() humidity_data.append(humid) # time of each reading curr_time = t.currentTime() time_data.append(curr_time) # read every 10 minutes counter = 0 counter += 1 sleep(0.1) # time to wake up! start_alarm_message = json.dumps({'type': START_ALARM}) client.publish(appTopic, start_alarm_message) elif message['type'] == RECEIVED_START_ALARM: distance = DistanceSensor() # activate distance sensor to check for user's hand while not handDetected: distance = distance.read() if distance < 200: # hand has come within threshold # turn alarm off stop_alarm_message = json.dumps({'type': STOP_ALARM}) # turn LED off led.turn_off() client.publish(appTopic, stop_alarm_message) handDetected = True stop_alarm_message = json.dumps({'type': STOP_ALARM}) client.publish(appTopic, stop_alarm_message) elif message['type'] == RECEIVED_STOP_ALARM: # greet user and give weather info client.publish( appTopic, json.dumps({ 'type': SPEAK, 'say': speech_messages['GOOD_MORNING'] })) elif message['type'] == ASK_RESULTS: # add all temperature sensor data to a dictionary # monitors room overnight and then displays graphically on web page # check if there is any data first if len(temperature_data) == 0 or len(humidity_data) == 0: client.publish( appTopic, json.dumps({ 'type': SPEAK, 'say': speech_messages['NO_DATA'] })) else: # if user asked for temperature data if message['data_for'] == TEMPERATURE: data = { 'type': RESULTS, 'data_for': TEMPERATURE, 'temp_data': temperature_data, # array of ints 'time': time_data # array strings: hh:mm:ss } client.publish( appTopic, json.dumps({ 'type': SPEAK, 'say': speech_messages['TEMP_DATA'] })) # else if user asked for humidity data elif message['data_for'] == HUMIDITY: data = { 'type': RESULTS, 'data_for': HUMIDITY, 'humid_data': humidity_data, # array of ints 'time': time_data # array strings: hh:mm:ss } client.publish( appTopic, json.dumps({ 'type': SPEAK, 'say': speech_messages['HUMID_DATA'] })) client.publish(appTopic, json.dumps(data))