我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用RPi.GPIO.IN。
def setup(): if os.path.isdir(ImagePath) == False: os.mkdir(ImagePath, 0777) try: GPIO.cleanup() finally: pass GPIO.setmode(GPIO.BOARD) GPIO.setup(BeepPin, GPIO.OUT) GPIO.setup(LedPin, GPIO.OUT) GPIO.setup(ButtonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) ledOn() beepOn() time.sleep(0.1) ledOff() beepOff() # Loop, wait for button press
def __init__(self): gpio.setmode(gpio.BOARD) # set up and init self.trigger = 13 self.echo = 11 gpio.setup(self.trigger, gpio.OUT) gpio.setup(self.echo, gpio.IN) self.pulse_start = 0. self.pulse_end = 0. self.speed_of_sound = 343 * 100 self.max_distance = 100 self.min_distance = 1
def set_up_gpio(self): GPIO.setmode(GPIO.BCM) #GPIO.setup(camera_led_pin, GPIO.OUT, initial=False) # Set GPIO to output GPIO.setup(config.led_pin_select,GPIO.OUT) # The 'Select' button LED GPIO.setup(config.led_pin_left,GPIO.OUT) # The 'Left' button LED GPIO.setup(config.led_pin_right,GPIO.OUT) # The 'Right' button LED # Detect falling edge on all buttons GPIO.setup(config.button_pin_select, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(config.button_pin_left, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(config.button_pin_right, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(config.button_pin_exit, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Drumminhands found it necessary to switch off LEDs initially GPIO.output(config.led_pin_select, False) GPIO.output(config.led_pin_left, False) GPIO.output(config.led_pin_right, False)
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 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 __init__(self, ready): Thread.__init__(self) self.ready = ready self.picked_up = False self.on = True self._ringer1 = 11 self._ringer2 = 13 self._button = 7 GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(self._ringer1, GPIO.OUT) GPIO.output(self._ringer1, GPIO.LOW) GPIO.setup(self._ringer2, GPIO.OUT) GPIO.output(self._ringer2, GPIO.LOW) GPIO.setup(self._button, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) self._last_state = 0 self._last_ts = time.time() self._last_check = time.time() self._ring = 1 self.max_ring_cnt = 2
def main(): try: while True: for led in LEDS: for idx, pin in enumerate(led): if pin == O: GPIO.setup(PINS[idx], GPIO.IN) else: GPIO.setup(PINS[idx], GPIO.OUT) GPIO.output(PINS[idx], pin) time.sleep(.1) except KeyboardInterrupt: pass finally: GPIO.cleanup()
def main(): import RPi.GPIO as GPIO import time try: GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(18, GPIO.OUT) GPIO.setup(27, GPIO.IN) while True: time.sleep(1) finally: GPIO.cleanup()
def __init__(self, data): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) self.SPIMOSI = 23 self.SPIMISO = 24 self.SPICLK = 18 self.SPICS = 25 if "mosiPin" in data: self.SPIMOSI = data["mosiPin"] if "misoPin" in data: self.SPIMISO = data["misoPin"] if "clkPin" in data: self.SPICLK = data["clkPin"] if "csPin" in data: self.SPICS = data["csPin"] GPIO.setup(self.SPIMOSI, GPIO.OUT) GPIO.setup(self.SPIMISO, GPIO.IN) GPIO.setup(self.SPICLK, GPIO.OUT) GPIO.setup(self.SPICS, GPIO.OUT) if MCP3008.sharedClass == None: MCP3008.sharedClass = self #read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)
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 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 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 __init__(self,pinA,pinB,callback): self.pinA = pinA self.pinB = pinB #self.button = button self.callback = callback GPIO.setmode(GPIO.BCM) # The following lines enable the internal pull-up resistors # on version 2 (latest) boards GPIO.setwarnings(False) GPIO.setup(self.pinA, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(self.pinB, GPIO.IN, pull_up_down=GPIO.PUD_UP) #GPIO.setup(self.button, GPIO.IN, pull_up_down=GPIO.PUD_UP) # For version 1 (old) boards comment out the above four lines # and un-comment the following 3 lines #GPIO.setup(self.pinA, GPIO.IN) #GPIO.setup(self.pinB, GPIO.IN) #GPIO.setup(self.button, GPIO.IN) # Add event detection to the GPIO inputs GPIO.add_event_detect(self.pinA, GPIO.FALLING, callback=self.switch_event) GPIO.add_event_detect(self.pinB, GPIO.FALLING, callback=self.switch_event) #GPIO.add_event_detect(self.button, GPIO.BOTH, callback=self.button_event, bouncetime=200) return # Call back routine called by switch events
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 ResetIOT_HW(cls, bMode): """Set Raspberry pi GPIO pins and reset RF Explorer device Parameters: bMode -- True if the baudrate is set to 500000bps, False to 2400bps """ try: import RPi.GPIO as GPIO #print("RPi info: " + str(GPIO.RPI_INFO)) #information about your RPi: #print("RPi.GPio version: " + GPIO.VERSION) #version of RPi.GPIO: GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) #refer to the pin numbers on the P1 header of the Raspberry Pi board GPIO.setup(12, GPIO.OUT) #set /reset (pin 12) to output GPIO.output(12, False) #set /reset (pin 12) to LOW GPIO.setup(21, GPIO.OUT) #set GPIO2 (pin 21) to output GPIO.output(21, bMode) #set GPIO2 (pin 21) to HIGH (for 500Kbps) time.sleep(0.1) #wait 100ms GPIO.output(12, True) #set /reset to HIGH time.sleep(2.5) #wait 2.5sec GPIO.setup(21, GPIO.IN) #set GPIO2 to input GPIO.cleanup() #clean up GPIO channels except RuntimeError: print("Error importing RPi.GPIO! This is probably because you need superuser privileges. You can achieve this by using 'sudo' to run your script")
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 __init__(self, clockPin, dataPin, buttonPin, rotaryCallback, buttonCallback, rotaryType): # persist values self.clockPin = clockPin self.dataPin = dataPin self.buttonPin = buttonPin self.rotaryCallback = rotaryCallback self.buttonCallback = buttonCallback self.rotaryType = rotaryType # setup pins if self.rotaryType == "standard": GPIO.setup(clockPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # All pins are pull up because both GPIO.setup(dataPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # the encoder and the button elif self.rotaryType == "keyes": GPIO.setup(clockPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # All pins are pull up because both GPIO.setup(dataPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # the encoder and the button GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # will be connected to Ground
def __init__(self, button_pins, bounce_time): # Set bounce time self.bounce_time = bounce_time # Set buttons self.buttons = button_pins # Initialize display client self.display = False # We don't need warnings from GPIO GPIO.setwarnings(False) # Set button GPIO pins as inputs and enable interrupts for button in button_pins: if (button_pins[button] != False): GPIO.setup(button_pins[button], GPIO.IN, pull_up_down = GPIO.PUD_UP) GPIO.add_event_detect(button_pins[button], GPIO.FALLING, callback=self.button_pressed, bouncetime=self.bounce_time) # Initalize MPD self.mpd = False # Register MPD client to send it commands
def calibrate(self): print("calibrating...") self.recharge_capacitors() # GPIO.setup(sensor_inputs, GPIO.IN) for pin in self.sensor_inputs: time = self.get_sensor_reading(pin) # Get the index from the map index = self.sensor_indices[pin] # This is the first iteration if (self.max_val[index] == -1): self.max_val[index] = time.microseconds self.min_val[index] = time.microseconds else: # Store the min and max values seen during calibration if (time.microseconds > self.max_val[index]): self.max_val[index] = time.microseconds elif (time.microseconds < self.min_val[index]): self.min_val[index] = time.microseconds # Print the calculated time in microseconds print("Pin: " + str(pin)) print(time.microseconds)
def __init__(self, dout=4, pd_sck=18, gain=128, readBits=24, offset=-96096, scale=925): self.PD_SCK = pd_sck self.DOUT = dout self.readBits = readBits self.twosComplementOffset = 1 << readBits self.twosComplementCheck = self.twosComplementOffset >> 1 GPIO.setmode(GPIO.BCM) GPIO.setup(self.PD_SCK, GPIO.OUT) GPIO.setup(self.DOUT, GPIO.IN) self.GAIN = 0 self.set_offset(offset) self.set_scale(scale) self.lastVal = 0 self.set_gain(gain)
def __initGPIOs(self): #setup GPIO using Board numbering (pins, not GPIOs) GPIO.setwarnings(False) GPIO.cleanup() GPIO.setmode(GPIO.BOARD) #setup defined pins and event_detectors or outputs and initial states (initial is always 0, low) for pin in pins_in_use: if pins_in_use[pin][0] == GPIO.IN: if pin == 5: GPIO.setup(pin, pins_in_use[pin][0], pull_up_down=GPIO.PUD_UP) else: GPIO.setup(pin, pins_in_use[pin][0]) GPIO.add_event_detect(pin, pins_in_use[pin][1], callback=self.shoutItOut, bouncetime=100) self.gpio_states.update({pin: 1}) elif pins_in_use[pin][0] == GPIO.OUT: GPIO.setup(pin, pins_in_use[pin][0], initial=0)
def __init__(self,pinA,pinB,button,callback, parent): self.pinA = pinA self.pinB = pinB self.button = button self.callback = callback self.parent = parent if self.pinA is not None and self.pinB is not None: GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(self.pinA, GPIO.IN) GPIO.setup(self.pinB, GPIO.IN) GPIO.add_event_detect(self.pinA, GPIO.FALLING, callback=self.switch_event) GPIO.add_event_detect(self.pinB, GPIO.FALLING, callback=self.switch_event) if self.button is not None: GPIO.setup(self.button, GPIO.IN) GPIO.add_event_detect(self.button, GPIO.BOTH, callback=self.button_event, bouncetime=200) return # Call back routine called by switch events
def writeByte(self, data): for i in range(0, 8): IO.output(self.__Clkpin, IO.LOW) if(data & 0x01): IO.output(self.__Datapin, IO.HIGH) else: IO.output(self.__Datapin, IO.LOW) data = data >> 1 IO.output(self.__Clkpin, IO.HIGH) # wait for ACK IO.output(self.__Clkpin, IO.LOW) IO.output(self.__Datapin, IO.HIGH) IO.output(self.__Clkpin, IO.HIGH) IO.setup(self.__Datapin, IO.IN) while(IO.input(self.__Datapin)): sleep(0.001) if(IO.input(self.__Datapin)): IO.setup(self.__Datapin, IO.OUT) IO.output(self.__Datapin, IO.LOW) IO.setup(self.__Datapin, IO.IN) IO.setup(self.__Datapin, IO.OUT)
def begin(irq): """ This function opens the SPI connection available on the Raspberry Pi using the chip select #0. Normally, spidev can auto enable chip select when necessary. However, in our case, the dw1000's chip select is connected to GPIO16 so we have to enable/disable it manually. It also sets up the interrupt detection event on the rising edge of the interrupt pin. Args: irq : The GPIO pin number managing interrupts. """ global _deviceMode # Wait 5 us to open spi connection to let the chip enter idle state, see 2.3.2 of the DW1000 user manual (INIT). time.sleep(C.INIT_DELAY) GPIO.setmode(GPIO.BCM) spi.open(0, 0) # spi.max_speed_hz = 4000000 _deviceMode = C.IDLE_MODE GPIO.setup(irq, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(irq, GPIO.RISING, callback=handleInterrupt)
def Setup(): global logger logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) handler = logging.FileHandler('/var/log/rodi.log') handler.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(message)s',"%Y-%m-%d %H:%M:%S") handler.setFormatter(formatter) logger.addHandler(handler) GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(WATER_VALVE, GPIO.OUT) GPIO.setup(FLOATSW_HIGH_WL, GPIO.IN, pull_up_down=GPIO.PUD_UP) #, initial = GPIO.HIGH) if not sys.stdout.isatty(): sys.stderr = open('/var/log/rodi_stderr.log', 'a') sys.stdout = open('/var/log/rodi_stdout.log', 'a')
def setup(): global counter global Last_RoB_Status, Current_RoB_Status GPIO.setmode(GPIO.BCM) GPIO.setup(RoAPin, GPIO.IN) GPIO.setup(RoBPin, GPIO.IN) GPIO.setup(RoSPin,GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set up a falling edge detect to callback clear GPIO.add_event_detect(RoSPin, GPIO.FALLING, callback=clear) # Set up a counter as a global variable counter = 0 Last_RoB_Status = 0 Current_RoB_Status = 0 # Define a function to deal with rotary encoder
def main(): GPIO.setmode(GPIO.BCM) GPIO.setup(PIR_PIN, GPIO.IN) turned_off = False last_motion_time = time() while True: if GPIO.input(PIR_PIN): last_motion_time = time() print ".", sys.stdout.flush() if turned_off: turned_off = False turn_on() else: if not turned_off and time() > (last_motion_time + SHUTOFF_DELAY): turned_off = True turn_off() sleep(0.01)
def main(): try: GPIO.setmode(GPIO.BCM) GPIO.setup(START_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) root = tk.Tk() root.overrideredirect(True) width, height = root.winfo_screenwidth(), root.winfo_screenheight() root.geometry('{0}x{1}+0+0'.format(width, height)) root.wm_title('Stoppuhr') stopwatch = Stopwatch(LOG_FILENAME) GPIO.add_event_detect(START_PIN, GPIO.FALLING, stopwatch.start) stopwatch_ui = StopwatchUI(root, stopwatch) stopwatch_ui.pack() root.mainloop() finally: GPIO.cleanup()
def _configure_input(self, name, configuration): pin = configuration['pin'] self.log().debug('Pin %d -> %s' % (pin, name)) if configuration['pull_up_down'] == 'up': pull_up_or_down = GPIO.PUD_UP else: pull_up_or_down = GPIO.PUD_DOWN if 'debounce' in configuration: debounce = configuration['debounce'] else: debounce = 0 GPIO.setup(pin, GPIO.IN, pull_up_down = pull_up_or_down) GPIO.add_event_detect(pin, GPIO.BOTH, callback = self._channel_changed, bouncetime = debounce)
def __init__(self, trigger_pin, echo_pin, distance_threshold): threading.Thread.__init__(self) self.trigger_pin = trigger_pin; self.echo_pin = echo_pin; self.not_stopped = True; #set GPIO direction (IN / OUT) GPIO.setmode(GPIO.BCM) GPIO.setup(trigger_pin, GPIO.OUT) GPIO.setup(echo_pin, GPIO.IN) '''Callbacks to be handled when obstacle is detected''' self.on_obstacle_detected_handlers = [] self.current_distance = 0; '''distance threshold is used to trigger the handlers''' self.threshold = distance_threshold;
def __init__(self, dout=5, pd_sck=6, gain=128, bitsToRead=24): self.PD_SCK = pd_sck self.DOUT = dout GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(self.PD_SCK, GPIO.OUT) GPIO.setup(self.DOUT, GPIO.IN) # The value returned by the hx711 that corresponds to your # reference unit AFTER dividing by the SCALE. self.REFERENCE_UNIT = 1 self.GAIN = 0 self.OFFSET = 1 self.lastVal = 0 self.bitsToRead = bitsToRead self.twosComplementThreshold = 1 << (bitsToRead-1) self.twosComplementOffset = -(1 << (bitsToRead)) self.setGain(gain) self.read()
def __init__(self): self.__RESET = 26 GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(self.__RESET, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Do not proceed unless the reset signal has turned off # attempt to prevent restart storm in systemd print "waiting for reset to complete." while GPIO.input(self.__RESET) != 1: time.sleep(0.100) pass GPIO.add_event_detect( self.__RESET, GPIO.FALLING, callback=onReset, bouncetime=100) print "GPIO initialized."
def loop(gpio0, gpio1, resource): print (str(gpio0) + " " + str(gpio1)) GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(gpio0, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(gpio1, GPIO.IN, pull_up_down=GPIO.PUD_UP) previousCode = 0 while True: # code(FW) = 0 1 3 2 0 1 3 2 0 1 3 2 rotationTable = [0,1,-1,0,-1,0,0,1,1,0,0,-1,0,-1,1,0] val0 = GPIO.input(gpio0) val1 = GPIO.input(gpio1) currentCode = val0 << 1 | val1 # todo: chattering if currentCode != previousCode: code = previousCode << 2 | currentCode rotation = rotationTable[code & 0x0f] resource.diffRotate += rotation * TICK_DEGREE resource.totalRotate += rotation * TICK_DEGREE previousCode = currentCode time.sleep(0.002)
def setup_gpio(): """ Setup GPIO pins on which LEDs and button switch are connected. """ GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) # led output GPIO.setup(LED_1_PIN, GPIO.OUT) GPIO.setup(LED_2_PIN, GPIO.OUT) GPIO.setup(LED_BUTTON_PIN, GPIO.OUT) # button input GPIO.setup(BUTTON_PIN, GPIO.IN, GPIO.PUD_UP) # switch leds off reset_led()
def _read_generic(self): value = None if self.control == 'native': GPIO.setmode(GPIO.BCM) GPIO.setup(self.pins['input']['number'], GPIO.IN) value = GPIO.input(self.pins['input']['number']) elif self.control == 'arduino': with self.arduino_api_scope() as api: api.pinMode(self.pins['input']['number'], api.INPUT) if self.pins['input']['type'] == 'analog': value = api.analogRead(self.pins['input']['number']) elif self.pins['input']['type'] == 'digital': value = api.digitalRead(self.pins['input']['number']) return value
def __init__(self, no, dir=IN): self.gpio_no = no print("GPIO ########## self.gpio_no, dir={}, {}".format(self.gpio_no, dir)) GPIO.setmode(GPIO.BCM) #GPIO.setmode(GPIO.BOARD) if dir==Pin.IN: GPIO.setup(self.gpio_no, GPIO.IN) print("GPIO >>>>>>>>>>>>>>>>>>>>>>>>>>> IN") else: GPIO.setup(self.gpio_no, GPIO.OUT) print("GPIO <<<<<<<<<<<<<<<<<<<<<<<<<< OUT")
def setup_GPIO(): GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT) GPIO.setup(37, GPIO.OUT) GPIO.setup(35, GPIO.IN)
def __init__(self, name = ''): self.importlib = GPIO self.logger = com_logger.Logger(name) # self.setwarnings(False) self.IN = GPIO.IN if GPIO is not None else None self.OUT = GPIO.OUT if GPIO is not None else None self.LOW = GPIO.LOW if GPIO is not None else None self.HIGH = GPIO.HIGH if GPIO is not None else None self.PUD_UP = GPIO.PUD_UP if GPIO is not None else None self.PUD_DOWN = GPIO.PUD_DOWN if GPIO is not None else None self.RISING = GPIO.RISING if GPIO is not None else None
def pull(self, io_number): if self.importlib is not None: # self.logger.debug('pull') # Afin d'éviter de laisser flottante toute entrée, il est possible de connecter des résistances de pull-up ou de pull-down, au choix, en interne. # Pour information, une résistance de pull-up ou de pull-down a pour but d'éviter de laisser une entrée ou une sortie dans un état incertain, en # forçant une connexion à la # masse ou à un potentiel donné. GPIO.setup(io_number, GPIO.IN, pull_up_down = GPIO.PUD_UP) GPIO.setup(io_number, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
def __init__(self): gpio.setmode(gpio.BOARD) # set up and init self.trigger = 11 self.echo = 13 gpio.setup(self.trigger, gpio.OUT) gpio.setup(self.echo, gpio.IN) self.pulse_start = 0. self.pulse_end = 0. self.speed_of_sound = 343 * 100 self.car_length = 1