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
python类PUD_UP的实例源码
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 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 __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 __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 __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 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')
12_rotaryEncoder.py 文件源码
项目:SunFounder_Super_Kit_V3.0_for_Raspberry_Pi
作者: sunfounder
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
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():
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):
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."
gpioRotaryEncoder.py 文件源码
项目:RaspberryPiControllerQtPython
作者: take-iwiw
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
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 __init__(self, config):
global DIRECTIONS, PULLUPS
import RPi.GPIO as gpio
self.io = gpio
DIRECTIONS = {
PinDirection.INPUT: gpio.IN,
PinDirection.OUTPUT: gpio.OUT
}
PULLUPS = {
PinPullup.OFF: gpio.PUD_OFF,
PinPullup.UP: gpio.PUD_UP,
PinPullup.DOWN: gpio.PUD_DOWN
}
gpio.setmode(gpio.BCM)
def __init__(self, resultQ):
multiprocessing.Process.__init__(self)
#we do not want to receive any tasks... for now
#self.taskQ = taskQ
self.resultQ = resultQ
self.initOK = False
self.intervallsec = 1 #intervall in seconds
if not self.enabled:
self.initOK=False
else:
self.initOK=True
io.setmode(io.BCM)
self.pir_pin = 18
io.setup(self.pir_pin, io.IN, pull_up_down=io.PUD_UP)
#THIS IS NOT WORKING, as RPI.GPIO says "no can do this channel", maybe wirinpgi?
#self.backlight_pin_virtual = 508
#io.setup(self.backlight_pin_virtual, io.OUT)
#io.output(self.backlight_pin_virtual, 0)
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):
super().__init__()
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def set_voice_sensor():
GPIO.setup(GPIOConfig.VOICE_SENSOR, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(GPIOConfig.VOICE_SENSOR, GPIO.FALLING)
def __init__(self, button_pin=12):
self.button_pin = button_pin
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set button_pin's mode is input, and pull up to high level(3.3V)
pass
def __init__(self, channel, polarity=GPIO.FALLING,
pull_up_down=GPIO.PUD_UP):
super().__init__()
self.channel = channel
self.polarity = polarity
if polarity not in [GPIO.FALLING, GPIO.RISING]:
raise ValueError('polarity must be GPIO.FALLING or GPIO.RISING')
self.expected_value = polarity == GPIO.RISING
self.event_detect_added = False
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN, pull_up_down=pull_up_down)
def __init__(self,
channel,
polarity=GPIO.FALLING,
pull_up_down=GPIO.PUD_UP,
debounce_time=0.08):
"""A simple GPIO-based button driver.
This driver supports a simple GPIO-based button. It works by detecting
edges on the given GPIO channel. Debouncing is automatic.
Args:
channel: the GPIO pin number to use (BCM mode)
polarity: the GPIO polarity to detect; either GPIO.FALLING or
GPIO.RISING.
pull_up_down: whether the port should be pulled up or down; defaults to
GPIO.PUD_UP.
debounce_time: the time used in debouncing the button in seconds.
"""
if polarity not in [GPIO.FALLING, GPIO.RISING]:
raise ValueError(
'polarity must be one of: GPIO.FALLING or GPIO.RISING')
self.channel = int(channel)
self.polarity = polarity
self.expected_value = polarity == GPIO.RISING
self.debounce_time = debounce_time
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN, pull_up_down=pull_up_down)
self.callback = None
def __init__(self, pin):
self.pin = pin
GPIO.setup(self.pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def __init__(self):
#the structure for a bt keyboard input report (size is 10 bytes)
self.state=[
0xA1, #this is an input report
0x01, #Usage report = Keyboard
#Bit array for Modifier keys
[0, #Right GUI - Windows Key
0, #Right ALT
0, #Right Shift
0, #Right Control
0, #Left GUI
0, #Left ALT
0, #Left Shift
0], #Left Control
0x00, #Vendor reserved
0x00, #rest is space for 6 keys
0x00,
0x00,
0x00,
0x00,
0x00]
print "setting up GPIO"
GPIO.setmode(GPIO.BOARD)
GPIO.setup(DeskCycle.PIN,GPIO.IN,pull_up_down=GPIO.PUD_UP)
print "setting up DBus Client"
self.bus = dbus.SystemBus()
self.btkservice = self.bus.get_object('org.yaptb.btkbservice','/org/yaptb/btkbservice')
self.iface = dbus.Interface(self.btkservice,'org.yaptb.btkbservice')
#hard code the key to send
self.state[4]=DeskCycle.KEYCODE
def __init__(self):
print "setting up GPIO"
GPIO.setmode(GPIO.BOARD)
GPIO.setup(DeskCycle.PIN,GPIO.IN,pull_up_down=GPIO.PUD_UP)
self.hitCount=0
pin2=38
GPIO.setup(pin2,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
GPIO.add_event_detect(pin2, GPIO.FALLING, callback=self.pin_2_event,bouncetime=100)
def __init__(self, params):
self.params = params
if gpio_available:
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(self.params['pause_button_pin'], GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(self.params['pause_led_pin'], GPIO.OUT)
else:
rospy.logwarn("Ergo hasn't found the GPIO, button will not work")
def setup(self):
gpio.setup(self.pin, gpio.IN, gpio.PUD_UP)
self.state = gpio.input(self.pin)
self.t = task.LoopingCall(self.loop)
self.t.start(0.1)