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)
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()
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
#!/usr/bin/env python3 import move import signal from gpiozero import DistanceSensor min_distance = 0.15 sonic_sensor = DistanceSensor( echo=18, trigger=17, threshold_distance=min_distance) speed = 0.5 def exit_gracefully(): exit() sonic_sensor.when_in_range = lambda: move.stop() sonic_sensor.when_out_of_range = lambda: move.forward() signal.signal(signal.SIGINT, exit_gracefully) move.forward(speed) while True: sonic_sensor.wait_for_in_range() move.backward(speed) sonic_sensor.wait_for_out_of_range() move.right(speed, 0.75) exit_gracefully()
from gpiozero import Robot, DistanceSensor from signal import pause sensor = DistanceSensor(23, 24, max_distance=1, threshold_distance=0.2) robot = Robot(left=(4, 14), right=(17, 18)) sensor.when_in_range = robot.backward sensor.when_out_of_range = robot.stop pause()
lcd = LCD(2, 3, 4, 5, 6, 7, 16, 2) player = Player() sensor = DistanceSensor(trigger=17, echo=18) sensor.threshold_distance = 0.2 botao1.when_pressed = ligar_campainha botao1.when_released = enviar_mensagem botao2.when_pressed = led1.off botao3.when_pressed = iniciar_gravacao botao3.when_released = parar_gravacao sensor.when_in_range = pessoa_porta sensor.when_out_of_range = pessoa_saiu # loop infinito ultimo_id = -1 while True: dados = {'offset': ultimo_id + 1} updates = get(endereco_updates, json=dados).json() if updates['ok']: result = updates['result'] for r in result: mensagem = r["message"] if ("text" in mensagem):
def sense(): #stop robot robot.stop() #record time start = time.time() #this function will stop when it see's any motion but if will stop anyway after 2 seconds pir.wait_for_motion(timeout=2) #if it took less than 2 seconds for the waitForMotion fuction to stop then it detected movement if time.time() - start < 1.9999999: #buzzer on led.on() #wait 2 seconds time.sleep(2) #buzzer off led.off() else: #the thing in front of the robot is a walll #turn to get out of the way robot.left() time.sleep(1) robot.stop() def move(): robot.forward() sensor.when_in_range = sense when_out_of_range = move pause()
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()
# Edit line 6 to match your chosen GPIO pin from gpiozero import Motor, DistanceSensor from time import sleep motor = Motor(backward=4) sensor = DistanceSensor(23, 24, max_distance=1, threshold_distance=0.2) sensor.when_in_range = motor.backward sensor.when_out_of_range = motor.close
from gpiozero import LED, Button, DistanceSensor from time import sleep led = LED(21) piezo = LED(12) distanceMeters = DistanceSensor(trigger=8, echo=11, 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 if distanceInches <= 3: piezo.on() else: piezo.off() sleep(.1)
sensor.threshold_distance = 0.10 aplicativo = None base = "https://api.telegram.org/bot" + chave endereco_enviar_mensagem = base + "/sendMessage" endereco_enviar_foto = base + "/sendPhoto" endereco_enviar_voice = base + "/sendVoice" endereco_atualizacao = base + "/getUpdates" endereco_download = base + "/getFile" botao.when_pressed = liga_buzzer botao.when_released = desliga_enviando_mensagem botao2.when_pressed = led.off botao3.when_pressed = grava_audio botao3.when_released = parar_gravacao sensor.when_in_range = chegou_na_porta sensor.when_out_of_range = saiu_da_porta player = Player() #loop infinito while True: dados = {"offset": proximo_id_de_update} resposta_atualizada = get(endereco_atualizacao, json=dados) dicionario_da_resposta = resposta_atualizada.json() for resultado in dicionario_da_resposta["result"]: mensagem = resultado["message"] if "text" in mensagem: texto = mensagem["text"] if texto == "Abrir": led.on()
from gpiozero import DistanceSensor, LED, Button from time import sleep from datetime import datetime from signal import pause from picamera import PiCamera dist_sensor = DistanceSensor(23, 24, max_distance=1, threshold_distance=0.2) capture_button = Button(12) camera = PiCamera() led = LED(25) def capture(): for i in range(10000): print(i) def recording_on(): for i in range(2000000000000000): print(i) #def recording_off(): capture_button.when_pressed = capture dist_sensor.when_in_range = recording_on #dist_sensor.when_out_of_range = recording_off pause()
from gpiozero import DistanceSensor from gpiozero import LED from time import sleep mySensor = DistanceSensor(echo=24, trigger=18, max_distance=2) myAlarm = LED(6) mySensor.when_in_range = myAlarm.on mySensor.when_out_of_range = myAlarm.off
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()
turnStraight() driveForward() elif left.distance < threshold and right.distance < threshold and not center.distance < threshold: turnStraight() driveForward() elif not left.distance < threshold and right.distance < threshold and center.distance < threshold and center.distance > .4: turnLeft() driveForward() elif left.distance < threshold and not right.distance < threshold and center.distance < threshold and center.distance > .4: turnRight() driveForward() elif left.distance < 1: turnRight() elif right.distance < 1: turnLeft() else: fullBrake() center.when_in_range = turnDirection center.when_out_of_range = turnDirection right.when_in_range = turnDirection right.when_out_of_range = turnDirection left.when_in_range = turnDirection left.when_out_of_range = turnDirection
sensor.threshold_distance = 0.10 campainha = Buzzer(16) botao1 = Button(11) botao2 = Button(12) # definição de funções def tocaCampainha(): campainha.beep(n=1, on_time=0.5) def distance(): led.blink(n=2) def ex3(): d = 100 * sensor.distance lcd.clear() lcd.message("%.1f cm" % d) documento = {"distancia": d, "data/hora": datetime.now()} colecao.insert(documento) # criação de componentes botao1.when_pressed = tocaCampainha botao2.when_pressed = ex3 sensor.when_in_range = distance sensor.when_out_of_range = distance
"Apt": apartamento, "Data/Hora": datetime.now(), "nome": morador } colecaolog.insert(documento) sleep(1) lcd.clear() def dados(): apt = coletar_digitos("Digite o apto:") busca = {"Apt": apt} ordenacao = [["Data/Hora", DESCENDING]] lista = list(colecaolog.find(busca, sort=ordenacao)) for item in lista: if (item["nome"] == None): print(item["Data/Hora"].strftime("%d/%m (%H:%M)") + ": SENHA INCORRETA") else: print(item["Data/Hora"].strftime("%d/%m (%H:%M)") + ": " + item["nome"]) # criação de componentes lcd = LCD(2, 3, 4, 5, 6, 7, 16, 2) sensor.threshold_distance = 0.2 sensor.when_in_range = entrada botao1 = Button(11) botao1.when_pressed = dados # loop infinito
ultrasonic = DistanceSensor( echo = ULTRASONIC_ECHO_PIN, trigger = ULTRASONIC_TRIG_PIN, max_distance = ULTRASONIC_MAX, threshold_distance = ULTRASONIC_DIST ) # LED for each sensor green = LED( BUTTON_LED_PIN ) red = LED( PHOTOCELL_LED_PIN ) blue = LED( ULTRASONIC_LED_PIN ) def take_picture_if_light( led, name, light = False ) : global photocell if ( ( light or photocell.light_detected ) and not taking_picture() ) : led.on() os.system( '/opt/bloginabox/biab camera-take-photo "' + datetime.now().strftime( '%-I:%M:%S %p' ) + ' - ' + name + '"' ) led.off() def taking_picture() : return green.is_lit or red.is_lit or blue.is_lit try : ultrasonic.when_in_range = lambda: take_picture_if_light( blue, 'Ultrasonic' ) photocell.when_light = lambda: take_picture_if_light( red, 'Photocell', True ) button.when_pressed = lambda: take_picture_if_light( green, 'Button' ) pause() except KeyboardInterrupt : print( ' Exiting via CTRL+C...' )
# Edit line 6 to match your chosen GPIO pin from gpiozero import Motor, DistanceSensor from time import sleep motor = Motor(forward=4) sensor = DistanceSensor(23,24, max_distance=1, threshold_distance=0.2) sensor.when_in_range = motor.forward sensor.when_out_of_range = motor.close
trigger=27, max_distance=1, threshold_distance=0.1) led = LED(5) # sv = Servo(18) # sv.min() # sleep(0.1) def move_max(): sv = Servo(18) sv.max() sleep(0.2) led.on() # sv.min() # sv.closed() def move_mid(): sv = Servo(18) sv.mid() sleep(0.2) led.off() # sv.min() # sv.closed() sensor.when_in_range = move_max sensor.when_out_of_range = move_mid pause()
from time import sleep from gpiozero import DistanceSensor dis = DistanceSensor(14, 15) #定义超声波的引脚 while True: print('', dis.distance, 'm') sleep(0.01) from gpiozero import DistanceSensor, LED from signal import pause sensor = DistanceSensor(14, 15, max_distance=1, threshold_distance=0.1) # 设置超声波引脚和检测最大距离、最小距离 led = LED(13) # 设置LED引脚 sensor.when_in_range = led.on # 当障碍物进入检测范围时,LED点亮 sensor.when_out_of_range = led.off # 当障碍物不在检测范围时,LED熄灭 #HC-SR04(PIN=4) #VCC-2 #TRIG-10 #ECHC-8 #GND-6
while True: print(ultrasonic.distance) while True: ultrasonic.wait_for_in_range() print("In range") ultrasonic.wait_for_out_of_range() print("Out of range") ultrasonic = DistanceSensor(echo=17, trigger=4, threshold_distance=0.5) ultrasonic.threshold_distance = 0.5 def hello(): print("Hello") ultrasonic.when_in_range = hello def bye(): print("Bye") ultrasonic.when_out_of_range = bye ultrasonic = DistanceSensor(echo=17, trigger=4, max_distance=2) ultrasonic.max_distance = 2
# critter detector - Interrupt solution from gpiozero import DistanceSensor, Button, LED from signal import pause dsense = DistanceSensor(echo=24, trigger=18) button = Button(16) theLED = LED(12) def IntruderAlert(device): if (type(device) == DistanceSensor): theLED.blink(on_time=.25, off_time=.75, n=10, background=True) print("Proximity: Intruder Alert!") else: print("Button: Intruder Alert!") theLED.blink(on_time=.75, off_time=.25, n=10, background=True) dsense.when_in_range = IntruderAlert button.when_pressed = IntruderAlert pause()
def mede(): lcd.clear() distancia = sensor.distance * 100 lcd.message("Distancia:" + "\n" + "%.1f" % (distancia) + "cm") dados = {"data/horario": datetime.now(), "distancia": distancia} colecao.insert(dados) # criação de componentes sensor = DistanceSensor(trigger=17, echo=18) led = LED(21) buzzer = Buzzer(16) botao = Button(11) botao2 = Button(12) lcd = Adafruit_CharLCD(2, 3, 4, 5, 6, 7, 16, 2) cliente = MongoClient("localhost", 27017) banco = cliente["teste_iniciais"] colecao = banco["teste_inicial"] sensor.max_distance = 1 sensor.threshold_distance = 0.1 botao.when_pressed = toca botao2.when_pressed = mede sensor.when_in_range = pisca sensor.when_out_of_range = pisca while True: sleep(0.5)
discoveryEnabler.start() ledsWhenNotConnected() connect() leftLDR = LightSensor(5, threshold=0.9) rightLDR = LightSensor(6, threshold=0.9) """ lightReporter = Thread(target=reportLight, args=(), daemon=True) lightReporter.start() distanceReporter = Thread(target=reportDistance, args=(), daemon=True) distanceReporter.start() """ leftLDR.when_light = stopFunction rightLDR.when_light = stopFunction distance = 0 # in cms distanceSensor = DistanceSensor(20, 21, threshold_distance=0.3) distanceSensor.when_in_range = stopFunction leftMotor = Motor(23, 24, 18, pwm=True) # In1 23-> pin16, In2 24->pin18, 18-> pin12 rightMotor = Motor(27, 22, 19, pwm=True) # 27-> pin13, 22-> pin15, 19-> pin35 buzzer = Buzzer(25) pause()
def Saiu(): intervalo = datetime.now() - tempo if (intervalo.seconds >= 10): SendText("Pessoa saiu") # criação de componentes tempo = datetime.now() sensor = DistanceSensor(trigger=17, echo=18) sensor.threshold_distance = 0.1 player = Player() aplicativo = None but1 = Button(11) but2 = Button(12) but3 = Button(13) led1 = LED(21) buz = Buzzer(16) but1.when_released = buttonReleased but1.when_pressed = buttonPressed but2.when_pressed = closeDoor but3.when_pressed = Gravacao but3.when_released = parar_gravacao sensor.when_in_range = Entrou sensor.when_out_of_range = Saiu lastUpdate = 0 # loop infinito while True: getMessage() sleep(1)
cl = 0.1 def inrange(): global cl robot.stop() robot.backward(curve_right=0.5) sleep(2) #robot.right() #robot.reverse() sleep(1) robot.forward(curve_right=cl) def outrange(): global cl robot.stop() robot.forward(curve_right=cl) sensor = DistanceSensor(echo=20, trigger=21, max_distance=1, threshold_distance=0.15) sensor.when_in_range = inrange sensor.when_out_of_range = outrange #robot = Robot(left=(26, 19), right=(6, 13)) robot = Robot(right=(19, 26), left=(6, 13)) robot.forward(curve_right=cl) pause()
''' ''' ### Turning an led on and off with an if-else statement ### while True: if button.is_pressed: led.off() else: led.on() ''' distanceMeters = DistanceSensor(trigger=18, echo=14, threshold_distance=0.15) # Initializes pins 8 and 11 as a DistanceSensor echo and trigger, respectively, with variable name "distanceMeters". Also sets threshold distance to 0.15m (~6in) while True: # Run the indented code forever distanceInches = distanceMeters.distance * 39.37 # Define variable "distanceInches" as distanceMeters times 39.37 distanceInches = round( distanceInches, 1 ) # Define new value of distanceInches as previous value of distanceInches rounded to one decimal place print('Distance: ', distanceInches, 'in') # Prints "Distance: XX.X in." distanceMeters.when_in_range = led.on # When distance sensed is less than threshold distance, turn on led distanceMeters.when_out_of_range = led.off # When distance sensed is greater than threshold distance, turn off led if distanceInches <= 3: # If distance is less than or equals to 3 inches, run the indented code below, otherwise skip to the indented code below else piezo.on() # Turn piezo on else: # If if statement is not satisfied, run the indented code below piezo.off() # Turn piezo off sleep( .1 ) # Waits 0.1 seconds before running next line of code, in this case back to initializing distanceInches
from gpiozero import DistanceSensor, LED from signal import pause red = LED(14) sensor = DistanceSensor(echo=24, trigger=23, max_distance=2, threshold_distance=0.6, queue_len=5) sensor.when_in_range = red.on sensor.when_out_of_range = red.off pause()
def tentativas (apt, name): if name == None: doc = {"apartamento":apt, "data":datetime.now()} else: doc = {"apartamento":apt, "data":datetime.now(), "nome": name} colecao02.insert(doc) return def listar_tentativas(): apt = coletar_digitos("Digite o apartamento") if validar_apartamento (apt): busca = {"apartamento":apt} orde = [["data", DESCENDING]] documentos = list(colecao02.find(busca,sort=orde)) for doc in documentos: if "nome" in doc: n = doc["nome"] else: n = "SENHA INCORRETA" date_time = doc["data"].strftime("%d/%m/%Y (%H:%M:%S): ") print(date_time + n +"\n") # criação de componentes # loop infinito sensor.when_in_range = principal B1.when_pressed = listar_tentativas