我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用RPi.GPIO.input()。
def __GPIOInit(self): """ Initialises the GPIO pins for the pi (tested on the Pi3 Model B+) """ # Set mode PIN numbering to BCM, and define GPIO pin functions GPIO.setmode(GPIO.BCM) # Setup Function for input Pins inputBNTs = (self.__soundBNTs + self.__stepBNTs) inputBNTs.append(self.__playBNT) inputBNTs.append(self.__recBNT) for b in inputBNTs: GPIO.setup(b, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Func for ouput Pins GPIO.setup(self.__LED, GPIO.OUT)
def send_gpio_order(param): """ GPIO???? type in(GPIO.IN) out(GPIO.OUT) value 1 GPIO.HIGH 0 GPIO.LOW :param param: :return: """ print param channel, type, value = param try: import RPi.GPIO as GPIO except RuntimeError: print("????") GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) if type == 'in': GPIO.setup(channel, GPIO.IN) GPIO.input(channel, value) else: GPIO.setup(channel, GPIO.OUT) GPIO.output(channel, value)
def start(): last = GPIO.input(button) while True: val = GPIO.input(button) GPIO.wait_for_edge(button, GPIO.FALLING) # we wait for the button to be pressed GPIO.output(lights[1], GPIO.HIGH) inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device) inp.setchannels(1) inp.setrate(16000) inp.setformat(alsaaudio.PCM_FORMAT_S16_LE) inp.setperiodsize(500) audio = "" while(GPIO.input(button)==0): # we keep recording while the button is pressed l, data = inp.read() if l: audio += data rf = open(path+'recording.wav', 'w') rf.write(audio) rf.close() inp = None alexa()
def ReadAck(self): GPIO.setup(self.SDA, GPIO.IN) readbuffer =0 for i in range(8): GPIO.output(self.SCL, GPIO.HIGH) self.tick(2) readbuffer |= (GPIO.input(self.SDA)<< 7) >> i GPIO.output(self.SCL, GPIO.LOW) self.tick(2) GPIO.setup(self.SDA, GPIO.OUT) GPIO.output(self.SDA, GPIO.LOW) GPIO.output(self.SCL, GPIO.HIGH) self.tick(2) GPIO.output(self.SCL, GPIO.LOW) GPIO.output(self.SDA, GPIO.LOW) self.tick(2) return readbuffer
def ReadNack(self): GPIO.setup(self.SDA, GPIO.IN) readbuffer =0 for i in range(8): GPIO.output(self.SCL, GPIO.HIGH) self.tick(2) readbuffer |= (GPIO.input(self.SDA)<< 7) >> i GPIO.output(self.SCL, GPIO.LOW) self.tick(2) GPIO.setup(self.SDA, GPIO.OUT) GPIO.output(self.SDA, GPIO.HIGH) GPIO.output(self.SCL, GPIO.HIGH) self.tick(2) GPIO.output(self.SCL, GPIO.LOW) GPIO.output(self.SDA, GPIO.LOW) self.tick(2) return readbuffer
def signalDoorBell(): global doorBell global belli global bellSum global previousDoorBell global GPIO_doorBell global GPIO_bell if belli != 15: GPIO.setmode(GPIO.BOARD) GPIO.setup(GPIO_doorBell, GPIO.IN) bellSum = bellSum + GPIO.input(GPIO_doorBell) belli += 1 else: belli = 0 if bellSum >= 15: doorBell = 1 else: doorBell = 0 if doorBell != previousDoorBell: previousDoorBell = doorBell DeviceControl.doorBell(doorBell) print("Dang qian doorBell %s" % doorBell) bellSum = 0
def signalshock(): global shocki global shockSum global shock global GPIO_shock if shocki != 5: GPIO.setmode(GPIO.BOARD) GPIO.setup(GPIO_shock, GPIO.IN) shockSum = shockSum+GPIO.input(GPIO_shock) shocki += 1 else: shocki = 0 if shockSum >=2: shock = 1 else: shock = 0 global previousShock if shock != previousShock: previousShock = shock print("Dang qian shock %s" % shock) shockSum = 0
def signaliR(): global iRi global iRSum global iR global GPIO_iR if iRi != 5: GPIO.setmode(GPIO.BOARD) GPIO.setup(GPIO_iR, GPIO.IN) iRSum = iRSum+GPIO.input(GPIO_iR) iRi += 1 else: iRi = 0 if iRSum >= 2: iR = 1 else: iR = 0 global previousIR if iR != previousIR: previousIR = iR print("Dang qian IR %s"%iR) iRSum = 0 IRStateMachine.stateJudge(iR) # ??????
def checkbutton(self): """ debounced button :return: """ ret = 0 ts = time.time() if ts - self._last_check <= 0.05: ret = 0 else: state = GPIO.input(self._button) # Read button state if (not self._last_state) and state: print("got it") ret = 1 self._last_state = state self._last_check = time.time() return ret
def record(): """ Record voice """ inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, DEVICE) inp.setchannels(1) inp.setrate(16000) inp.setformat(alsaaudio.PCM_FORMAT_S16_LE) inp.setperiodsize(500) audio = "" # we keep recording while the button is pressed while GPIO.input(BUTTON) == 0: valid, data = inp.read() if valid: audio += data save_audio = open(AUDIBLE_PATH + RecordVoice.RECORD_FILE, 'w') save_audio.write(audio) save_audio.close()
def cameraSettings() : global cam global camset cp = "Camera> " camMode = True while camMode : key = input(cp + "Enter command, H lists camera commands") if key.upper() == "H" : print ("A toset Auto White Balance mode, currently at : " + str(cam.awb_mode)) print(" B to set brightness, currently at: " + str(cam.brightness)) print(" C to set contrast,currently at: " + str(cam.contrast)) print(" E to set effects, currently at: " + str(cam.image_effect)) print(" X to set exposure, ") print(" T to Take test image ") print(" Q to quit back to main mode ") elif key.upper() == "E" : print(" Available image effects are:"+str(cam.IMAGE_EFFECTS)) elif key.upper() =="Q" : camMode = False
def loop(): """ The main loop in which we mow the lawn. """ print 'GPIO daemon started' while True: for PIN in PINS: index = [y[0] for y in PINS].index(PIN[0]) pin = PINS[index][0] oldstate = PINS[index][1] newstate = GPIO.input(pin) if newstate != oldstate: mqttc.publish(MQTT_TOPIC_OUT % pin, payload=newstate, qos=MQTT_QOS, retain=MQTT_RETAIN) PINS[index][1] = newstate time.sleep(.8) # Use the signal module to handle signals
def read(self): '''Reads 32 bits of the SPI bus & stores as an integer in self.data.''' bytesin = 0 # Select the chip GPIO.output(self.cs_pin, GPIO.LOW) # Read in 32 bits for i in range(32): GPIO.output(self.clock_pin, GPIO.LOW) bytesin = bytesin << 1 if (GPIO.input(self.data_pin)): bytesin = bytesin | 1 GPIO.output(self.clock_pin, GPIO.HIGH) # Unselect the chip GPIO.output(self.cs_pin, GPIO.HIGH) # Save data self.data = bytesin
def read(self): '''Reads 16 bits of the SPI bus & stores as an integer in self.data.''' bytesin = 0 # Select the chip GPIO.output(self.cs_pin, GPIO.LOW) # Read in 16 bits for i in range(16): GPIO.output(self.clock_pin, GPIO.LOW) time.sleep(0.001) bytesin = bytesin << 1 if (GPIO.input(self.data_pin)): bytesin = bytesin | 1 GPIO.output(self.clock_pin, GPIO.HIGH) time.sleep(0.001) # Unselect the chip GPIO.output(self.cs_pin, GPIO.HIGH) # Save data self.data = bytesin
def wait_pir(DEBUG=False): """ Loops till PIR doesn't detect something""" # setting GPIO PINs with open(SETTINGS) as file: settings = json.load(file) logging.info('Setting GPIO PINS') GPIO.setmode(GPIO.BOARD) GPIO.setup(settings['pir_pin_board'], GPIO.IN) ##################### # PIR cycle logging.info('Starting PIR waiting cycle...') if DEBUG: while input('insert 1 to start...') != '1': time.sleep(0.1) else: while GPIO.input(settings['pir_pin_board']) is not 1: time.sleep(0.1) logging.info('PIR detection') return
def switch_kalliope_mute_led(self, event): """ Switch the state of the MUTE LED :param event: not used """ logger.debug("[RpiUtils] Event button caught. Switching mute led") # get led status led_mute_kalliope = GPIO.input(self.rpi_settings.pin_led_muted) # switch state if led_mute_kalliope == GPIO.HIGH: logger.debug("[RpiUtils] Switching pin_led_muted to OFF") self.switch_pin_to_off(self.rpi_settings.pin_led_muted) self.callback(muted=False) else: logger.debug("[RpiUtils] Switching pin_led_muted to ON") self.switch_pin_to_on(self.rpi_settings.pin_led_muted) self.callback(muted=True)
def init_gpio(self, rpi_settings): """ Initialize GPIO pin to a default value. Leds are off by default Mute button is set as an input :param rpi_settings: RpiSettings object """ # All led are off by default if self.rpi_settings.pin_led_muted: GPIO.setup(rpi_settings.pin_led_muted, GPIO.OUT, initial=GPIO.LOW) if self.rpi_settings.pin_led_started: GPIO.setup(rpi_settings.pin_led_started, GPIO.OUT, initial=GPIO.LOW) if self.rpi_settings.pin_led_listening: GPIO.setup(rpi_settings.pin_led_listening, GPIO.OUT, initial=GPIO.LOW) if self.rpi_settings.pin_led_talking: GPIO.setup(rpi_settings.pin_led_talking, GPIO.OUT, initial=GPIO.LOW) # MUTE button if self.rpi_settings.pin_mute_button: GPIO.setup(rpi_settings.pin_mute_button, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(rpi_settings.pin_mute_button, GPIO.FALLING, callback=self.switch_kalliope_mute_led, bouncetime=500)
def _r_byte(self): """ Read byte from the chip. :return: byte value :rtype: int """ # data pin is now input (pull-down resistor embedded in chip) GPIO.setup(self._data_pin, GPIO.IN) # clock the byte from chip byte = 0 for i in range(8): # make a high pulse on CLK pin GPIO.output(self._clk_pin, GPIO.HIGH) time.sleep(self.CLK_DELAY) GPIO.output(self._clk_pin, GPIO.LOW) time.sleep(self.CLK_DELAY) # chip out data on clk falling edge: store current bit into byte bit = GPIO.input(self._data_pin) byte |= ((2 ** i) * bit) # return byte value return byte
def stopwatch(hexUID, name): start = time.time() time.clock() elapsed = 0 while elapsed < maxRaceTime and GPIO.input(laserPin) != GPIO.LOW: elapsed = time.time() - start millis = int(round(elapsed * 1000)) hours, millis = divmod(millis, 3600000) minutes, millis = divmod(millis, 60000) seconds, millis = divmod(millis, 1000) s = "%02i:%02i:%03i" % (minutes, seconds, millis) with canvas(disp) as draw: draw.text((0, 0), "Timer:", font=defaultFont, fill=255) draw.text((0, 20), s, font=timerFont, fill=255) color(100, 0, 0, 0) publishRaceTimes(hexUID, name, elapsed) # Function to plubish the race times for the current user. # It takes the hexUID, name and completionTime # and publishes them to the AWS IoT topic.
def measure(): # Send a 10us pulse to trigger GPIO.output(GPIO_TRIGGER, True) time.sleep(0.00001) GPIO.output(GPIO_TRIGGER, False) start = time.time() while GPIO.input(GPIO_ECHO) == 0: start = time.time() while GPIO.output(GPIO_ECHO) == 1: stop = time.time() elapsed = stop - start distance = (elapsed * 34300) / 2 return distance
def read_soil_moist_digital(gpio_pin): reading = False soil_value = None count = 0 while reading == False: GPIO.setup(gpio_pin, GPIO.IN) try: soil_value = GPIO.input(gpio_pin) except Exception as e: print("!!! couldn't read sensor, error " + str(e)) time.sleep(1) if not soil_value == None: print(" The sensor " + str(gpio_pin) + " returned a value of; " + str(soil_value)) return soil_value count = count + 1 if count >= 10: print("Sensor failed to read ten times, giving up...") return 'none'
def door_check(self, channel): time.sleep(3) status = GPIO.input(button_pin) db = get_db() # logging.getLogger('garage').info('status = %s, last status = %s' % (status, self.last_status)) if status == 1: if status != self.last_status: db.record_door_closed() logging.getLogger('garage').info('Door closed') self.notify.notify() else: pass # logging.getLogger('garage').info('Door closed again') else: if status != self.last_status: db.record_door_opened() logging.getLogger('garage').info('Door opened') self.notify.notify() self.camera.take_picture() else: pass # logging.getLogger('garage').info('Door opened again') db.shutdown() self.last_status = status
def button_press_switch(channel): global button_status GPIO.remove_event_detect(channel) logging.info('Button pressed') pressed_time = datetime.datetime.now() while not GPIO.input(channel): time.sleep(.5) dif = datetime.datetime.now() - pressed_time pressed_time = dif.seconds if pressed_time > 6: shutdown() button_status = BUTTON_SHUTDOWN elif pressed_time > 2: button_status = BUTTON_MONITOR_SWITCH else: button_status = BUTTON_SENSOR_SWITCH logging.info("Button status = %s", button_status) GPIO.add_event_detect(channel, GPIO.FALLING, callback=button_press_switch, bouncetime=200) # Run cleanup routines
def shutdown(channel): """ Calls system shutdown after a button press of more than 2 seconds """ GPIO.remove_event_detect(channel) pressed_timestamp = datetime.datetime.now() while not GPIO.input(channel): time.sleep(.5) dif = datetime.datetime.now() - pressed_timestamp pressed_time = dif.seconds logging.debug('Pressed time = %s', pressed_time) if pressed_time > 2: logging.info('Button initiated shutdown') os.system("sudo shutdown -h now") GPIO.add_event_detect(channel, GPIO.FALLING, callback=shutdown, bouncetime=200) # Add button pressed event detects
def shutdown(channel): # Change to lowercase function name # Modify function to require the shutdown button to be pressed and held # for at least 2 seconds before shutting down. GPIO.remove_event_detect(channel) pressed_time = datetime.datetime.now() while not GPIO.input(channel): time.sleep(.5) dif = datetime.datetime.now() - pressed_time pressed_time = dif.seconds logging.debug('Pressed time = %s', pressed_time) if pressed_time > 2: pass #os.system("sudo shutdown -h now") GPIO.add_event_detect(channel, GPIO.FALLING, callback=shutdown, bouncetime=200) ## ##
def button_press_switch(channel): GPIO. remove_event_detect(channel) print('Button pressed') pressed_time = datetime.datetime.now() while not GPIO.input(channel): time.sleep(.5) dif = datetime.datetime.now() - pressed_time pressed_time = dif.seconds if pressed_time < 2: button_status = 1 elif pressed_time < 6: button_status = 2 else: button_status = 4 print(button_status) GPIO.add_event_detect(channel, GPIO.FALLING, callback=button_press_switch, bouncetime=200) ## ##
def RCtime (PiPin): measurement = 0 # Discharge capacitor GPIO.setup(PiPin, GPIO.OUT) GPIO.output(PiPin, GPIO.LOW) time.sleep(0.1) GPIO.setup(PiPin, GPIO.IN) # Count loops until voltage across # capacitor reads high on GPIO start = time.time() while (GPIO.input(PiPin) == GPIO.LOW): measurement += 1 end = time.time() # print end - start # return measurement return str(end - start) # Connects the socket
def RCtime (PiPin): measurement = 0 # Discharge capacitor GPIO.setup(PiPin, GPIO.OUT) GPIO.output(PiPin, GPIO.LOW) time.sleep(0.1) GPIO.setup(PiPin, GPIO.IN) # Count loops until voltage across # capacitor reads high on GPIO start = time.time() while (GPIO.input(PiPin) == GPIO.LOW): measurement += 1 end = time.time() # print end - start # return measurement return str(end - start) # Main program loop
def light_sense(): count = 0 #Output on the pin for GPIO.setup(pin_to_circuit, GPIO.OUT) GPIO.output(pin_to_circuit, GPIO.LOW) time.sleep(0.1) #Change the pin back to input GPIO.setup(pin_to_circuit, GPIO.IN) #Count until the pin goes high while (GPIO.input(pin_to_circuit) == GPIO.LOW): count += 1 if (count > 3000): led5_on() return count else: led5_off() return count
def ADC_Read(channel): value = 0; for i in range(0,4): if((channel >> (3 - i)) & 0x01): GPIO.output(Address,GPIO.HIGH) else: GPIO.output(Address,GPIO.LOW) GPIO.output(Clock,GPIO.HIGH) GPIO.output(Clock,GPIO.LOW) for i in range(0,6): GPIO.output(Clock,GPIO.HIGH) GPIO.output(Clock,GPIO.LOW) time.sleep(0.001) for i in range(0,10): GPIO.output(Clock,GPIO.HIGH) value <<= 1 if(GPIO.input(DataOut)): value |= 0x01 GPIO.output(Clock,GPIO.LOW) return value
def detect_distance(): # ?????? GPIO.output(TRIG_CHANNEL, GPIO.HIGH) # ??10us?? time.sleep(0.000015) GPIO.output(TRIG_CHANNEL, GPIO.LOW) while GPIO.input(ECHO_CHANNEL) == GPIO.LOW: pass # ??????????? t1 = time.time() while GPIO.input(ECHO_CHANNEL) == GPIO.HIGH: pass # ?????????? t2 = time.time() # ????????? return (t2-t1)*340/2
def jsonstatus(): status = {} for pin in pinLEDs: status[pinLEDs[pin]] = str(GPIO.input(pin)) status['distance'] = str(round(MeasureDistance() * 100, 1)) + ' cm' status['surface'] = BlackOrWhite() # JSON encode and transmit response response = json.dumps(status) client_sock.send(response) return # # main loop # # add serial port service
def get_status_string(): with thermostatLock: sched = "None" if holdControl.state == "down": sched = "Hold" elif useTestSchedule: sched = "Test" elif heatControl.state == "down": sched = "Heat" elif coolControl.state == "down": sched = "Cool" return "[b]System:[/b]\n " + \ "Heat: " + ( "[color=00ff00][b]On[/b][/color]" if GPIO.input( heatPin ) else "Off" ) + "\n " + \ "Cool: " + ( "[color=00ff00][b]On[/b][/color]" if GPIO.input( coolPin ) else "Off" ) + "\n " + \ "Fan: " + ( "[color=00ff00][b]On[/b][/color]" if GPIO.input( fanPin ) else "Auto" ) + "\n " + \ "Sched: " + sched
def ShowPhoto(photoFile): screen = pygameEngine.GetScreen() image = pygame.image.load(photoFile).convert() image = pygame.transform.scale(image, (config.WIDTH,config.HEIGHT)) screen.blit(image, (0,0)) pygame.display.update() sleep(1) pygameEngine.ShowNavButtons() i = 0 while True: # get one pygame event event = pygame.event.poll() # handle events # Button 1 = Quit if (event.type == pygame.MOUSEBUTTONUP and event.button == 1) or (event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE) or GPIO.input(config.GPIO_NUMBER_BUTTON_1): return -1 # Button 2 = Cycle old photos if (event.type == pygame.MOUSEBUTTONUP and event.button == 3) or (event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN) or GPIO.input(config.GPIO_NUMBER_BUTTON_2): return 1 # Button Esc or Q = Quit keys if event.type == pygame.KEYDOWN and (event.key == pygame.K_ESCAPE or event.key == pygame.K_q) : return -1
def button_pressed(self, channel): # Debouncing time.sleep(0.05) if (GPIO.input(channel) == 0): # Find out which button was pressed for button in self.buttons: if (channel == self.buttons[button]): # Change screen if (button == 'MODE_BUTTON'): if (self.display != False): self.display.change_screen() # Toggle backlight elif (button == 'PAUSE_BUTTON'): if (self.display != False): self.display.toggle_backlight() # Send command to MPD client elif (self.mpd != False): self.mpd.commands(button.replace('_BUTTON', ''))
def lowBattery(channel): #Checking for LED bounce for the duration of the battery Timeout for bounceSample in range(1, int(round(batteryTimeout / sampleRate))): time.sleep(sampleRate) if GPIO.input(batteryGPIO) is 1: break global playerFlag while playerFlag is 1: time.sleep(1) #If the LED is a solid for more than 10% of the timeout, we know that the battery is getting low. Launch the Low Battery alert. if bounceSample > int(round(batteryTimeout / sampleRate * 0.1)): playerFlag = 1 os.system("/usr/bin/omxplayer --no-osd --layer 999999 " + lowalertVideo + " --alpha 160;"); playerFlag = 0 #Discovered a bug with the Python GPIO library and threaded events. Need to unbind and rebind after a System Call or the program will crash GPIO.remove_event_detect(batteryGPIO) GPIO.add_event_detect(batteryGPIO, GPIO.FALLING, callback=lowBattery, bouncetime=300)
def powerSwitch(channel): #Checking for LED bounce for the duration of the Power Timeout for bounceSample in range(1, int(round(powerTimeout / sampleRate))): time.sleep(sampleRate) if GPIO.input(powerGPIO) is 0: break if bounceSample is int(round(powerTimeout / sampleRate)) - 1: #When the Power Switch is placed in the off position with no bounce for the duration of the Power Timeout, we immediately shutdown os.system("sudo shutdown -h now") try: sys.stdout.close() except: pass try: sys.stderr.close() except: pass sys.exit(0)
def main(): #if the Low Battery LED is active when the program launches, handle it if GPIO.input(batteryGPIO) is 0: lowBattery(batteryGPIO) #if the Power Switch is active when the program launches, handle it if GPIO.input(powerGPIO) is 1: powerSwitch(powerGPIO) #Add threaded event listeners for the Low Battery and Power Switch try: GPIO.remove_event_detect(batteryGPIO) GPIO.add_event_detect(batteryGPIO, GPIO.FALLING, callback=lowBattery, bouncetime=300) GPIO.remove_event_detect(powerGPIO) GPIO.add_event_detect(powerGPIO, GPIO.RISING, callback=powerSwitch, bouncetime=300) except KeyboardInterrupt: GPIO.cleanup()
def read(self): self.waitForReady() unsignedValue = 0 for i in range(0, self.readBits): GPIO.output(self.PD_SCK, True) unsignedValue = unsignedValue << 1 GPIO.output(self.PD_SCK, False) bit = GPIO.input(self.DOUT) if (bit): unsignedValue = unsignedValue | 1 self.setChannelGainFactor() signedValue = self.correctForTwosComplement(unsignedValue) self.lastVal = signedValue return self.lastVal
def set(self): parser = argparse.ArgumentParser( description='Set zone state high=1 or low=0') parser.add_argument('--zone', help='Set zone 1/2/3/4/5 or *', required=False) parser.add_argument('--state',help='Set state high=1 or low=0', required=False) args = parser.parse_args(sys.argv[2:]) if args.zone: for zone in self.data["zones"]: if zone["id"]==int(args.zone): GPIO.setup(zone["boardOut"], GPIO.OUT) GPIO.output(zone["boardOut"], int(args.state)) zone["value"] = GPIO.input(int(zone["boardOut"])) print zone else: self.setAll(args.state)
def get(self): parser = argparse.ArgumentParser( description='Set zone state high=1 or low=0') parser.add_argument('--zone', help='Set zone 1/2/3/4/5 or *', required=False) args = parser.parse_args(sys.argv[2:]) if args.zone: for zone in self.data["zones"]: if zone["id"]==int(args.zone): GPIO.setup(zone["boardOut"], GPIO.OUT) zone["value"]=GPIO.input(int(zone["boardOut"])) print zone else: print self.getAll()
def value(self, v=None): if v is None: return GPIO.input(self.gpio_no) GPIO.output(self.gpio_no, v) print("GPIO ########## GPIO.output({},{})={}".format(self.gpio_no,v,GPIO.input(self.gpio_no)))
def accState(roomNumber, accNumber): if roomNumber == 0: if GPIO.input(outPin[roomNumber][accNumber]) is 1: return 'containerOff' else: return 'containerOn' elif roomNumber > 0: #get the state of other accesories in other rooms return 'containerOff'
def buttonStates(): accState=[] for i in range(len(outPin)): accState.append([]) for j in range(len(outPin[i])): accState[i].append(1 - GPIO.input(outPin[i][j])) return json.dumps(accState)
def toggle(roomNumber, accNumber): if len(outPin[roomNumber]) != 0: state= 1 - GPIO.input(outPin[roomNumber][accNumber]) GPIO.output(outPin[roomNumber][accNumber], state) #subprocess.call(['./echo.sh'], shell=True) else: #action for other rooms subprocess.call(['./echo.sh'], shell=True) #print(roomNumber, accNumber) buttonHtmlName = accName[roomNumber][accNumber].replace(" ", "<br>") passer="<button class='%s' onclick='toggle(%d,%d)'>%s</button>" % (accState(roomNumber,accNumber), roomNumber, accNumber, buttonHtmlName) return passer
def getio(self, io_number): if self.importlib is not None: return GPIO.input(io_number)
def main(): read_25 = GPIO.input(25) print(read_25) GPIO.cleanup() ### #############################
def get_state(sleep_time=wheel_pulse): # clear trigger sensor gpio.output(trigger, False) time.sleep(sleep_time) # send trigger pulse gpio.output(trigger, True) time.sleep(0.00001) gpio.output(trigger, False) while gpio.input(echo) == 0: pulse_start = time.time() while gpio.input(echo) == 1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start distance = pulse_duration * 343 * 100 / 2. # speed of sound m/s * m to cm / round trip if distance > 2 and distance < 400: # sensor range distance = distance + distance_from_sensor_to_car_front # don't worry about things further 4' # this also reduces the size of the state machine if distance >= max_distance: distance = max_distance - 1 return int(distance) ############################################################################## # perform action ##############################################################################
def get_distance(self): # clear trigger gpio.output(self.trigger, False) time.sleep(0.1) print('checking.....') # send pulse to trigger gpio.output(self.trigger, True) time.sleep(0.00001) gpio.output(self.trigger, False) # check echo for return signal while gpio.input(self.echo) == 0: self.pulse_start = time.time() while gpio.input(self.echo) == 1: self.pulse_end = time.time() pulse_duration = self.pulse_end - self.pulse_start distance = self.speed_of_sound / 2. * pulse_duration distance = round(distance, 2) distance /= 2.54 # inches # filter out things far away if distance > self.max_distance: distance = self.max_distance # filter out junk if distance < self.min_distance: disance = self.min_distance return distance