def GPIO_PULL_UPDW_TESTING(): checkPins = [] print('== Testing GPIO PULL_UP_DOWN ==') testPin = gpioUsedPins print("Check that nothing connects to those pins: %s" % (','.join([str(x) for x in testPin]))) GPIO.setmode(GPIO.BOARD) GPIO.setup(testPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) for pin in testPin: if (GPIO.input(pin) != InternalPullUpDnValue[PullUpDnPins[pin] if pin in PullUpDnPins else GPIO.PUD_UP]): checkPins.append(pin) GPIO.setup(testPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) for pin in testPin: if (GPIO.input(pin) != InternalPullUpDnValue[PullUpDnPins[pin] if pin in PullUpDnPins else GPIO.PUD_DOWN]): checkPins.append(pin) print("[%s] Pull Up and Down" % ('PASS' if len(checkPins) <= 0 else 'FAILED')) if (len(checkPins) > 0): print('Please check those pins: %s' % (','.join([str(x) for x in checkPins]))) GPIO.cleanup() print('===============================')
def GPIO_IO_TESTING(): print('== Testing GPIO INPUT/OUTPUT ==') for mode in ['phys', 'TB', 'BCM']: GPIO.setmode(modeMap[mode]) LPin = [pinTable[pins[0] - 1][mode] for pins in pairPins] RPin = [pinTable[pins[1] - 1][mode] for pins in pairPins] if (-1 in LPin or -1 in RPin): print('Some pins use the 3.3V or GND pin.') exit() for IPin, OPin in [(LPin, RPin), (RPin, LPin)]: GPIO.setup(IPin, GPIO.IN) GPIO.setup(OPin, GPIO.OUT) if (False in [GPIO.gpio_function(pin) == GPIO.IN for pin in IPin] or False in [GPIO.gpio_function(pin) == GPIO.OUT for pin in OPin]): print('Check GPIO.gpio_function or GPIO.setup.') exit() for volt in [GPIO.HIGH, GPIO.LOW]: GPIO.output(OPin, volt) OResult = [GPIO.input(pin) == volt for pin in OPin] IResult = [ GPIO.input(IPin[i]) == GPIO.input(OPin[i]) for i in range(len(IPin)) ] if (False in OResult): print('Check Pin[%d].' % (OPin[OResult.index(False)])) exit() if (False in IResult): print('Check Pin[%d].' % (IPin[IResult.index(False)])) exit() print("[PASS] GPIO.setmode(%s)" % (modeNameMap[mode])) GPIO.cleanup() print('===============================')
def attach_interrupts(self): if self.return_config_bool("pcb") and GPIO.input( self.check_pin ) == GPIO.LOW: # check if there is an pcb and if so attach the interrupts GPIO.add_event_detect(self.check_pin, GPIO.RISING, callback=self.pcb_interrupt ) # if not the interrupt gets attached if GPIO.input( self.power_pin ) == GPIO.HIGH: #when the system gets startet in the on position it gets shutdown print('shutting down') os.system("sudo shutdown -h now") else: self.led(1) GPIO.add_event_detect(self.reset_pin, GPIO.FALLING, callback=self.reset_interrupt) GPIO.add_event_detect(self.power_pin, GPIO.RISING, callback=self.power_interrupt) else: #no pcb attached so lets exit print('no PCB detected') GPIO.cleanup() exit()
def readLevel(): try: GPIO.setWarnings(False) GPIO.setmode(GPIO.BOARD) Trigger_AusgangsPin = 7 Echo_EingangsPin = 8 GPIO.setup(Trigger_AusgangsPin, GPIO.OUT) GPIO.setup(Echo_EingangsPin, GPIO.IN) GPIO.output(Trigger_AusgangsPin, False) AusschaltZeit = 0 GPIO.output(Trigger_AusgangsPin, True) time.sleep(0.00001) GPIO.output(Trigger_AusgangsPin, False) EinschaltZeit = time.time() while GPIO.input(Echo_EingangsPin) == 0: EinschaltZeit = time.time( ) # Es wird solange die aktuelle Zeit gespeichert, bis das Signal aktiviert wird while GPIO.input(Echo_EingangsPin) == 1: AusschaltZeit = time.time( ) # Es wird die letzte Zeit aufgenommen, wo noch das Signal aktiv war Dauer = AusschaltZeit - EinschaltZeit Abstand = (Dauer * 34300) / 2 return Abstand except: return 0
def pinSonar2(self, trig,echo): #print pin #print self.pinUse[pin] self.pinUse[trig] = self.PSONAR self.pinUse[echo] = self.PSONAR GPIO.setup(trig,GPIO.OUT) GPIO.setup(echo,GPIO.OUT) ti = time.time() # setup a list to hold 3 values and then do 3 distance calcs and store them #print 'sonar started' distlist = [0.0,0.0,0.0,0.0,0.0] ts=time.time() for k in range(5): #print "sonar pulse" , k GPIO.output(trig, 1) # Send Pulse high time.sleep(0.00001) # wait GPIO.output(trig, 0) # bring it back low - pulse over. t0=time.time() # remember current time GPIO.setup(echo,GPIO.IN) #PIN_USE[i] = PINPUT don't bother telling system t1=t0 # This while loop waits for input pin (7) to be low but with a 0.04sec timeout while ((GPIO.input(echo)==0) and ((t1-t0) < 0.02)): #time.sleep(0.00001) t1=time.time() t1=time.time() #print 'low' , (t1-t0).microseconds t2=t1 # This while loops waits for input pin to go high to indicate pulse detection # with 0.04 sec timeout while ((GPIO.input(echo)==1) and ((t2-t1) < 0.02)): #time.sleep(0.00001) t2=time.time() t2=time.time() #print 'high' , (t2-t1).microseconds t3=(t2-t1) # t2 contains time taken for pulse to return #print "total time " , t3 distance=t3*343/2*100 # calc distance in cm distlist[k]=distance #print distance GPIO.setup(echo,GPIO.OUT) tf = time.time() - ts distance = sorted(distlist)[1] # sort the list and pick middle value as best distance #print "total time " , tf #for k in range(5): #print distlist[k] #print "pulse time" , distance*58 #print "total time in microsecs" , (tf-ti).microseconds # only update Scratch values if distance is < 500cm if (distance > 280): distance = 299 if (distance < 2): distance = 1 return distance
def power_interrupt(self, channel): time.sleep(self.debounce_time) # debounce if GPIO.input(self.power_pin) == GPIO.HIGH and GPIO.input( self.check_pin ) == GPIO.LOW: # shutdown function if the powerswitch is toggled self.led(0) # led and fan off os.system("killall emulationstation") #end emulationstation self.blink(20, 0.1) #wait for the metadata to be safed self.fan(0) os.system("sudo shutdown -h now")
def SwitchInterrupt(switch): #rotary will make a noise at the end #SO it have to make a timer for bouncing global buttonStatus, start_time, end_time, rotary_mode if start_time == 0: start_time = time.time() while 1: if GPIO.input(switch) == 0: end_time = time.time() break else: start_time == 0 return buttonTime = end_time - start_time if 2 > buttonTime > 0.01: #for wrong interrupt rotary_mode += 1 if (rotary_mode > 4): rotary_mode = 0 packet = bytearray([0xFF, 0X55, 0x0, 0x7, 0x1, rotary_mode]) _LCD.write(packet) elif buttonTime >= 5: AudioOutputMute() packet = bytearray([0xFF, 0X55, 0x0, 0x0, 0x1, 0x0]) #LCD OFF _LCD.write(packet) print('power off!!') os.system("shutdown now -h") else: start_time = 0 return start_time = 0
def LeerSensor(self): try: if (GPIO.input(self.PirSensor)): return True else: return False except: return False
def pinRead(self, pin): #print "pin",pin ,"set to", self.pinUse[pin] #print pin ," being read" try: return GPIO.input(pin) except Exception,e: print "Some error reading pin" ,pin print str(e) return 0
def RotaryInterrupt(A_or_B): global rotary_counter, current_A, current_B, lockRotary switch_A = GPIO.input(encoder_a) switch_B = GPIO.input(encoder_b) if current_A == switch_A and current_B == switch_B: return current_A = switch_A current_B = switch_B if (switch_A and switch_B): lockRotary.acquire() if A_or_B == encoder_b: rotary_counter = 1 else: rotary_counter = -1 lockRotary.release() return
def sensorData(): readPin = 0 GPIO.setup(photoPin, GPIO.OUT) GPIO.output(photoPin, GPIO.LOW) time.sleep(0.1) GPIO.setup(photoPin, GPIO.IN) while (GPIO.input(photoPin) == GPIO.LOW): readPin += 1 return readPin
def reset_interrupt(self, channel): if GPIO.input(self.reset_pin) == GPIO.LOW: # reset function reset_counter = 0 # counter for the time funktion time.sleep(self.debounce_time) # debounce time while GPIO.input( self.reset_pin ) == GPIO.LOW: # while the button is hold the counter counts up reset_counter = reset_counter + 1 time.sleep(self.counter_time) if reset_counter > self.reset_hold_short: # check if its hold more that one second if reset_counter <= self.reset_hold_long: # if you hold it less than 5 sec it will toggle the fan self.change_config_value("fan") self.blink(3, 0.5) self.led(1) if reset_counter > self.reset_hold_long: # if you hold it more than 5 seconds if will toggle the bootupvideo self.change_config_value("video") self.blink(10, 0.5) self.led(1) else: os.system("killall emulationstation") self.blink(15, 0.1) os.system("sudo reboot")
def get_range(self): self._is_reading = True #---Call for a reading GPIO.output(self._gpio_trigger, GPIO.HIGH) time.sleep(0.00001) GPIO.output(self._gpio_trigger, GPIO.LOW) GPIO.output(self._gpio_trigger, GPIO.HIGH) time.sleep(0.00001) GPIO.output(self._gpio_trigger, GPIO.LOW) pulse_start_time = time.time() pulse_end_time = time.time() #--- Wait for the answer while GPIO.input(self._gpio_echo) == 0: pulse_start_time = time.time() time0 = time.time() while GPIO.input(self._gpio_echo) == 1: pulse_end_time = time.time() self._last_time_reading = time.time() self._is_reading = False pulse_duration = pulse_end_time - pulse_start_time distance = pulse_duration * self._speed_sound if distance > self._range_max: distance = self._range_max if distance < self._range_min: distance = self._range_min return (distance) @property def is_reading(self): return (self._is_reading)
def output(self): """Input button event""" try: if not GPIO.input(self.BTN_input) and not self.prev_input: print("click") self.prev_input = True return True # elif not GPIO.input(self.BTN_input) and self.prev_input: else: self.prev_input = False except KeyboardInterrupt: GPIO.cleanup() # Get a frame from the video source return False
def button_test(): print "Push button 10 times.\r\n" old_state = 0 current_state = 0 i = 0 while i < 10: current_state = GPIO.input(switch) if old_state == 0 and current_state == 1: GPIO.output(led, GPIO.HIGH) old_state = current_state elif old_state == 1 and current_state == 0: GPIO.output(led, GPIO.LOW) old_state = current_state i += 1 time.sleep(0.05)
def get_state(self): if gpio.input(self.state_pin) == self.state_pin_closed_value: return 'closed' elif self.last_action == 'open': if time.time() - self.last_action_time >= self.time_to_open: return 'open' else: return 'opening' elif self.last_action == 'close': if time.time() - self.last_action_time >= self.time_to_close: return 'open' # This state indicates a problem else: return 'closing' else: return 'open'
def pinRCTime (self,pin): reading = 0 #print "rc pin told to set to output" self.pinUpdate(pin,0) #print "rc changed to ouput" time.sleep(0.1) #print "sleep done" GPIO.setup(pin,GPIO.IN) #print "rc set to input" #time.sleep(3) #print "sleep 2 done" # This takes about 1 millisecond per loop cycle while (GPIO.input(pin) == GPIO.LOW) and (reading < 1000): reading += 1 #print "change back to output" GPIO.setup(pin,GPIO.OUT) self.pinUpdate(pin,0) return reading
time.sleep(0.5) def poweroff(): led_blink() os.system( "sudo killall emulationstation && sleep 5s && sudo shutdown -h now") def poweron(): ledon() try: while True: if GPIO.input(powerPin): poweron() else: poweroff() except KeyboardInterrupt: GPIO.cleanup() #power = LED(powerenPin) #power.on() #functions that handle button events def when_pressed(): led.blink(.2, .2) os.system( "sudo killall emulationstation && sleep 5s && sudo shutdown -h now")
def poweron(): ledon() def reboot(): output = int( subprocess.check_output(['/opt/RetroFlag/multi_switch.sh', '--es-pid'])) output_rc = int( subprocess.check_output(['/opt/RetroFlag/multi_switch.sh', '--rc-pid'])) if output_rc: os.system("/opt/RetroFlag/multi_switch.sh --closeemu") elif output: os.system("/opt/RetroFlag/multi_switch.sh --es-restart") else: os.system("sudo reboot") try: while True: time.sleep(0.1) if GPIO.input(resetPin) == GPIO.LOW: reboot() elif GPIO.input(powerPin): poweron() else: poweroff() except KeyboardInterrupt: GPIO.cleanup()
GPIO.setup(ledBlue, GPIO.OUT) GPIO.setup(pir, GPIO.IN) UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) UDPServerSocket.bind((localIP, localPort)) print("UDP server up and listening") while (True): message, address = UDPServerSocket.recvfrom(bufferSize) print(message.decode('utf-8')) if GPIO.input(pir) == GPIO.HIGH: data_e_hora_atuais = datetime.now() data_e_hora_em_texto = data_e_hora_atuais.strftime("%d/%m/%Y %H:%M") UDPServerSocket.sendto( str.encode('SENSOR ATIVADO! - ' + data_e_hora_em_texto), address) else: UDPServerSocket.sendto(str.encode(''), address) #if message.decode('utf-8') == 'play red': # GPIO.output(ledRed, 1) # time.sleep(0.5) # UDPServerSocket.sendto(str.encode('Red on!'), address) #elif message.decode('utf-8') == 'stop red': # GPIO.output(ledRed, 0) # UDPServerSocket.sendto(str.encode('Red off!'), address) #elif message.decode('utf-8') == 'play blue':
GPIO.output( IR_analog_warn, GPIO.LOW ) # Kızılötesi analog sensörlerin uyarı çıkışı LOW olarak tanımlandı try: port = serial.Serial( "/dev/ttyACM0", baudrate=9600, timeout=2 ) # Try except ile klavyede KeyboardInterrupt işlevi olana kadar kod çalışmaya devam eder port.flushInput( ) # Seri port tanımlandı bununla birlikte timeout ve baudrate değerleri atandı print "...starting..." # Başlatılıyor time.sleep(2) # 2 saniye bekle while True: # Program sonsuz döngüye girer # MZ80 sensörünün yaptığı ölçüm limit değerinin altında ise çıkış LOW olur if GPIO.input(mz80_1) and GPIO.input( mz80_2 ): # Her iki MZ80 sensörü çıkış veriyorsa problem yok ve Kızılötesi dijital sensörlerin uyarı çıkışı LOW olarak atanır print "...no problem..." GPIO.output(IR_digital_warn, GPIO.LOW) else: # Aksi halde Kızılötesi dijital sensörlerin uyarı çıkışı HIGH olarak atanır print "be careful" GPIO.output(IR_digital_warn, GPIO.HIGH) satir = port.readline( ) # satir değişkeni ile seri porttan gelen bilgi okunur satir = satir[:-2] # satir değişkenindeki \r\n ifadeleri temizlenir distance_IRsensor1, distance_IRsensor2, distance_ultrason = satir.split( "-" ) # satir değişkeni 3 farklı değişken bilgisi bulundurur (3-4-5) ve bu bilgiler değişkenlere atanır distance_IRsensor1 = float(
import ASUS.GPIO as GPIO import time GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) LED = 11 button = 13 GPIO.setup(LED, GPIO.OUT) GPIO.setup(button, GPIO.IN) try: while True: if GPIO.input(button) == False: GPIO.output(LED, True) print("pressed") time.sleep(.1) else: GPIO.output(LED, False) print("off") time.sleep(.1) except KeyboardInterrupt: GPIO.cleanup()
newkey = '' oldkey = '' mypipe = open('mypipe', 'w') mypipe.write('') mypipe.close() try: while (True): newkey = '' for j in range(4): GPIO.output(COL[j], 0) time.sleep(0.01) for i in range(4): if GPIO.input(ROW[i]): newkey = MATRIX[i][j] break GPIO.output(COL[j], 1) time.sleep(0.01) if (newkey == '' and oldkey != ''): mypipe = open('mypipe', 'a') print oldkey mypipe.write(str(oldkey) + "\n") mypipe.close() oldkey = newkey except KeyboardInterrupt:
MotionSensor = 257 TimeUntilDisplayOff = 10 # ****************************************** # GPIO.setwarnings(False) GPIO.setmode(GpioMode) GPIO.setup(MotionSensor, GPIO.IN) timer = TimeUntilDisplayOff call(['xhost', '+']) os.environ["DISPLAY"] = ":0.0" try: while True: if GPIO.input(MotionSensor): timer = TimeUntilDisplayOff print("Setting timer to " + str(timer) + "s.") if timer > 0: timer -= 1 print("Timer: " + str(timer) + "s") else: print("Timer is 0 -> turning display off.") call(['xrandr', '--output', 'HDMI-1', '--off']) GPIO.wait_for_edge(MotionSensor, GPIO.RISING) print("Motion detected -> turning display on") call(
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 22 09:51:47 2019 @author: daniel """ import ASUS.GPIO as GPIO import time GPIO.setwarnings(False) GPIO.setmode(GPIO.ASUS) PirSensor = 257 #TouchSensor = 256 GPIO.setup(PirSensor, GPIO.IN) try: while True: if (GPIO.input(PirSensor)): print("***** pir sensor activated *****") time.sleep(0.1) except KeyboardInterrupt: GPIO.cleanup()
def run(self, chat_id): while self._running: if GPIO.input(pir) == GPIO.HIGH: bot.sendMessage(chat_id, "Movimento detectado!!") time.sleep(2)
def run(self): self.dial_state = GPIO.input(self.DIAL_PIN) self.pulse_state = GPIO.input(self.PULSE_PIN) self.hook_state = GPIO.input(self.HOOK_PIN) self.dial_bounce = 0 self.pulse_bounce = 0 self.hook_bounce = 0 self.dialed_digit = 0 self.phone_number = "" self.call_timer = 0 self.first_digit = True if self.hook_state: print("ON HOOK") else: print("OFF HOOK") while not self.finish: try: if self.hook_bounce == 0: hook = GPIO.input(self.HOOK_PIN) if hook != self.hook_state: self.hook_state = hook self.hook_bounce = 5 if self.hook_state == 0: # off hook print("OFF HOOK") self.first_digit = True self.hs.off_hook() else: self.phone_number = "" # on hook self.dialed_digit = 0 print("ON HOOK") self.hs.on_hook() else: self.hook_bounce = self.hook_bounce - 1 if self.dial_bounce == 0: dial = GPIO.input(self.DIAL_PIN) if dial != self.dial_state: self.dial_state = dial self.dial_bounce = 5 if self.hook_state == 0: if self.dial_state == 0: # dial has just been activated self.dialed_digit = 0 if self.first_digit: self.first_digit = False self.hs.dial_began() else: # dialing digit complete print(self.dialed_digit) if self.dialed_digit == 10: self.phone_number = self.phone_number + str( 0) else: if (self.dialed_digit > 0) and (self.dialed_digit < 10): self.phone_number = self.phone_number + str( self.dialed_digit) self.call_timer = 300 else: self.dial_bounce = self.dial_bounce - 1 if self.pulse_bounce == 0: pulse = GPIO.input(self.PULSE_PIN) if pulse != self.pulse_state: self.pulse_state = pulse self.pulse_bounce = 3 if (self.pulse_state == 1) and (self.hook_state == 0) and (self.dial_state == 0): self.dialed_digit = self.dialed_digit + 1 else: self.pulse_bounce = self.pulse_bounce - 1 if self.call_timer > 0: self.call_timer = self.call_timer - 1 if self.call_timer == 0: if len(self.phone_number) > 0: print("dialing %s" % self.phone_number) self.hs.number_dialed( self.phone_number) # dial the number self.phone_number = "" time.sleep(0.01) except KeyboardInterrupt: self.stop() self.hs.stop() exit(0) except ValueError: print("Value Error") continue
def my_callback(channel): if GPIO.input(3): # if port 25 == 1 print "Rising edge detected on 25" else: # if port 25 != 1 print "Falling edge detected on 25"
import ASUS.GPIO as GPIO from time import sleep mz80 = 252 GPIO.setwarnings(False) GPIO.setmode(GPIO.ASUS) GPIO.setup(mz80,GPIO.IN) try: while True: if not GPIO.input(mz80): print "*** distance in ***" else: print "distance out" sleep(0.5) except KeyboardInterrupt: GPIO.cleanup() print "Good bye my love"
RED = 164 YELLOW = 166 GREEN = 167 PirSensor = 257 TouchSensor = 256 GPIO.setup(RED, GPIO.OUT) GPIO.setup(YELLOW, GPIO.OUT) GPIO.setup(GREEN, GPIO.OUT) GPIO.setup(PirSensor, GPIO.IN) GPIO.setup(TouchSensor, GPIO.IN) try: while True: if (GPIO.input(PirSensor)): GPIO.output(RED, GPIO.HIGH) GPIO.output(YELLOW, GPIO.HIGH) GPIO.output(GREEN, GPIO.HIGH) print "***** pir sensor activated *****" if (GPIO.input(TouchSensor)): GPIO.output(RED, GPIO.LOW) GPIO.output(YELLOW, GPIO.LOW) GPIO.output(GREEN, GPIO.LOW) print "+++++ touch sensor activated +++++" time.sleep(0.1) except KeyboardInterrupt: GPIO.cleanup()