def leerAnalogico(): pinCLK = pins.pin(spiCLK , direction=Out) pinMISO = pins.pin(spiMISO , direction=In) pinMOSI = pins.pin(spiMOSI , direction=Out) pinCS = pins.pin(spiCS , direction=Out) pines = [pinCLK, pinMISO, pinMOSI, pinCS] try: for p in pines: p.open() pinCS.value = 1 pinCLK.value = 0 pinCS.value = 0 envio = inAnalogico envio |= 0x18 envio <<= 3 for i in range(5): if envio & 0x80: pinMOSI.value = 1 else: pinMOSI.value = 0 envio <<= 1 pinCLK.value = 1 pinCLK.value = 0 valor = 0 for i in range(12): pinCLK.value = 1 pinCLK.value = 0 valor <<= 1 if pinMISO.value: valor |= 0x1 pinCS.value = 1 valor /= 2 return valor finally: for p in pines: p.close()
def status_leds(state): disabled = pins.pin(0, direction=Out) enabled = pins.pin(7, direction=Out) dispath = str(disabled._pin_path())+"value" enpath = str(enabled._pin_path())+"value" for pinname, pinpath in {disabled:dispath,enabled:enpath}.items(): if not os.path.isfile(pinpath): pinname.open() if state == 0: dis = 1 else: dis = 0 with open(enpath, "+w") as f: f.write(str(state)+"\n") with open(dispath, "+w") as f: f.write(str(dis)+"\n")
def status_leds(state): disabled = pins.pin(0, direction=Out) enabled = pins.pin(7, direction=Out) dispath = str(disabled._pin_path()) + "value" enpath = str(enabled._pin_path()) + "value" for pinname, pinpath in {disabled: dispath, enabled: enpath}.items(): if not os.path.isfile(pinpath): pinname.open() if state == 0: dis = 1 else: dis = 0 with open(enpath, "+w") as f: f.write(str(state) + "\n") with open(dispath, "+w") as f: f.write(str(dis) + "\n")
def test_opens_and_closes_itself_when_used_as_a_context_manager(self): pin = pins.pin(0) with pin: pin.value with pytest.raises(IOError): pin.value
def tempOff(): pin = pins.pin(int(conf.config['Quick2Wire']['relay1OffPin']), direction = Out) logging.debug('Temp Library - Switch heating off') with pin: pin.value=1 sleep(0.05) pin.value=0 return "Off"
def ledon(): led = pins.pin(5, direction = Out) led_state = 1 with led: led.value=1 sleep(30) return "LED on";
def test_can_set_direction_on_construction(self): pin = pins.pin(0, Out) assert pin.direction == Out assert not os.path.exists(u"/sys/class/gpio/gpio17/direction") with pin: assert content_of(u"/sys/class/gpio/gpio17/direction") == u"out\n" assert pin.direction == Out
def test_mcp23017_interrupts(): i2c_int = pins.pin(I2C_INTERRUPT, direction=In) with i2c_int, I2CMaster() as i2c: chip = MCP23017(i2c) chip.reset(interrupt_polarity=1) check_interrupts(chip, i2c_int, Topology) check_interrupts(chip, i2c_int, inverse(Topology))
def ledonoff(): led = pins.pin(5, direction = Out) led_state = 1 with led: for v in cycle([1,0]): led.value=v sleep(0.5) return "s'allright";
def test_direction_and_value_of_pin_is_reset_when_closed(self): with pins.pin(0, Out) as pin: pin.value = 1 gpio_admin("export", 17, PullDown) try: assert content_of('/sys/class/gpio/gpio17/value') == '0\n' assert content_of('/sys/class/gpio/gpio17/direction') == 'in\n' finally: gpio_admin("unexport", 17)
def test_direction_and_value_of_pin_is_reset_when_closed(self): with pins.pin(0, Out) as pin: pin.value = 1 gpio_admin(u"export", 17, PullDown) try: assert content_of(u"/sys/class/gpio/gpio17/value") == u"0\n" assert content_of(u"/sys/class/gpio/gpio17/direction") == u"in\n" finally: gpio_admin(u"unexport", 17)
def test_direction_and_value_of_pin_is_reset_when_closed(self): with pins.pin(0, Out) as pin: pin.value = 1 gpio_admin(u"export", 17, PullDown) try: assert content_of(u'/sys/class/gpio/gpio17/value') == u'0\n' assert content_of(u'/sys/class/gpio/gpio17/direction') == u'in\n' finally: gpio_admin(u"unexport", 17)
def test_can_set_and_query_direction_of_pin_when_open(self): with pins.pin(0) as pin: pin.direction = Out assert pin.direction == Out assert content_of(u"/sys/class/gpio/gpio17/direction") == u"out\n" pin.direction = In assert pin.direction == In assert content_of(u"/sys/class/gpio/gpio17/direction") == u"in\n"
def test_setting_value_of_output_pin_writes_to_device_file(self): with pins.pin(0) as pin: pin.direction = Out pin.value = 1 assert pin.value == 1 assert content_of(u"/sys/class/gpio/gpio17/value") == u"1\n" pin.value = 0 assert pin.value == 0 assert content_of(u"/sys/class/gpio/gpio17/value") == u"0\n"
def test_setting_value_of_output_pin_writes_to_device_file(self): with pins.pin(0) as pin: pin.direction = Out pin.value = 1 assert pin.value == 1 assert content_of(u'/sys/class/gpio/gpio17/value') == u'1\n' pin.value = 0 assert pin.value == 0 assert content_of(u'/sys/class/gpio/gpio17/value') == u'0\n'
def test_pin_must_be_opened_before_use_and_is_unusable_after_being_closed(self): pin = pins.pin(0) with pytest.raises(IOError): pin.value pin.open() try: pin.value finally: pin.close() with pytest.raises(IOError): pin.value
def set_pin(pin_nr, value): """ Write HIGH or LOW to GPIO pin. :param pin_nr: BOARD pin number. :param vaue: Value. """ pin = pins.pin(pin_nr, direction=Out) with pin: pin.value = int(value) log.debug('Wrote %d to pin %d.' % (value, pin_nr)) return pin.value
def take_control(self): """ Custom implementation of take_control method. Takes control if the current behavior is IdleBehavior and the rising edge of input pin is detected. """ result = False if isinstance(self.engine().current_behavior(), IdleBehavior): with pins.pin(7, direction=In) as pin: if pin.value == 0: self._can_take_control = True #to detect rising edge elif self._can_take_control == True and pin.value == 1: self._can_take_control = False result = True return result
def run(self): """ Run the PWM pattern into a background thread. This function should not be called outside of this class. """ pin = pins.pin(self.gpioPin, direction=Out) with pin: while self.toTerminate == False: if self.dutyCycle > 0: pin.value = 1 time.sleep(self.dutyCycle * self.sliceTime) if self.dutyCycle < self.maxCycle: pin.value = 0 time.sleep((self.maxCycle - self.dutyCycle) * self.sliceTime) self.terminated = True
def should_stop(self): """ Custom implementation of should_stop method. Stops the behavior if stop() method is called or if rising edge of input pin is detected. """ result = Behavior.should_stop(self) if result == True: return True with pins.pin(7, direction=In) as pin: if pin.value == 0: self._can_stop = True #to detect rising edge elif self._can_stop == True and pin.value == 1: result = True self._can_stop == False return result
def run(self): """ Run the PWM pattern into a background thread. This function should not be called outside of this class. """ pin = pins.pin(self.gpioPin, direction=Out) with pin: while self.toTerminate == False: if self.dutyCycle > 0: pin.value = 1 time.sleep(self.dutyCycle * self.sliceTime) if self.dutyCycle < self.maxCycle: pin.value = 0 time.sleep( (self.maxCycle - self.dutyCycle) * self.sliceTime) self.terminated = True
import time config = ConfigParser.RawConfigParser() config.read('ls.cfg') dbhost = config.get('db','host') dbuser = config.get('db','user') dbpass = config.get('db','pass') dbdatabase = config.get('db','database') #GPIO.setmode(GPIO.BCM) #wiringpi2.wiringPiSetupGpio() from quick2wire.gpio import pins, In, Out # Pin Definitons: #r1Pin = 14 # Broadcom pin 14 (P1 pin 8) #r2Pin = 15 # Broadcom pin 15 (P1 pin 10) r1Pin = pins.pin(3, direction=Out) r2Pin = pins.pin(4, direction=Out) with r1Pin: r1Pin.value = 0 print('r1Pin set to out, value 0') time.sleep(2) Print('exiting') with r2Pin: r2Pin.value = 0 print('r1Pin set to out, value 0') time.sleep(2) Print('exiting') #GPIO.setup(r1Pin,GPIO.OUT) #GPIO.setup(r2Pin,GPIO.OUT) #wiringpi2.pinMode(r1Pin,1) # Set pin 6 to 1 ( OUTPUT ) #wiringpi2.pinMode(r2Pin,1) # Set pin 6 to 1 ( OUTPUT )
#!/usr/bin/env python3 from time import sleep from quick2wire.gpio import pins, Out, In button = pins.pin(0, direction=In) runled = pins.pin(1, direction=Out) led1 = pins.pin(2, direction=Out) led2 = pins.pin(3, direction=Out) led3 = pins.pin(4, direction=Out) print("go") with button, runled, led1, led2, led3: while True: if button.value == 1: runled.value = 1 led1.value = 1 led2.value = 1 led3.value = 1 print("started") sleep(5) elif button.value != 1: runled.value = 0 led3.value = 0 sleep(2) led2.value = 0 sleep(2) led1.value = 0 sleep(2) print("stopped", end='\r')
from zocp import ZOCP import logging if __name__ == '__main__': zl = logging.getLogger("zocp") zl.setLevel(logging.DEBUG) z = ZOCP("ZOCP-GPIO") z.register_bool("myBool", True, 'rwe') z.register_float("myFloat", 2.3, 'rws', 0, 5.0, 0.1) z.register_int('myInt', 10, access='rwes', min=-10, max=10, step=1) z.register_percent('myPercent', 12, access='rw') z.register_vec2f('myVec2', [0,0], access='rwes') # register pins pin1 = pins.pin(0, direction=In, interrupt=Rising) pin2 = pins.pin(1, direction=In, interrupt=Falling) def handle_pin(pin): logging.debug("handle pin {0}".format(pin)) with pin: logging.debug("pin {0}:{1}".format(pin, pin.value) poller = zmq.Poller() poll.register(z.inbox, zmq.POLLIN) poll.register(pin1.fileno(), zmq.POLLIN) poll.register(pin2.fileno(), zmq.POLLIN) z.start() z.running = True #is this needed? while True: try:
def test_cannot_get_a_pin_with_an_invalid_index(self): with pytest.raises(IndexError): pins.pin(-1) with pytest.raises(IndexError): pins.pin(len(pins))
#!/usr/bin/python3 ## Script to run the pump every 12 hours, but first check the status of the pump ## in weather_data.db, if its 1 run the pump for specified amount of time. import sqlite3 import time from quick2wire.gpio import pins, Out relay = pins.pin(1, direction=Out) pump_led = pins.pin(5, direction=Out) db_file = "/home/pi/python/waterer/weather_data.db" ## Log Writer def writelog(text): """ Append a line to the logfile if there are any unusual activities used by the other methods when necessary """ logfile = open("/home/pi/python/waterer/water.log", "a") logfile.write(text + "\n") logfile.close() ## Check the latest entry in the db, if the pump_status = 1 or 0 def pump_status(): db_conn = sqlite3.connect(db_file) c = db_conn.cursor() c.execute("select max(ID), PUMP_STATUS from weather")
from quick2wire.gpio import pins,In import quick2wire.i2c as i2c from time import sleep direccionArduino = 0x8 try: while True: with pins.pin(0,direction=In) as boton: valor = boton.value with i2c.I2CMaster() as bus: transaccion = i2c.writing_bytes(direccionArduino,boton.value) bus.transaction(transaccion) print('Envio ... ',end='') print(valor) sleep(0.2) except KeyboardInterrupt: pass
def test_exports_gpio_device_to_userspace_when_opened_and_unexports_when_closed( self): with pins.pin(0) as pin: assert os.path.exists(u'/sys/class/gpio/gpio17/value') assert not os.path.exists(u'/sys/class/gpio/gpio17/value')
#!/usr/bin/python3 ## Script to run the pump every 12 hours, but first check the status of the pump ## in weather_data.db, if its 1 run the pump for specified amount of time. import sqlite3 import time from quick2wire.gpio import pins, Out relay = pins.pin(1, direction=Out) pump_led = pins.pin(5, direction=Out) db_file = "/home/pi/python/waterer/weather_data.db" ## Log Writer def writelog(text): """ Append a line to the logfile if there are any unusual activities used by the other methods when necessary """ logfile = open("/home/pi/python/waterer/water.log","a") logfile.write(text+"\n") logfile.close() ## Check the latest entry in the db, if the pump_status = 1 or 0 def pump_status(): db_conn = sqlite3.connect(db_file) c = db_conn.cursor() c.execute("select max(ID), PUMP_STATUS from weather") pump_stat = c.fetchone()[1] c.close
epoll = select.epoll() with pin1: epoll.register(pin1,select.EPOLLIN | select.EPOLLET) print("") while True: events = epoll.poll() for fileno, event in events: if fileno == pin1.fileno(): handle_pin_1() #ISR for GPIO interrupt def handle_pin_1(): print("Interrupt on GPIO has occured") #define global variables - used across threads SendObj = NRF24() #Start class pin1 = pins.pin(5,direction=In,interrupt=Rising) #define GPIO 18?? pin for interrupt if __name__ == "__main__": #pin1 = pins.pin(5,direction=In,interrupt=Rising) #define GPIO 18?? pin for interrupt #epoll = select.epoll() #print("Starting threads") t1 = Thread(target = handleInterrup) t1.start() rxtx = input("Input option: \n\rrx - receive\n\rtx - transmit\n\rr0 - MASTER\n\r") try: if rxtx == 'tx':
#!/usr/bin/env python3 import sys from quick2wire.gpio import pins, Out from time import sleep from time import time start = time() DEBUG = 0 led1 = pins.pin(2, direction=Out) led2 = pins.pin(3, direction=Out) led3 = pins.pin(4, direction=Out) def PHP(phpvalue): if phpvalue == 1: led1.value = 1 elif phpvalue == 2: led2.value = 1 else: led3.value = 1 print ("led%s on" % phpvalue) print (led1.value,led2.value,led3.value) if DEBUG == 1: sleep(2) def Main(): with led1, led2, led3: status1 = int(sys.argv[1]) if len(sys.argv) >= 2 else "error"
epoll.register(pin1, select.EPOLLIN | select.EPOLLET) print("") while True: events = epoll.poll() for fileno, event in events: if fileno == pin1.fileno(): handle_pin_1() #ISR for GPIO interrupt def handle_pin_1(): print("Interrupt on GPIO has occured") #define global variables - used across threads SendObj = NRF24() #Start class pin1 = pins.pin(5, direction=In, interrupt=Rising) #define GPIO 18?? pin for interrupt if __name__ == "__main__": #pin1 = pins.pin(5,direction=In,interrupt=Rising) #define GPIO 18?? pin for interrupt #epoll = select.epoll() #print("Starting threads") t1 = Thread(target=handleInterrup) t1.start() rxtx = input( "Input option: \n\rrx - receive\n\rtx - transmit\n\rr0 - MASTER\n\r") try: if rxtx == 'tx': print("Starting Transmitter..\n") SendObj.init() #OK
clock.value = 1 clock.value = 0 #indico que finalizo el envío de nuevos valores latchPin.value = 1 # un pequeño retraso entre estados para mantener los leds en esa iluminacion sleep(0.5) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--tipoMovimiento',help='1 para izquierda<->derecha. 2 para simetría. Valor por defecto 1.') args = parser.parse_args() latchPin = pins.pin(1,direction=Out) clockPin = pins.pin(4,direction=Out) dataPin = pins.pin(5,direction=Out) pines = [latch,clock,data] for pin in pines: pin.open() try: if args.tipoMovimiento=='2': while True: for i in range(7,-1,-1): shiftOut(latchPin,dataPin,clockPin,'MSBFIRST',2**i) else: while True:
# Setup Quick2Wire import quick2wire.i2c as i2c from quick2wire.gpio import pins, Out from quick2wire.parts.pcf8591 import * # Stuff for collecting online data from urllib.request import Request from urllib.request import urlopen from urllib.error import URLError from urllib.error import HTTPError # Custom module for drawing the graphs from create_graphs import CreateGraphs # setup the quick2wire pins power = pins.pin(3, direction=Out) db_file = "/home/pi/python/waterer/weather_data.db" def status_leds(state): disabled = pins.pin(0, direction=Out) enabled = pins.pin(7, direction=Out) dispath = str(disabled._pin_path()) + "value" enpath = str(enabled._pin_path()) + "value" for pinname, pinpath in {disabled: dispath, enabled: enpath}.items(): if not os.path.isfile(pinpath): pinname.open() if state == 0: dis = 1
def test_exports_gpio_device_to_userspace_when_opened_and_unexports_when_closed(self): with pins.pin(0) as pin: assert os.path.exists(u"/sys/class/gpio/gpio17/value") assert not os.path.exists(u"/sys/class/gpio/gpio17/value")
# GPIO PIN DEFINES (using quick2wire GPIO numbers) # NUMBER OF STATIONS num_stations = 16 # STATION BITS values = [0]*num_stations # In case things don't close correctly, we'll just clear the pins and be ok if the command yields errors pinsToClear = [4, 17, 21, 22] for p in pinsToClear: call(['gpio-admin', 'unexport', str(p)]) pin_sr_clk = pins.pin(7, Out) # Pin 7 (GPIO 4) pin_sr_noe = pins.pin(0, Out) # Pin 11 (GPIO 17) pin_sr_dat = pins.pin(2, Out) # Pin 13 (GPIO 21) # May need to be changed with rev.2 board pin_sr_lat = pins.pin(3, Out) # Pin 15 (GPIO 22) pin_sr_clk.open() pin_sr_lat.open() pin_sr_noe.open() pin_sr_dat.open() def enableShiftRegisterOutput(): pin_sr_noe.value = 0 def disableShiftRegisterOutput():
from quick2wire.gpio import pins, Out pins = [pins.pin(i, Out) for i in range(8)] for p in pins: p.close()
#|| ============ #|| #|| This example extends the [blink program](blink) to read from a #|| GPIO input pin connected to a push-button. The LED will only #|| blink while you are holding the button down. from itertools import cycle from time import sleep #| [5] You must import the GPIO pins and direction constants In and #| Out from quick2wire.gpio before you can use them from quick2wire.gpio import pins, In, Out #|. #| [4] Get hold of the input and output pins from the bank of GPIO #| pins. button = pins.pin(0, direction=In) led = pins.pin(1, direction=Out) #|. #| [6] The with statement acquires the button and led pins and ensures #| that they are always released when the body of the statement #| finishes, whether successfully or by an exception being thrown. with button, led: #|. print("ready") #| [1] This is the core of the program: an infinite loop that #| reads from and writes to the GPIO pins connected to the button #| and LED. Each time round the loop, _blink_state_ alternates #| between 1 (voltage high) and 0 (voltage low). for blink_state in cycle([1,0]): #| [2] Read the state of the button pin multiply it with