我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用RPi.GPIO.output()。
def blinking(): if keepalive: threading.Timer(10.0, blinking).start() # Only blink when we are actually building if building or error: # If error, blink red. if error: color = "red" else: color = "yellow" alloff() pin = getcode(color) GPIO.output(pin, True) time.sleep(3) GPIO.output(pin, False) # Check every 10s if we are building, if not or done get latest status
def __init__(self, lr, s_size, a_size): self.state_in = tf.placeholder(shape=[1], dtype=tf.int32) state_in_OH = slim.one_hot_encoding(self.state_in, s_size) output = slim.fully_connected(state_in_OH, a_size, biases_initializer=None, activation_fn=tf.nn.sigmoid, weights_initializer=tf.ones_initializer()) self.output = tf.reshape(output, [-1]) self.chosen_action = tf.argmax(self.output, 0) self.reward_holder = tf.placeholder(shape=[1], dtype=tf.float32) self.action_holder = tf.placeholder(shape=[1], dtype=tf.int32) self.responsible_weight = tf.slice(self.output, self.action_holder, [1]) self.loss = -(tf.log(self.responsible_weight) * self.reward_holder) optimizer = tf.train.GradientDescentOptimizer(learning_rate=lr) self.update = optimizer.minimize(self.loss)
def reverse(t=wheel_pulse/2): gpio.output(reverse_left, gpio.HIGH) gpio.output(reverse_right, gpio.HIGH) sleep(t) gpio.output(reverse_left, gpio.LOW) gpio.output(reverse_right, gpio.LOW) ########################################################################## # cleanup ##########################################################################
def reverse_left(t): gpio.output(15, gpio.HIGH) gpio.output(36, gpio.HIGH) sleep(t) gpio.output(15, gpio.LOW) gpio.output(36, gpio.LOW) # test
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 __init__(self, dev='/dev/spidev0.0', speed=1000000, pin_rst=22, pin_ce=0): self.pin_rst = pin_rst self.pin_ce = pin_ce SPI.openSPI(device=dev, speed=speed) GPIO.setmode(GPIO.BOARD) GPIO.setup(pin_rst, GPIO.OUT) GPIO.output(pin_rst, 1) if pin_ce != 0: GPIO.setup(pin_ce, GPIO.OUT) GPIO.output(pin_ce, 1) self.reset() self.dev_write(0x2A, 0x8D) self.dev_write(0x2B, 0x3E) self.dev_write(0x2D, 30) self.dev_write(0x2C, 0) self.dev_write(0x15, 0x40) self.dev_write(0x11, 0x3D) self.set_antenna(True)
def _GPIO_Power_Set(pins, on): if on==1: GPIO.output( pins, GPIO.HIGH) else : GPIO.output( pins, GPIO.LOW ) return #=====================================
def startwalking(): # Make the buzzer buzz on and off, half a second of # sound followed by half a second of silence # GPIO.output(PinRedPedestrian, GPIO.LOW) # GPIO.output(PinGreenPedestrian, GPIO.HIGH) iCount = 1 while iCount <= 4: GPIO.output(PinBuzzer, GPIO.HIGH) time.sleep(0.5) GPIO.output(PinBuzzer, GPIO.LOW) time.sleep(0.5) iCount += 1 # Turn the buzzer off and wait for 2 seconds # (If you have a second green 'pedestrian' LED, make it flash on and # off for the two seconds)
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 setup_output(self, name, pwm=False, initial=False): """ Set pin as output. :param name: Numer of the pin. :type name: int :param pwm: If value if PWM. :type pwm: bool :param initial: Initial value to set. :type initial: bool """ self._pins[name] = {"name": name, "type": "out", "pwm": None} GPIO.setup(name, GPIO.OUT) if pwm: pwm = GPIO.PWM(name, 200) pwm.start(initial * 100.0) self._pins[name]["pwm"] = pwm else: self[name] = initial
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 init(self,bitrate,SDAPIN,SCLPIN): if(SDAPIN != SCLPIN): self.SCL = SCLPIN self.SDA = SDAPIN else: print "SDA = GPIO"+str(self.SDA)+" SCL = GPIO"+str(self.SCL) #configer SCL as output GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(self.SCL, GPIO.OUT) GPIO.setup(self.SDA, GPIO.OUT) GPIO.output(self.SDA, GPIO.HIGH) GPIO.output(self.SCL, GPIO.HIGH) if bitrate == 100: self.int_clk = 0.0000025 elif bitrate == 400: self.int_clk = 0.000000625 elif bitrate == 1000: self.int_clk = 1 elif bitrate == 3200: self.int_clk = 1
def Start(self): #SCL # ______ # | |______ #SDA # ___ # | |_________ GPIO.setup(self.SDA, GPIO.OUT) #cnfigure SDA as output GPIO.output(self.SDA, GPIO.HIGH) GPIO.output(self.SCL, GPIO.HIGH) self.tick(1) GPIO.output(self.SDA, GPIO.LOW) self.tick(1) GPIO.output(self.SCL, GPIO.LOW) self.tick(2)
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 calculateDistance(): GPIO.output(TRIG, False) time.sleep(0.000002) GPIO.output(TRIG, True) time.sleep(0.00001) GPIO.output(TRIG, False) try: pulse_start = pulseIn(ECHO, 0) pulse_end = pulseIn(ECHO, 1) except ValueError as error: logging.warning(str(error)) return False # Speed of sound 34300 cm/s distance = round((pulse_end - pulse_start) * 17150) # round distance to upper multiple of 5, e.g. 146 -> 150; 140 -> 145 distance += READING_ROUND - distance % READING_ROUND return distance if 0 < distance < HEIGHT_CAN else False # determines how full the can is
def test_relay(): """Test relay on and off cycle""" # check if the output is high print 'current control output is: ', is_output_high(), ' (should be off)' # start the relay start_relay() print 'current control output is: ', is_output_high(), ' (should be on)' # setup a timer to stop the relay after 5 seconds t = Timer(5, stop_relay) t.start() # wait for the timer to finish t.join()
def quit(self): """ Cleanup function """ log.debug("Quitting") log.debug("Cleaning the photobooth") self.queue.put("exit") self.camera.close() self.lamp.set_level(0) self.count_display.switch_off() GPIO.output(self.trigger_led_channel, 0) GPIO.output(self.shutdown_led_channel, 0) GPIO.cleanup() sys.exit() ################# ### Functions ### #################
def __init__(self, channel, invert=False): from navio import adafruit_pwm_servo_driver as pwm from navio import util import RPi.GPIO as GPIO util.check_apm() #Navio+ requires the GPIO line 27 to be set to low #before the PCA9685 is accesed GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(27, GPIO.OUT) GPIO.output(27,GPIO.LOW) #GPIO.cleanup() self.frequency = 60 self.channel = channel self.invert = invert self.pwm = pwm.PWM() self.pwm.setPWMFreq(self.frequency)
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 _v2_init(self): self.reset() self._send_command(0x74, 0x54) # Set analog control block self._send_command(0x75, 0x3b) # Sent by dev board but undocumented in datasheet # Driver output control self._send_command(0x01, [0xd3, 0x00, 0x00]) # Dummy line period # Default value: 0b-----011 # See page 22 of datasheet self._send_command(0x3a, 0x07) # Gate line width self._send_command(0x3b, 0x04) # Data entry mode self._send_command(0x11, 0x03)
def _pin_pulse(pin, initial_state=GPIO.LOW, pulse_width=PULSE_WIDTH_SEC): # type: (int, bool, Union[int, float]) -> None """Sends one pulse to the specified pin. The pin will be returned to the specified initial state after the pulse Args: pin: The pin to pulse. initial_state: The negation of this will be used as the pulse. Defaults to GPIO.LOW. pulse_width: how long, in seconds, to pulse the pin. Defaults to PULSE_WIDTH_SEC. """ GPIO.output(pin, not initial_state) try: time.sleep(pulse_width) finally: GPIO.output(pin, initial_state)
def _int_to_bcd(value): # type: (Optional[int]) -> Tuple[bool, bool, bool, bool] """Converts an integer to a tuple representing the input bits to a BCD. If the input value is None, an all high output will be produced. This will typically make the BCD to turn its corresponding output off. Args: value: The value to be converted. Returns: tuple of bool corresponding to the BCD representation of the inputted value. """ if value is None: output = (GPIO.HIGH,) * 4 elif 0 <= value <= 9: output = tuple(int(digit, 2) for digit in "{:04b}".format(value)) assert len(output) == 4 else: raise ValueError("Specified input must be either None or between " "0 and 9. Input was: {!r}.".format(value)) logger.debug("Converted %s to %s", value, output) return output
def pulsetest(): dir=True for freq in [200, 400, 800, 1000]: halfpulse=.5/freq # for j in range(0,i): logging.debug("start") for i in range(0,1600): GPIO.output(pulse_pin, True) time.sleep(halfpulse) GPIO.output(pulse_pin, False) time.sleep(halfpulse) logging.debug("stop") dir=not dir GPIO.output(dir_pin, dir) time.sleep(.5) # logging.debug(i)
def __init__(self): GPIO.setmode(GPIO.BCM) GPIO.setup(self.dir_pin, GPIO.OUT) GPIO.setup(self.pulse_pin, GPIO.OUT) GPIO.setup(self.ms1_pin, GPIO.OUT) GPIO.setup(self.ms2_pin, GPIO.OUT) GPIO.setup(self.sleep_pin, GPIO.OUT) GPIO.setup(self.reset_pin, GPIO.OUT) dir=False GPIO.output(self.dir_pin, dir) GPIO.output(self.pulse_pin, False) GPIO.output(self.ms1_pin, True) GPIO.output(self.ms2_pin, False) GPIO.output(self.sleep_pin, False) GPIO.output(self.reset_pin, True) self.p1 = GPIO.PWM(self.pulse_pin, self.pulse_freq)
def beep(self): if self.state is False: cbpi.app.logger.error("BUZZER not working") return def play(sound): try: for i in sound: if (isinstance(i, str)): if i == "H" and self.beep_level == "HIGH": GPIO.output(int(self.gpio), GPIO.HIGH) elif i == "H" and self.beep_level != "HIGH": GPIO.output(int(self.gpio), GPIO.LOW) elif i == "L" and self.beep_level == "HIGH": GPIO.output(int(self.gpio), GPIO.LOW) else: GPIO.output(int(self.gpio), GPIO.HIGH) else: time.sleep(i) except Exception as e: pass start_new_thread(play, (self.sound,))
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 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 alloff(): GPIO.output(getcode('red'), False) GPIO.output(getcode('buzzer'), False) GPIO.output(getcode('yellow'), False) GPIO.output(getcode('green'), False) return # Toggle function with parameter output and duration
def toggle(gpio, duration): GPIO.output(gpio, True) time.sleep(duration) GPIO.output(gpio, False) time.sleep(duration) return # Set according to status
def setstatus(status): if status != "": alloff() if status == "SUCCESS": GPIO.output(getcode('green'), True) if status == "UNSTABLE": GPIO.output(getcode('yellow'), True) if status == "FAILURE": GPIO.output(getcode('red'), True) return
def led1(on_off): GPIO.output(7, bool(on_off))
def led2(on_off): GPIO.output(37, bool(on_off))
def switchOnLight(PIN): GPIO.setup(PIN, GPIO.OUT) GPIO.output(PIN, True)
def switchOffLight(PIN): GPIO.setup(PIN, GPIO.OUT) GPIO.output(PIN, False)
def beepOn(): global DisableBeep if DisableBeep == False: GPIO.output(BeepPin, GPIO.LOW)
def beepOff(): GPIO.output(BeepPin, GPIO.HIGH)
def ledOn(): GPIO.output(LedPin, GPIO.LOW)
def ledOff(): GPIO.output(LedPin, GPIO.HIGH) # Event Listener
def setstate(roomNumber, accNumber, state): if len(outPin[roomNumber]) != 0: GPIO.output(outPin[roomNumber][accNumber], 1 - state) #subprocess.call(['./echo.sh'], shell=True) else: #action for other rooms subprocess.call(['./echo.sh'], shell=True) return "0"
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 setio(self, io_number, state): if self.importlib is not None: GPIO.output(io_number, state)
def switchio(self, io_number): if self.importlib is not None: GPIO.output(io_number, not self.getio(io_number))
def reset_led(self): GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) for gpio in self.gpios: gpio = int(gpio) GPIO.setup(gpio, GPIO.OUT) GPIO.output(gpio, GPIO.HIGH)
def enable_tally(self, enable): if enable: GPIO.output(self.gpio_red, GPIO.LOW) else: GPIO.output(self.gpio_red, GPIO.HIGH)
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 forward(t=wheel_pulse): gpio.output(forward_right, gpio.HIGH) gpio.output(forward_left, gpio.HIGH) sleep(t) gpio.output(forward_right, gpio.LOW) gpio.output(forward_left, gpio.LOW)