Python RPi.GPIO 模块,PUD_UP 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用RPi.GPIO.PUD_UP。
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 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')
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."
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)
def reset_radio(self):
"""
Reset the Si4707 chip
"""
# Ref https://github.com/AIWIndustries/Pi_4707/blob/master/firmware/NWRSAME_v2.py
if self.gpio_started:
gpio.cleanup()
self.gpio_started = True
gpio.setmode(gpio.BCM) # Use board pin numbering
gpio.setup(17, gpio.OUT) # Setup the reset pin
gpio.output(17, gpio.LOW) # Reset the Si4707.
sleep(0.4)
gpio.output(17, gpio.HIGH)
gpio.setup(23, gpio.IN, pull_up_down=gpio.PUD_UP)
gpio.add_event_detect(23, gpio.FALLING)
# Initialize the onboard relays
for pin in self.relay_gpio_pins:
gpio.setup(pin, gpio.OUT) # setup gpio pin for relay
gpio.output(pin, gpio.LOW) # boot to disabled state
# set up the LED
# https://www.reddit.com/r/raspberry_pi/comments/3641ug/blinking_an_onboard_led_on_the_pi_2_model_b/
# http://raspberrypi.stackexchange.com/questions/697/how-do-i-control-the-system-leds-using-my-
# sudo echo none >/sys/class/leds/led0/trigger
# GPIO 16 LOW is on, HIGH is off
gpio.setup(16, gpio.OUT)
gpio.output(16, gpio.HIGH)
sleep(1.5)
def __init__(self):
GPIO.setmode(GPIO.BCM)
#Setup each hall effect pin for interrupts
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)
print ("Encoders Ready")
GPIO.add_event_detect(18, GPIO.FALLING, callback=self.add_right_pulse)
GPIO.add_event_detect(24, GPIO.FALLING, callback=self.add_left_pulse)
while 1:
pass
# Callback function for Hall Sensor interrupts
def __init__(self, gpio_pin):
self.gpio_pin = gpio_pin
GPIO.setmode(GPIO.BCM)
GPIO.setup(gpio_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def __init__(self):
self.button_callback = None
self.button_held_callback = None
self.reset_callback = None
self.pressed_at = None
self.time_to_hold = 1
self.time_to_reset = 5
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(18, GPIO.BOTH, callback=self.button_state_changed,bouncetime=200)
def __init__(self, index, gpio_pin):
self.pressed = False
self._on_press_handler = None
self._on_release_handler = None
self._gpio_pin = gpio_pin
self._index = index
GPIO.setup(self._gpio_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(self._gpio_pin, GPIO.BOTH, bouncetime=1, callback=self._handle_button)
def main():
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(LAMP_SX, GPIO.OUT)
GPIO.setup(LAMP_DX, GPIO.OUT)
GPIO.output(LAMP_SX, 0)
GPIO.output(LAMP_DX, 0)
GPIO.setup(INT_SX, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(INT_DX, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(INT_SX, GPIO.BOTH, callback=handler_int_sx, bouncetime=100)
GPIO.add_event_detect(INT_DX, GPIO.BOTH, callback=handler_int_dx, bouncetime=100)
try:
#Entro in un loop infinito dove conto i secondi che passano
while True:
time.sleep(1)
except KeyboardInterrupt:
print "Exit"
GPIO.cleanup() # clean up GPIO on CTRL+C exit
GPIO.cleanup() # clean up GPIO on normal exit
def setup():
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
print strftime('%d.%m.%Y: ', gmtime()) + 'rev counter started with an interval of ' + str(interval) + ' second(s)'
def __init__(self, pin):
GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(pin, GPIO.BOTH, callback=self._gpio_event)
self._pin = pin
self._pressed = False
self._was_pressed = False
self._was_released = False
def initGpio(self):
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(23, GPIO.RISING, callback=self.tickFlow1, bouncetime=20)
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(24, GPIO.RISING, callback=self.tickFlow2, bouncetime=20)
self.fm1 = FlowMeter('metric', ["beer"])
self.fm1.enabled = True
self.fm2 = FlowMeter('metric', ["beer"])
self.fm2.enabled = True
def __init__(self, clockPin, dataPin, switchPin, rotaryCallback, switchCallback):
#persist values
self.clockPin = clockPin
self.dataPin = dataPin
self.switchPin = switchPin
self.rotaryCallback = rotaryCallback
self.switchCallback = switchCallback
#setup pins
GPIO.setup(clockPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(dataPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(switchPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def __init__(self):
# Set the board.
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# Setup outputs.
for pin in self.__output_pins:
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, False)
# Setup inputs.
for pin in self.__input_pins:
GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Initialize the timers.
self.init_c1()
self.init_c2()
self.__mcp = Adafruit_MCP3008.MCP3008(clk=self.__CLK, cs=self.__CS, miso=self.__MISO, mosi=self.__MOSI)
self.__output_len = len(self.__output_pins)
self.__input_len = len(self.__input_pins)
## Destructor
# @param self The object pointer.
def Setup():
global logger
global p_R
global p_G
global p_B
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(Pins["FLOATSW_HIGH_WL"], GPIO.IN, pull_up_down=GPIO.PUD_UP, initial = GPIO.HIGH)
GPIO.setup(Pins["FLOATSW_LOW_WL"], GPIO.IN, pull_up_down=GPIO.PUD_UP, initial = GPIO.HIGH)
GPIO.setup(Pins["FLOATSW_LOW_AWC_WL"], GPIO.IN, pull_up_down=GPIO.PUD_UP, initial = GPIO.HIGH)
GPIO.setup(Pins["WATER_LEAK_DETECTOR_1"], GPIO.IN)
GPIO.setup(Pins["WATER_LEAK_DETECTOR_2"], GPIO.IN)
GPIO.setup(Pins["WATER_VALVE"], GPIO.OUT)
GPIO.setup(Pins["AWC_PUMP_IN"], GPIO.OUT)
GPIO.setup(Pins["AWC_PUMP_OUT"], GPIO.OUT)
GPIO.setup(Pins["LED_PIN_R"], GPIO.OUT, initial = GPIO.HIGH) #high = leds off
GPIO.setup(Pins["LED_PIN_G"], GPIO.OUT, initial = GPIO.HIGH)
GPIO.setup(Pins["LED_PIN_B"], GPIO.OUT, initial = GPIO.HIGH)
p_R = GPIO.PWM(Pins["LED_PIN_R"], 2000)
p_G = GPIO.PWM(Pins["LED_PIN_G"], 2000)
p_B = GPIO.PWM(Pins["LED_PIN_B"], 2000)
p_R.start(0)
p_G.start(0)
p_B.start(0)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.FileHandler('/var/log/aquamonitor.log')
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(message)s',"%Y-%m-%d %H:%M:%S")
handler.setFormatter(formatter)
logger.addHandler(handler)
if not sys.stdout.isatty(): # if we are not running from console, redirect the stdout & err to files
sys.stdout = open('/var/log/aquamonitor_stdout.log', 'a')
sys.stderr = open('/var/log/aquamonitor_stderr.log','a')
def setup():
# Set the GPIO modes to BCM Numbering
GPIO.setmode(GPIO.BCM)
# Set LedPin's mode to output,
# and initial level to high (3.3v)
GPIO.setup(LedPin, GPIO.OUT, initial=GPIO.HIGH)
# Set BtnPin's mode to input,
# and pull up to high (3.3V)
GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Set up a falling detect on BtnPin,
# and callback function to swLed
GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=swLed)
# Define a callback function for button callback
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(SDI, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(RCLK, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(SRCLK, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(TouchPin, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.add_event_detect(TouchPin, GPIO.RISING, callback = randomISR, bouncetime = 20)
# Shift the data to 74HC595
def setup():
GPIO.setmode(GPIO.BCM) # Numbers GPIOs by physical location
GPIO.setup(SigPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set Pin's mode is input, and pull up to high level(3.3V)
GPIO.add_event_detect(SigPin, GPIO.RISING, callback=count) # wait for rasing
def main(switch=18, green=8, red=7):
GPIO.setmode(GPIO.BCM)
#GPIO.setup(switch, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(switch, GPIO.IN)
GPIO.setup(green, GPIO.OUT)
GPIO.setup(red, GPIO.OUT)
queue = Queue()
GPIO.add_event_detect(switch, GPIO.BOTH, callback=partial(interrupt_Event, queue), bouncetime=150)
start=False
try:
while True:
sleep(0.1)
if not queue.empty():
if not start:
start = queue.get()
GPIO.output(green, False)
GPIO.output(red, True)
else:
end = queue.get()
print_duration(start, end)
GPIO.output(green, True)
GPIO.output(red, False)
start=False
except (KeyboardInterrupt, SystemExit):
GPIO.cleanup()
print("\nQuit\n")
def main(switch=18, green=8, red=7):
GPIO.setmode(GPIO.BCM)
#GPIO.setup(switch, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(switch, GPIO.IN)
GPIO.setup(green, GPIO.OUT)
GPIO.setup(red, GPIO.OUT)
queue = Queue()
GPIO.add_event_detect(switch, GPIO.BOTH, callback=partial(interrupt_Event, queue), bouncetime=150)
running=True
start=datetime.now()
end=datetime.now()
try:
while running:
sleep(0.1)
if not queue.empty():
pin, state = queue.get()
if state == GPIO.LOW:
start = datetime.now()
GPIO.output(green, False)
GPIO.output(red, True)
elif state == GPIO.HIGH:
print_duration(start, datetime.now())
GPIO.output(green, True)
GPIO.output(red, False)
except (KeyboardInterrupt, SystemExit):
running=False
GPIO.cleanup()
print("\nQuit\n")
def __init__(self):
''' initialize the pin for the anemometer sensor '''
self.SENSOR_PIN = 4
self.count = 0
# tell the GPIO module that we want to use the chip's pin numbering scheme
GPIO.setmode(GPIO.BCM)
# setup pin as an input with pullup
GPIO.setup(self.SENSOR_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# threaded event, to detect voltage falling on anemometer
# bouncetime is in ms - edges within this time will be ignored
GPIO.add_event_detect(self.SENSOR_PIN, GPIO.FALLING, bouncetime=30)
self.starttime = time.time()
# deal with events by calling a function
GPIO.add_event_callback(self.SENSOR_PIN, self.inputEventHandler)
def main():
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.add_event_detect(pin, GPIO.BOTH, callback = _hook_switch_changed, bouncetime = 200)
while True:
time.sleep(100)
def main():
GPIO.setmode(GPIO.BCM)
GPIO.setup(reset_switch, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(hook_switch, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.add_event_detect(reset_switch, GPIO.BOTH, callback = _io_pulsed, bouncetime = 200)
GPIO.add_event_detect(hook_switch, GPIO.BOTH, callback = _io_pulsed, bouncetime = 200)
while True:
time.sleep(1000)