def __iRDectector__(self): change_time = 0.0 read_value = False print("setting up pins") ir_light = LED(self.light) start_timer = time.perf_counter() ''' This that the time should be below 90.0 second or until the value does read as true it must be reaching the value ''' while (time.perf_counter() - start_timer) <= 90.0 or (read_value is True): finish_timer = time.perf_counter() print("Running with senors") #this is me setting up the ligth reflection with a certain threshold i_r_detection = LightSensor(self.reflection, threshold=.99) # this turn the light on for test reason ir_light.on() #this is a call to wait for light # this should allow for a better print out # it threshold is less then the intital call then it wouldn't detect if i_r_detection.wait_for_dark(): change_time = finish_timer - start_timer read_value = False #if the threshold is greater then the value it will return with a value of the changes elif i_r_dectection.wait_for_light(.001): change_time = finish_timer - start_timer read_value = True return abs(change_time)
class LDRSensor(Sensor): """docstring for LDRSensor""" def __init__(self, pin): super(LDRSensor, self).__init__(name='LDR') self.pin = pin self.ldr = LightSensor(self.pin) # alter if using a different pin self.ldr.wait_for_light(timeout=1) # wait one second def __read__(self): return self.ldr.value
def main(): ldr_pin = int(os.environ.get('LDR_PIN', '17')) sensor = LightSensor(ldr_pin, charge_time_limit=0.005, threshold=0.1) time.sleep(3) # wait a bit for setup (initial capacitor charge) while True: sensor.wait_for_dark() alert() # Wait 5 seconds so as to not send a burst of alerts time.sleep(5)
def __init__(self, start_pin, finish_pin): self.start_sensor = LightSensor( start_pin, threshold=THRESHOLD, charge_time_limit=CHARGE_TIME_LIMIT, queue_len=QUEUE_LEN, ) self.finish_sensor = LightSensor( finish_pin, threshold=THRESHOLD, charge_time_limit=CHARGE_TIME_LIMIT, queue_len=QUEUE_LEN, )
def restart(): r = sr.Recognizer() ldr = LightSensor(4) rl.rele1_off() ml.rele2_off() with sr.Microphone() as source: while True: try: r.adjust_for_ambient_noise(source, duration=0.5)#Tova e za namalqvane na vremeto za slushane audio = r.listen(source) print("I'm listening") #Ako gornoto ne raboti pravilno tova shte e hint za koga usera da govori text = r.recognize_google(audio) print(text) if("coffee" in text): print("ok") rl.rele1_on() print(ldr.value) while ldr.value < 1: #vinagi e po malko ot 1 toest vinagi proverqva dali sveti lampata if (ldr.value >0.80): #ako se e nagrqla chisloto e stoinostta na fotorezistora ml.rele2_on() #puskame pompata time.sleep(10) #deset sekundi kysoto kafe?! ml.rele2_off() #spirame pompata da ne se oleesh restart1() else: print("Unknow Command") #ako neshto zburkash nali si ebe maikata :) restart1() except:
def main(): import speech_recognition as sr #importvame googleskata biblioteka import relay as rl #importvame koda za nagrevatelq import time import pompatarele as ml #importvame koda za pompata from gpiozero import LightSensor, Buzzer #a tuk importvame scripta koito ni raboti s fotorezistora r = sr.Recognizer() ldr = LightSensor(4) rl.rele1_on() ml.rele2_off() with sr.Microphone() as source: while True: try: r.adjust_for_ambient_noise(source) audio = r.listen(source) text = r.recognize_google(audio) #text = int(input()) print(text) if("coffee" in text): #if(text == 5): print("ok") rl.rele1_off() print(ldr.value) while ldr.value < 2: #vinagi e po malko ot 1 toest vinagi proverqva dali sveti lampata if (ldr.value >0.80): #ako se e nagrqla chisloto e stoinostta na fotorezistora ml.rele2_on() #puskame pompata time.sleep(10) #deset sekundi kysoto kafe?! ml.rele2_off() #spirame pompata da ne se oleesh rl.rele1_on() #spirame nagrevatelq da ne se podpalish else: print("Unknow Command") #ako neshto zburkash nali si ebe maikata :) except: print("Unknow Command") #tva ne znam zashto e
def get_light_status(): """ Safely read the available light and calculate a status - daytime/dusk/nighttime/unknown :return: String - light status """ app.logger.info("Starting to read available light") status = -1 try: sensor = LightSensor(pin=15) status = float(sensor.value) except exc.BadPinFactory as e: app.logger.warning( f"Unable to use light sensor in this environment: {e}") except Exception as e: app.logger.error(f"Unknown problem with light sensor: {e}") if status == -1: result = "Unknown" elif status >= 0.5: result = "Daytime" else: result = "Nighttime" app.logger.debug(f"Light: {status} - {result}") app.logger.info("Finished reading available light") return result
def main(): brightness = 0 last_time = None show_colon = False ldr = LightSensor(LDR_PIN) if "flip" in sys.argv: sphd.rotate(180) while True: now = datetime.now() current_time = (now.hour, now.minute) old_brightness = brightness brightness = MAX_BRIGHTNESS if ldr.light_detected else 0.1 if current_time != last_time or brightness != old_brightness: sphd.clear() draw_digit(0, 0, now.hour // 10, brightness) draw_digit(4, 0, now.hour % 10, brightness) draw_digit(10, 0, now.minute // 10, brightness) draw_digit(14, 0, now.minute % 10, brightness) last_time = current_time if show_colon != (now.microsecond < 500000) or brightness != old_brightness: show_colon = now.microsecond < 500000 sphd.set_pixel(8, 1, brightness * show_colon) sphd.set_pixel(8, 5, brightness * show_colon) sphd.show() time.sleep(0.01)
def check_ldr(global_namespace): try: from gpiozero import LightSensor except ImportError: print("Failed to import gpiozero") try: ldr = LightSensor(LDR_PIN) intersection = False intersection_previous = intersection while True: intersection = ldr.value < LIGHT_THRESHOLD if intersection and not intersection_previous: # If the beam has just been broken global_namespace.number_of_people = max( 0, global_namespace.number_of_people + global_namespace.increment) if global_namespace.number_of_people >= global_namespace.maximum_capacity and global_namespace.increment == 1: os.system(SOUND_COMMAND_NOTIFY) else: os.system(SOUND_COMMAND_REGISTER) intersection_previous = intersection time.sleep(0.01) except: print("Lightsensor fail")
def __init__(self, pins, client): self._min_value = 0 self._max_value = 100 self._light_sensors = [LightSensor(int(pin)) for pin in pins] self._threshold = 50 #default self._client = client
def ldr(): print("LDR running") LDR_DATA_PIN = 22 ldr = LightSensor(LDR_DATA_PIN) while settings.LIGHT_AUTOMATION_OFF: intensity = ldr.value print("ldr : " + str(intensity)) if intensity == 0.0: #global LIGHT_FREQ settings.LIGHT_FREQ_TRUE = 0.001 settings.LIGHT_FREQ_FALSE = 0.001 else: #global LIGHT_FREQ settings.LIGHT_FREQ_TRUE = 0.5 settings.LIGHT_FREQ_FALSE = 0.5 #elif intensity > 30 and intensity < 60: #global LIGHT_FREQ #settings.LIGHT_FREQ = 0.2 #elif intensity > 60: #global LIGHT_FREQ #settings.LIGHT_FREQ = 0.5 time.sleep(0.5) print "--------------LIGHTS AUTOMATION IS OFF-------------" print "true : ", settings.LIGHT_FREQ_TRUE print "false: ", settings.LIGHT_FREQ_FALSE settings.LIGHT_FREQ_TRUE = settings.MIN settings.LIGHT_FREQ_FALSE = settings.MAX
def txt_a_change(): lbl_c_state.config(text="AUTO") btn_LED1_on.config(state="disable") btn_LED1_off.config(state="disable") btn_LED2_on.config(state="disable") btn_LED2_off.config(state="disable") btn_LED3_on.config(state="disable") btn_LED3_off.config(state="disable") ldr= LightSensor(7) i=50000 while i>=0 : if(ldr.value<0.5444): led1.on() led2.on() led3.on() else: led1.off() led2.off() led3.off() #break print(ldr.value) i -=1 LED1_Off() LED2_Off() LED3_Off()
def initialize_sensors(specification): sensors = dict() for k, v in specification.items(): print(f'Creating sensor "{k}" = GPIO({v})') sensor = LightSensor(v) print(f'Initial value: {sensor.value}') sensors[k] = sensor return sensors
def automatico(): ldr = LightSensor(17) # Sensor de luz en pin 17 del raspberry pir = MotionSensor(4) # Sensor de movimiento en el pin 4 if pir.motion_detected: # Si hay movimiento movimiento = "Si" if (int(ldr.value * 100) >= 0) and (int(ldr.value * 100) <= 60): # Poca luz, se encienden los dos focos GPIO.output(23, GPIO.HIGH) GPIO.output(24, GPIO.HIGH) print(int(ldr.value * 100)) foco1 = "Encendido" foco2 = "Encendido" luz = "Poca o nada" elif (int(ldr.value * 100) > 60) and (int( ldr.value * 100) <= 70): # Media luz, se enciende solo un foco GPIO.output(23, GPIO.HIGH) GPIO.output(24, GPIO.LOW) print(int(ldr.value * 100)) foco1 = "Encendido" foco2 = "Apagado" luz = "Media" elif (int(ldr.value * 100) > 70): # Mucha luz, se apagan los dos focos GPIO.output(23, GPIO.LOW) GPIO.output(24, GPIO.LOW) print(int(ldr.value * 100)) foco1 = "Apagado" foco2 = "Apagado" luz = "Bastante" else: #si no hay movimiento se apagan los dos focos movimiento = "No" GPIO.output(23, GPIO.LOW) GPIO.output(24, GPIO.LOW) foco1 = "Apagado" foco2 = "Apagado" if (int(ldr.value * 100) >= 0) and (int(ldr.value * 100) <= 60): print(int(ldr.value * 100)) luz = "Poca o nada" elif (int(ldr.value * 100) > 60) and (int(ldr.value * 100) <= 70): print(int(ldr.value * 100)) luz = "Media" elif (int(ldr.value * 100) > 70): print(int(ldr.value * 100)) luz = "Bastante" return json.dumps({ 'status': 'OK-automatico', 'luz': luz, '1': foco1, '2': foco2, 'mov': movimiento }) # Se envia respuesta a archivo script.js
def main(): print("It begins") if socket.gethostname() == 'Scanner2': print("Behold, I am scanner 2 and in charge of the Callback") os.system("python3 /home/pi/heart-of-maker-faire/ScanPi/macMQTT.py &") else: print("Behold, I am scanner 1 and not in charge of anything") ldr = LightSensor(23, charge_time_limit=0.2, threshold = 0.1) # LDR sensor last_time_checked = int(round(time.time()*1000)) # record the start time frame = 0 # set the initial frame to zero for the blinky lights unique = False # set the QR repetition bool to False while True: ringSelect(strip, 'green', 1, False) last_time_checked, frame = pulselight(strip, last_time_checked, frame, 60) # get the current pulse frame #print(ldr.value) if (ldr.value > 0.9) or button.is_pressed: # a heart has been placed on the scanner short = shortButton.is_pressed print("Heart detected") ringSelect(strip, 'cyan', 1, True) time.sleep(2) # positioning delay scannedQR = QRread() # read the QR on the heart if scannedQR == False: # if zbar can't read the QR code for i in range(6): ringSelect(strip, 'red', 1, True) time.sleep(0.5) ringSelect(strip, 'blank', 1, True) time.sleep(0.5) continue unique = QR_usage_checker(conn, scannedQR) # check for an already used QR if unique == True: cell_num = unique_cell_picker(conn, short) # choose a unique cell if cell_num == False: continue update_heart(conn, cell_num, scannedQR, 0) # bagsey the cell from the database else: cell_num = unique status = watch_colour_picker(conn, cell_num) if status == False: # what if we've run out of indication colours error('Wait') continue MQTTsend(cell_num, status, 0) ringSelect(strip, status, 2, True) heartrate = encoder(status,cell_num) if heartrate == False: error('Reset') continue update_heart(conn, cell_num, scannedQR, heartrate) average = getAverage(conn) MQTTsend(cell_num, status, heartrate) sendAverage(average) HRprinter(scannedQR, heartrate, status) countdown()
def run(): global R global G global B led = RGBLED(4, 17, 27) ldr = LightSensor(22, 50) R = (1, 0, 0) G = (0, 1, 0) B = (0, 0, 1) N = (0, 0, 0) Y = (1, 1, 0) # W = (1,1,1) # M = (1,0,1) night_time on_time = 0.01 on_time_noacft = 0.20 server_address = ('localhost', 30003) BUFF_LEN = 256 connCnt = 0 x = threading.Thread(target=thread_function, args=(1, ldr)) x.start() # INIT LED - Blink BLUE while not connected & data led.blink(0.25, 0.25, 0, 0, B, N) connect(server_address, ldr) try: while (1): data = sock.recv(BUFF_LEN) if (len(data) > 10): led.blink(on_time, 0, 0, 0, G, N, 1) else: led.blink(on_time, 0, 0, 0, R, N, 1) if not data: led.color = R connCnt = connCnt + 1 if (connCnt > 10): l('Error. Try to reconnect .... ') close() # No blink thread = block script for 20sec = time to SDR recovery led.blink(1, 1, 0, 0, Y, N, 10, False) led.blink(0.25, 0.25, 0, 0, B, N) connect(server_address, ldr) else: connCnt = 0 finally: led.color = N close()
def send_to_AWS(): # Publish sensor data values in a loop forever from gpiozero import LightSensor ldr = LightSensor(4) loopcount = 0 while True: ldr_d = ldr.value temperature = getTemperature() msg = '"LDR_value":"{}","Temperature":"{}"'.format(ldr_d,temperature) msg = '{'+msg+'}' myAWSIoTMQTTClient.publish(topic,msg,1) time.sleep(20)
def record_loop(loop_on): ldr = LightSensor(21) pir = MotionSensor(20) while True: if loop_on.value == True: print("Running") try: if pir.motion_detected: On() except: print("Your program is shit get a f*****g degree!") print(pir.motion_detected)
def main(): global l_verbosemode parser = argparse.ArgumentParser(description='Power and temp monitor.') parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true") parser.add_argument("-p", "--purge", help="purge file and database", action="store_true") args = parser.parse_args() if (args.purge): do_purge() l_verbosemode = args.verbose ldr_1 = LightSensor(l_gpio_ldr_1) ldr_2 = LightSensor(l_gpio_ldr_2) ldr_1.when_light = light_pulse_seen_1 ldr_2.when_light = light_pulse_seen_2 handle_time_event() schedule.every(l_poll_minutes).minutes.do(handle_time_event) while True: schedule.run_pending() time.sleep(1)
def main(): # now just write the code you would use in a real Raspberry Pi from Adafruit_CharLCD import Adafruit_CharLCD from gpiozero import Buzzer, LED, PWMLED, Button, DistanceSensor, LightSensor, MotionSensor from lirc import init, nextcode from py_irsend.irsend import send_once from time import sleep def show_sensor_values(): lcd.clear() lcd.message( "Distance: %.2fm\nLight: %d%%" % (distance_sensor.distance, light_sensor.value * 100) ) def send_infrared(): send_once("TV", ["KEY_4", "KEY_2", "KEY_OK"]) lcd = Adafruit_CharLCD(2, 3, 4, 5, 6, 7, 16, 2) buzzer = Buzzer(16) led1 = LED(21) led2 = LED(22) led3 = LED(23) led4 = LED(24) led5 = PWMLED(25) led5.pulse() button1 = Button(11) button2 = Button(12) button3 = Button(13) button4 = Button(14) button1.when_pressed = led1.toggle button2.when_pressed = buzzer.on button2.when_released = buzzer.off button3.when_pressed = show_sensor_values button4.when_pressed = send_infrared distance_sensor = DistanceSensor(trigger=17, echo=18) light_sensor = LightSensor(8) motion_sensor = MotionSensor(27) motion_sensor.when_motion = led2.on motion_sensor.when_no_motion = led2.off init("default") while True: code = nextcode() if code != []: key = code[0] lcd.clear() lcd.message(key + "\nwas pressed!") sleep(0.2)
def __init__(self): self.door_open_button = Button(DOOR_OPEN_PIN) self.door_closed_button = Button(DOOR_CLOSED_PIN) self.relay = gpiozero.OutputDevice(RELAY_PIN, active_high=False, initial_value=False) self.wall_switch = Button(WALL_SWITCH_PIN) self.thread = threading.Thread(target=self.wall_input).start() self.lock = threading.Lock() self.ldr = LightSensor(LIGHTSENSOR_PIN) print('Controller class intialized:' + time.strftime('%I:%M:%S %p %A, %B %d')) print('1light detected:' + str(self.ldr.light_detected))
def light_sensor_control(self): result = 0 critical_value = 0.1 LDR = LightSensor(self.LDR_pin) #while True: # print(LDR.value) # time.sleep(1) if LDR.value <= critical_value: result = 1 elif LDR.value > critical_value: result = 0 return result
def start(): ''' initiate the receiver ''' sensor = LightSensor(config.RECEIVER_PIN) chars = [] received = "" running = True ''' Loop until detected laser (syncing) ''' while True: if int(sensor.light_detected): break while running: # lets get the message bit = int(sensor.light_detected) received += str(bit) if len(received) >= 8: # end if received == config.START_END and len(chars) != 0: print('[Receiver] stopped recording') running = False # start elif received == config.START_END: print('[Receiver] recording...') received = "" # append else: chars.append(received) received = "" sleep(config.SEND_RATE) # message received, process it msg = "" for c in chars: try: msg += text_from_bits(c) except Exception: msg += ' unknown ' print(msg) print(chars)
def add_component(comp_id, data): ports = data['ports'] if data['component'] == 'led': components[comp_id] = (LED(int(ports[0])), data['component']) elif data['component'] == 'motor': components[comp_id] = (Motor(int(ports[0]), int(ports[1])), data['component']) elif data['component'] == 'distance_sensor': components[comp_id] = (DistanceSensor(trigger=int(ports[0]), echo=int(ports[1])), data['component']) elif data['component'] == 'motion_sensor': components[comp_id] = (MotionSensor(int(ports[0])), data['component']) elif data['component'] == 'light_sensor': components[comp_id] = (LightSensor(int(ports[0])), data['component']) for port in ports: ports_used.add(port) return
def setup(): GPIO.setmode(GPIO.BCM) GPIO.setup(TIMER_BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(NAME_ENTRY_BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(BUZZER_PIN, GPIO.OUT) GPIO.add_event_detect(TIMER_BUTTON_PIN, GPIO.BOTH, callback=timer_button_press_loop, bouncetime=250) GPIO.add_event_detect(NAME_ENTRY_BUTTON_PIN, GPIO.FALLING, callback=name_entry_press_loop, bouncetime=250) light_sensors = [LightSensor(pin) for pin in LDR_PINS] return light_sensors
def backyard_light(light_gpio, motion_gpio, relay_gpio, timing, sense_time=2): ls = LightSensor(light_gpio, threshold=0.2) ms = MotionSensor(motion_gpio, threshold=0.4) light = OutputDevice(relay_gpio) while True: if not ls.light_detected: if ms.motion_detected: x = time.time() while time.time() - x < sense_time: if not ms.motion_detected: break else: while ms.motion_detected: light.on() else: light.off() else: light.off() else: light.off()
def __init__(self, pin_dht=18, pin_light=24, pin_pir=23, pin_pir_led=25): self.pin_dht = pin_dht self.pin_light = pin_light self.pin_pir = pin_pir self.pin_pir_led = pin_pir_led # Initialize Temperature and Humidity Sensor self.sensor_dht = Adafruit_DHT.DHT22 # Initialize and Calibrate Gas Sensor 1x self.mq = MQ() # Initialize Light Sensor self.ls = LightSensor(self.pin_light) # Initialize PIR Sensor self.pir = MotionSensor(self.pin_pir) self.led = LED(self.pin_pir_led) self.logger = logging.getLogger(__name__) logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
def sample(): #flg=True lbl_c_state.config(text="AUTO") btn_LED1_on.config(state="disable") btn_LED1_off.config(state="disable") btn_LED2_on.config(state="disable") btn_LED2_off.config(state="disable") btn_LED3_on.config(state="disable") btn_LED3_off.config(state="disable") ldr= LightSensor(7) if(ldr.value<0.5444)and(flg): led1.on() led2.on() led3.on() else: led1.off() led2.off() led3.off() #break print(ldr.value) root.after(500, sample)
def run_ss_sound(pin, pathout, dt_file, endtime, dt_sample=0.1, display=False, analog=True): if analog: ss = MCP3008(pin) else: ss = LightSensor(pin) while datetime.now() < endtime: t0, fid, pout, fout = create_datafile(pathout, node + '_sound', display=display) fid.write('time,sound\n') while (datetime.now() - t0).seconds < dt_file: strout = datetime.now().strftime('%Y-%m-%d_%H:%M:%S') + ',' + str( round(ss.value, 2)) fid.write(strout + '\n') sleep(dt_sample) fid.close() os.system('mv -f ./tmp/' + fout + ' ' + pout) return
# Displays It's Light or Dark from gpiozero import LightSensor sensor = LightSensor(18) while True: sensor.wait_for_light() print("It's light...") sensor.wait_for_dark() print("It's dark...")
from gpiozero import LightSensor, LED from time import sleep light = LightSensor(4, charge_time_limit=0.001) buzzer = LED(26) buzzer.off() sleep(1) light.wait_for_dark() buzzer.on()
tcpSerSock = socket(AF_INET, SOCK_STREAM) tcpSerSock.bind(ADDR) tcpSerSock.listen(5) flag = 1 flag1 = 1 flag2 = 1 flag3 = 1 flag4 = 1 flag5 = 1 flag6 = 1 data = '' ttt = 0 ttt1 = 0 ttt2 = 0 a = Motor(20, 21) ldr = LightSensor(26) while True: flag1, flag2, flag3, flag4, flag5, flag6 = 1, 1, 1, 1, 1, 1 ttt = 0 print("Waiting for connection") tcpCliSock, addr = tcpSerSock.accept() print("...connected from : ", addr) try: while True: data = tcpCliSock.recv(BUFSIZE) #print(data) #print(type(data)) data = data.decode("utf-8") if data == ccmd[0]: print('PIR')
# Turn On the light when it's become dark. from gpiozero import LightSensor, LED sensor = LightSensor(18) led = LED(16) sensor.when_dark = led.on sensor.when_light = led.off