def diag(): print("Revision:", GPIO.RPI_INFO['REVISION']) print("Version:", GPIO.VERSION) print('Board mode', nrmodes[GPIO.getmode()]) GPIO.setmode(GPIO.BCM) print('Board mode', nrmodes[GPIO.getmode()]) for i in range(2,28): pm = pinmodes[GPIO.gpio_function(i)] if pm == 'IN': GPIO.setup(i, GPIO.IN) print('Pin {:2d} {:4s} {} {}'.format(i, pm, GPIO.input(i), tctl[i])) else: print('Pin {:2d} {:6s} {}'.format(i, pm, tctl[i]))
def priorityLoop(): #This is the main function. It is an infinite loop that checks priority Based on what the priority is, it does stuff. global priority while True: checkTxt() #Check for updates if (priority == 0): try: manual() except IOError: print("Error in manual") except KeyboardInterrupt: print("\nCaught KeyboardInterrupt, cleaning GPIO pins.\nGPIO mode before cleanup: "+str(GPIO.getmode())) GPIO.cleanup() print("GPIO mode after cleanup: "+str(GPIO.getmode())+"\nExiting Now. Thank you for your patience.") sys.exit() elif (priority == 1): try: light() except IOError: print("Error in temperature") except KeyboardInterrupt: print("\nCaught KeyboardInterrupt, cleaning GPIO pins.\nGPIO mode before cleanup: "+str(GPIO.getmode())) GPIO.cleanup() print("GPIO mode after cleanup: "+str(GPIO.getmode())+"\nExiting Now. Thank you for your patience.") sys.exit() elif (priority == 2): try: schedule() except IOError: print("Error in schedule") except KeyboardInterrupt: print("\nCaught KeyboardInterrupt, cleaning GPIO pins.\nGPIO mode before cleanup: "+str(GPIO.getmode())) GPIO.cleanup() print("GPIO mode after cleanup: "+str(GPIO.getmode())+"\nExiting Now. Thank you for your patience.") sys.exit() else: print("The priority is not 0, 1 or 2. It is",priority)
def __init__(self, out_channels=None, in_channels=None): logger.info('RPI board info: %s' % GPIO.RPI_INFO) GPIO.setmode(GPIO.BCM) if GPIO.getmode() != GPIO.BCM: logger.warn('Please note, could not set GPIO Mode to GPIO.BCM, but %s; This might create troubles around the board numbering convention' % GPIO.getmode()) #chan_list = [11,12] #GPIO.setup(channel, GPIO.OUT) #GPIO.setup(channel, GPIO.OUT, initial=GPIO.HIGH) self.out_channels = out_channels if out_channels is not None: try: logger.info('Initializing out channels %s' % out_channels) GPIO.setup(out_channels, GPIO.OUT) except: logger.error('Unexpected error: %s' % sys.exc_info()[0]) raise else: logger.warning('No output channels are initialized.') if in_channels is not None: logger.warning('Input channels are initialized, but input is not yet supported.') else: logger.warning('No input channels are initialized.')
def testSimultaniously2(self): control.clearAllR1() control.clearAllR2() if (GPIO.getmode() != 11): GPIO.setmode(GPIO.BCM) GPIO.setup(PINS.PIN1, GPIO.OUT, initial=GPIO.HIGH) GPIO.setup(PINS.PIN2, GPIO.OUT, initial=GPIO.LOW) now = round(time.time()) control.autoSwitchRelay( wordsOn='N/A', wordsOff='N/A', reversed=False, epOn=now + 16, epOff=now + 20, relay='relay1' ) control.autoSwitchRelay( wordsOn='N/A', wordsOff='N/A', reversed=True, epOn=now + 20, epOff=now + 16, relay='relay2' ) time.sleep(18) self.assertEqual(GPIO.input(PINS.PIN1), GPIO.LOW) self.assertEqual(GPIO.input(PINS.PIN2), GPIO.HIGH) time.sleep(5) self.assertEqual(GPIO.input(PINS.PIN1), GPIO.HIGH) self.assertEqual(GPIO.input(PINS.PIN2), GPIO.LOW) control.clearAllR1() control.clearAllR2() PINS.clean()
def init(): GPIO.setmode(GPIO.BCM) print "GPIO mode: ", GPIO.getmode(), "(BCM = ", GPIO.BCM, ", BOARD = ", GPIO.BOARD, ")" print "GPIO RPI info:", GPIO.RPI_INFO print "GPIO version: ", GPIO.VERSION GPIO.setup(18, GPIO.OUT, initial=GPIO.HIGH) GPIO.setup(17, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def __init__(self, dht11Port): self.channel = dht11Port self.last_value = None if not GPIO.getmode(): raise GPIONotInitializeError() print("Starting DHT11 sensor")
def init_led(): if led_enabled: gpio.setmode(gpio.BOARD) gpio.setwarnings(False) assert gpio.getmode() == gpio.BOARD gpio.setup(light_1, gpio.OUT) gpio.setup(light_2, gpio.OUT)
def testDigitalAnalogue(self): control.clearAllR1() control.clearAllR2() if (GPIO.getmode() != 11): GPIO.setmode(GPIO.BCM) GPIO.setup(PINS.PIN1, GPIO.OUT, initial=GPIO.HIGH) GPIO.setup(PINS.PIN2, GPIO.OUT, initial=GPIO.HIGH) now = round(time.time()) control.autoSwitchRelay( wordsOn='N/A', wordsOff='N/A', reversed=False, epOn=now + 10, epOff=now + 45, relay='relay1' ) control.autoSwitchRelay( wordsOn='N/A', wordsOff='N/A', reversed=False, epOn=now + 10, epOff=now + 20, relay='relay2' ) control.autoSwitchRelay( wordsOn='N/A', wordsOff='N/A', reversed=False, epOn=now + 25, epOff=now + 35, relay='relay2' ) control.autoSwitchRelay( wordsOn='N/A', wordsOff='N/A', reversed=False, epOn=now + 40, epOff=now + 45, relay='relay2' ) time.sleep(13) self.assertEqual(GPIO.input(PINS.PIN1), GPIO.LOW) self.assertEqual(GPIO.input(PINS.PIN2), GPIO.LOW) time.sleep(10) self.assertEqual(GPIO.input(PINS.PIN1), GPIO.LOW) self.assertEqual(GPIO.input(PINS.PIN2), GPIO.HIGH) time.sleep(5) self.assertEqual(GPIO.input(PINS.PIN1), GPIO.LOW) self.assertEqual(GPIO.input(PINS.PIN2), GPIO.LOW) time.sleep(10) self.assertEqual(GPIO.input(PINS.PIN1), GPIO.LOW) self.assertEqual(GPIO.input(PINS.PIN2), GPIO.HIGH) time.sleep(5) self.assertEqual(GPIO.input(PINS.PIN1), GPIO.LOW) self.assertEqual(GPIO.input(PINS.PIN2), GPIO.LOW) time.sleep(8) self.assertEqual(GPIO.input(PINS.PIN1), GPIO.HIGH) self.assertEqual(GPIO.input(PINS.PIN2), GPIO.HIGH) control.clearAllR1() control.clearAllR2() PINS.clean()
def __init__(self): if GPIO.getmode() != GPIO.BOARD: GPIO.setmode(GPIO.BOARD) # Pin for the solenoid release gate self.gateOutputPin = 19 # Setup GPIO pin GPIO.setup(self.gateOutputPin, GPIO.OUT)
def on_press(self): super(GPIOPressButton, self).on_press() if (self.PWM is None) or (not self.gpio_configured): if GPIO.getmode() is None: GPIO.setmode(GPIO.BOARD) self.PWM = GPIO.PWM(int(self.pin), 3000) self.gpio_configured = True self.PWM.start(25) return True
def testReaper(self): control.clearAllR1() control.clearAllR2() if (GPIO.getmode() != 11): GPIO.setmode(GPIO.BCM) GPIO.setup(PINS.PIN1, GPIO.OUT, initial=GPIO.HIGH) GPIO.setup(PINS.PIN2, GPIO.OUT, initial=GPIO.HIGH) now = round(time.time()) control.autoSwitchRelay( wordsOn='N/A', wordsOff='N/A', reversed=False, epOn=now + 10, epOff=now + 30, relay='relay1' ) control.autoSwitchRelay( wordsOn='N/A', wordsOff='N/A', reversed=False, epOn=now + 25, epOff=now + 40, relay='relay2' ) control.reaper.start() self.assertEqual(len(control.RELAY1_TIMERS), 2) self.assertEqual(len(control.RELAY1_APPOINTMENTS), 1) self.assertEqual(len(control.RELAY2_TIMERS), 2) self.assertEqual(len(control.RELAY2_APPOINTMENTS), 1) time.sleep(19) self.assertEqual(len(control.RELAY1_TIMERS), 1) self.assertEqual(len(control.RELAY1_APPOINTMENTS), 1) self.assertEqual(len(control.RELAY2_TIMERS), 2) self.assertEqual(len(control.RELAY2_APPOINTMENTS), 1) time.sleep(18) self.assertEqual(len(control.RELAY1_TIMERS), 0) self.assertEqual(len(control.RELAY1_APPOINTMENTS), 0) self.assertEqual(len(control.RELAY2_TIMERS), 1) self.assertEqual(len(control.RELAY2_APPOINTMENTS), 1) time.sleep(15) self.assertEqual(len(control.RELAY1_TIMERS), 0) self.assertEqual(len(control.RELAY1_APPOINTMENTS), 0) self.assertEqual(len(control.RELAY2_TIMERS), 0) self.assertEqual(len(control.RELAY2_APPOINTMENTS), 0) control.clearAllR1() control.clearAllR2() PINS.clean()
def testRemoveSingle2(self): control.clearAllR1() control.clearAllR2() if (GPIO.getmode() != 11): GPIO.setmode(GPIO.BCM) GPIO.setup(PINS.PIN1, GPIO.OUT, initial=GPIO.HIGH) GPIO.setup(PINS.PIN2, GPIO.OUT, initial=GPIO.HIGH) now = round(time.time()) control.autoSwitchRelay( wordsOn='N/A', wordsOff='N/A', reversed=False, epOn=now + 10, epOff=now + 20, relay='relay1' ) ID = control.RELAY1_APPOINTMENTS[0].ID control.autoSwitchRelay( wordsOn='N/A', wordsOff='N/A', reversed=False, epOn=now + 25, epOff=now + 35, relay='relay1' ) control.autoSwitchRelay( wordsOn='N/A', wordsOff='N/A', reversed=False, epOn=now + 3600, epOff=now + 7200, relay='relay2' ) time.sleep(15) self.assertEqual(GPIO.input(PINS.PIN1), GPIO.LOW) self.assertEqual(GPIO.input(PINS.PIN2), GPIO.HIGH) control.remove_singleR1(str(ID)) self.assertEqual(GPIO.input(PINS.PIN1), GPIO.LOW) self.assertEqual(GPIO.input(PINS.PIN2), GPIO.HIGH) time.sleep(7) self.assertEqual(GPIO.input(PINS.PIN1), GPIO.LOW) self.assertEqual(GPIO.input(PINS.PIN2), GPIO.HIGH) time.sleep(6) self.assertEqual(GPIO.input(PINS.PIN1), GPIO.LOW) self.assertEqual(GPIO.input(PINS.PIN2), GPIO.HIGH) time.sleep(10) self.assertEqual(GPIO.input(PINS.PIN1), GPIO.HIGH) self.assertEqual(GPIO.input(PINS.PIN2), GPIO.HIGH) control.clearAllR1() control.clearAllR2() PINS.clean()
def __init__(self, addr, sda_pin=3, scl_pin=5): self.addr = addr self.sda_pin = sda_pin self.scl_pin = scl_pin if gp.getmode() != 10: gp.setmode(gp.BOARD) gp.setup(self.sda_pin, gp.OUT) gp.setup(self.scl_pin, gp.OUT) gp.output(self.sda_pin, 1) gp.output(self.scl_pin, 1)
def testInit(self): PINS.init(PINS.PIN1, PINS.PIN2) BCM = 11 # check if the board numeration mode matches BCM mode self.assertEqual(BCM, GPIO.getmode()) # check if both pins are raised (OFF state) after initialiazation self.assertEqual(GPIO.HIGH, GPIO.input(PINS.PIN1)) self.assertEqual(GPIO.HIGH, GPIO.input(PINS.PIN2)) PINS.clean()
def getStatus(relay): # to avoid error if refresh is done # while server is shutting down # check if mode is still 11 (BCM=11) if (GPIO.getmode() != 11): GPIO.setmode(GPIO.BCM) if(PINS.getState(relay) == 0): return "on" else: return "off"
def __init__(self, dataPin=4): """ Create the object to talk to the LED Keyword arguments: dataPin - the pin that is used to talk to the led """ self.dataPin = dataPin if GPIO.getmode() == -1: GPIO.setmode(GPIO.BCM) GPIO.setup(self.dataPin, GPIO.OUT)
def __init__(self, pin): ''' Initializes the pin pin - pin number to read ''' tmp = GPIO.getmode() if tmp == GPIO.BCM: raise RuntimeError("Incompatible GPIO pin enumeration scheme") GPIO.setmode(GPIO.BOARD) self.pin = pin GPIO.setup(self.pin, GPIO.OUT,initial=GPIO.HIGH)
def testState(self): if (GPIO.getmode() != 11): GPIO.setmode(GPIO.BCM) GPIO.setup(PINS.PIN1, GPIO.OUT, initial=GPIO.HIGH) GPIO.setup(PINS.PIN2, GPIO.OUT, initial=GPIO.LOW) actual = control.state() expected1 = '{"relay2": "on", "relay1": "off"}' expected2 = '{"relay1": "off", "relay2": "on"}' self.assertTrue((actual == expected1) or (actual == expected2)) PINS.clean()
def _init_gpio(self): """ Sets gpio for controlling pins connected to an RGB led. No assumptions are made about the pin numbering mode. The mode is first checked and set to BCM if found undefined. So, if you wish to use BOARD numbering mode, then set this mode prior to instantiating a RGB_led class. """ GPIO.setwarnings(False) if GPIO.getmode() is None: GPIO.setmode(GPIO.BCM) GPIO.setup(self._rgb, GPIO.OUT)
def testGetState(self): if (GPIO.getmode() != 11): GPIO.setmode(GPIO.BCM) GPIO.setup(PINS.PIN1, GPIO.OUT, initial=GPIO.HIGH) # check if the correct state of the PIN is returned self.assertEqual(GPIO.HIGH, PINS.getState(PINS.PIN1)) GPIO.setup(PINS.PIN2, GPIO.OUT, initial=GPIO.LOW) # check if the correct state of the PIN is returned self.assertEqual(GPIO.LOW, PINS.getState(PINS.PIN2)) PINS.clean()
def testStatus(self): if (GPIO.getmode() != 11): GPIO.setmode(GPIO.BCM) GPIO.setup(PINS.PIN1, GPIO.OUT, initial=GPIO.HIGH) # check if the correct status of the relay is returned self.assertEqual('off', control.getStatus(PINS.PIN1)) GPIO.setup(PINS.PIN2, GPIO.OUT, initial=GPIO.LOW) # check if the correct status of the relay is returned self.assertEqual('on', control.getStatus(PINS.PIN2)) PINS.clean()
def on_press(self): # work around widget properties not being set # when __init__() is called if not self.gpio_configured: if GPIO.getmode() is None: GPIO.setmode(GPIO.BOARD) print("setting up pin {}".format(self.pin)) if self.pull_up_down is not None: GPIO.setup(self.pin, self.direction, pull_up_down=self.pull_up_down) else: GPIO.setup(self.pin, self.direction) if self.gpio_value is not None: GPIO.output(self.pin, self.gpio_value) self.gpio_configured = True return False
def testSwitch(self): if (GPIO.getmode() != 11): GPIO.setmode(GPIO.BCM) GPIO.setup(PINS.PIN1, GPIO.OUT, initial=GPIO.HIGH) PINS.switchState(PINS.PIN1, GPIO.LOW) # check if PIN's state matches the expected after the switch self.assertEqual(GPIO.LOW, GPIO.input(PINS.PIN1)) GPIO.setup(PINS.PIN1, GPIO.OUT, initial=GPIO.LOW) # check if PIN's state matches the expected after the switch PINS.switchState(PINS.PIN1, GPIO.HIGH) self.assertEqual(GPIO.HIGH, GPIO.input(PINS.PIN1)) PINS.clean()
def __init__(self, dataPin=4, minVal=0, maxVal=11): """ Create the object to talk to the jack Keyword arguments: dataPin - the pin that is used to detect a high or low voltage minVal - the value that will indicate off maxVal - the value that will indicate on """ self.dataPin = dataPin if GPIO.getmode() == -1: GPIO.setmode(GPIO.BCM) GPIO.setup(self.dataPin, GPIO.IN) self.__MIN = minVal self.__MAX = maxVal
def write(pin, state): """ Write output GPIO pin to state MAKE SURE pin is setup before use @param int pin @param bool state """ if( GPIO.getmode() == None ): return False # print("GPIO WRITE", pin, state, gpioState) gpioState = GPIO.HIGH if state == True or state == 1 or state == "1" else GPIO.LOW if( pwmPins.get(pin) == None ): GPIO.output(pin, gpioState) # pwmPins.get(pin).stop() else: GPIO.output(pin, gpioState) return
def update(self, dt): # work around widget properties not being set # when __init__() is called if not self.gpio_configured: if GPIO.getmode() is None: GPIO.setmode(GPIO.BOARD) print("setting up pin {}".format(self.pin)) if self.pull_up_down is not None: GPIO.setup(self.pin, self.direction, pull_up_down=self.pull_up_down) else: GPIO.setup(self.pin, self.direction) if self.gpio_value is not None: GPIO.output(self.pin, self.gpio_value) self.gpio_configured = True if GPIO.input(self.pin): self.state = "normal" else: self.state = "down"
def testExpired(self): if (GPIO.getmode() != 11): GPIO.setmode(GPIO.BCM) appointmentX = control.Appointment( 'N/A', 'N/A', 100, 150, False, 'code' ) self.assertTrue(appointmentX.expired()) future = round(time.time()) + 5 appointmentY = control.Appointment( 'N/A', 'N/A', 150, future, False, 'code' ) self.assertFalse(appointmentY.expired()) time.sleep(7) self.assertTrue(appointmentY.expired()) control.clearAllR1() control.clearAllR2()
def on_value(self, instance, value): if (self.PWM is None) or (not self.gpio_configured): # work around widget properties not being set # when __init__() is called if GPIO.getmode() is None: GPIO.setmode(GPIO.BOARD) if self.pin is None: return True print("setting up pin {}".format(self.pin)) if self.pull_up_down is not None: GPIO.setup(self.pin, self.direction, pull_up_down=self.pull_up_down) else: GPIO.setup(self.pin, self.direction) self.PWM = GPIO.PWM(int(self.pin), int(self.value)) self.PWM.start(50) self.gpio_configured = True self.PWM.ChangeFrequency(int(self.value)) return True
def testManualSwitch(self): if (GPIO.getmode() != 11): GPIO.setmode(GPIO.BCM) GPIO.setup(PINS.PIN1, GPIO.OUT, initial=GPIO.HIGH) GPIO.setup(PINS.PIN2, GPIO.OUT, initial=GPIO.LOW) control.relay1('on') control.relay2('off') self.assertEqual(GPIO.input(PINS.PIN1), GPIO.LOW) self.assertTrue(GPIO.input(PINS.PIN2), GPIO.HIGH) control.relay1('off') control.relay2('on') time.sleep(3) self.assertEqual(GPIO.input(PINS.PIN1), GPIO.HIGH) self.assertEqual(GPIO.input(PINS.PIN2), GPIO.LOW) PINS.clean()
def testHeterogenousOverlap(self): control.clearAllR1() control.clearAllR2() if (GPIO.getmode() != 11): GPIO.setmode(GPIO.BCM) GPIO.setup(PINS.PIN1, GPIO.OUT, initial=GPIO.HIGH) GPIO.setup(PINS.PIN2, GPIO.OUT, initial=GPIO.HIGH) now = round(time.time()) control.autoSwitchRelay( wordsOn='N/A', wordsOff='N/A', reversed=False, epOn=now + 10, epOff=now + 30, relay='relay1' ) control.autoSwitchRelay( wordsOn='N/A', wordsOff='N/A', reversed=True, epOn=now + 20, epOff=now + 15, relay='relay1' ) time.sleep(12) self.assertEqual(GPIO.input(PINS.PIN1), GPIO.LOW) time.sleep(5) self.assertEqual(GPIO.input(PINS.PIN1), GPIO.HIGH) time.sleep(8) self.assertEqual(GPIO.input(PINS.PIN1), GPIO.LOW) time.sleep(7) self.assertEqual(GPIO.input(PINS.PIN1), GPIO.HIGH) control.clearAllR1() control.clearAllR2() PINS.clean()
operation = sys.argv[1].lower() if operation != "on" and operation != "off": print("Usage: " + sys.argv[0] + " <on|off>") sys.exit(-1) # reference on initializing u-blox LARA-R203 on Seeed Raspberry PI LTE Hat # https://github.com/Seeed-Studio/ublox_lara_r2_pi_hat/blob/master/test/test01.py # https://github.com/Seeed-Studio/ublox_lara_r2_pi_hat/blob/master/ublox_lara_r2/ublox_lara_r2.py POWER_PIN = 29 # GPIO 5 RESET_PIN = 31 # GPIO 6 GPIO.setwarnings(False) if GPIO.getmode() == None: GPIO.setmode(GPIO.BOARD) if GPIO.getmode() == GPIO.BCM: POWER_PIN = 5 RESET_PIN = 6 GPIO.setup([POWER_PIN, RESET_PIN], GPIO.OUT) GPIO.output([POWER_PIN, RESET_PIN], GPIO.LOW) if operation == "on": GPIO.output([POWER_PIN, RESET_PIN], GPIO.HIGH) else: GPIO.output([POWER_PIN], GPIO.HIGH) time.sleep(1)
def getmode(self): if self.importlib is not None: return GPIO.getmode()
#!/usr/bin/python try: import RPi.GPIO as GPIO 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" ) # Pin number relay_pin = 7 GPIO.setwarnings(False) # Different pin numbering depending on board mode = GPIO.getmode() # Set the numbering mode GPIO.setmode(mode) # Setup as output relay component GPIO.setup(relay_pin, GPIO.OUT) # Grab value from geofence.py and if it is true, then send a signal def cut_down(): GPIO.output(relay_pin, 0) time.sleep(.1) GPIO.output(relay_pin, 1) GPIO.cleanup()
def __init__(self, gpio_pin): self.channel = int(gpio_pin) if not GPIO.getmode(): GPIO.setmode(GPIO.BCM) GPIO.setup(self.channel, GPIO.OUT)
def runTest(self): # Test mode not set (BOARD or BCM) exception with self.assertRaises(RuntimeError) as e: GPIO.setup(LED_PIN, GPIO.OUT) self.assertEqual( str(e.exception), 'Please set pin numbering mode using GPIO.setmode(GPIO.BOARD) or GPIO.setmode(GPIO.BCM)' ) # Test trying to change mode after it has been set GPIO.setmode(GPIO.BCM) with self.assertRaises(ValueError) as e: GPIO.setmode(GPIO.BOARD) GPIO.setup(LED_PIN_BCM, GPIO.IN) GPIO.cleanup() # Test getmode() self.assertEqual(GPIO.getmode(), GPIO.UNKNOWN) GPIO.setmode(GPIO.BCM) self.assertEqual(GPIO.getmode(), GPIO.BCM) GPIO.setup(LED_PIN_BCM, GPIO.IN) GPIO.cleanup() GPIO.setmode(GPIO.BOARD) self.assertEqual(GPIO.getmode(), GPIO.BOARD) # Test not set as OUTPUT message GPIO.setmode(GPIO.BOARD) with self.assertRaises(RuntimeError) as e: GPIO.output(LED_PIN, GPIO.HIGH) self.assertEqual(str(e.exception), 'The GPIO channel has not been set up as an OUTPUT') # Test setup(..., pull_up_down=GPIO.HIGH) raises exception GPIO.setmode(GPIO.BOARD) with self.assertRaises(ValueError): GPIO.setup(LED_PIN, GPIO.IN, pull_up_down=GPIO.HIGH) # Test not valid on a raspi exception GPIO.setmode(GPIO.BOARD) with self.assertRaises(ValueError) as e: GPIO.setup(GND_PIN, GPIO.OUT) self.assertEqual(str(e.exception), 'The channel sent is invalid on a Raspberry Pi') # Test 'already in use' warning GPIO.setmode(GPIO.BOARD) with open('/sys/class/gpio/export', 'wb') as f: f.write(str(LED_PIN_BCM).encode()) time.sleep(0.05) # wait for udev to set permissions with open('/sys/class/gpio/gpio%s/direction' % LED_PIN_BCM, 'wb') as f: f.write(b'out') with open('/sys/class/gpio/gpio%s/value' % LED_PIN_BCM, 'wb') as f: f.write(b'1') time.sleep(0.2) with warnings.catch_warnings(record=True) as w: GPIO.setup(LED_PIN, GPIO.OUT) # generate 'already in use' warning self.assertEqual(w[0].category, RuntimeWarning) with open('/sys/class/gpio/unexport', 'wb') as f: f.write(str(LED_PIN_BCM).encode()) GPIO.cleanup() # test initial value of high reads back as high GPIO.setmode(GPIO.BOARD) GPIO.setup(LED_PIN, GPIO.OUT, initial=GPIO.HIGH) self.assertEqual(GPIO.input(LED_PIN), GPIO.HIGH) GPIO.cleanup() # test initial value of low reads back as low GPIO.setmode(GPIO.BOARD) GPIO.setup(LED_PIN, GPIO.OUT, initial=GPIO.LOW) self.assertEqual(GPIO.input(LED_PIN), GPIO.LOW) GPIO.cleanup() # test setup of a list of channels GPIO.setmode(GPIO.BOARD) GPIO.setup([LED_PIN, LOOP_OUT], GPIO.OUT) self.assertEqual(GPIO.gpio_function(LED_PIN), GPIO.OUT) self.assertEqual(GPIO.gpio_function(LOOP_OUT), GPIO.OUT) GPIO.cleanup() GPIO.setmode(GPIO.BOARD) with self.assertRaises(ValueError) as e: GPIO.setup([LED_PIN, GND_PIN], GPIO.OUT) self.assertEqual(GPIO.gpio_function(LED_PIN), GPIO.OUT) self.assertEqual(str(e.exception), 'The channel sent is invalid on a Raspberry Pi') GPIO.cleanup() # test setup of a tuple of channels GPIO.setmode(GPIO.BOARD) GPIO.setup((LED_PIN, LOOP_OUT), GPIO.OUT) self.assertEqual(GPIO.gpio_function(LED_PIN), GPIO.OUT) self.assertEqual(GPIO.gpio_function(LOOP_OUT), GPIO.OUT) GPIO.cleanup() # test warning when using pull up/down on i2c channels GPIO.setmode(GPIO.BOARD) if GPIO.RPI_INFO['P1_REVISION'] == 0: # compute module pass # test not vailid else: # revision 1, 2 or A+/B+ with warnings.catch_warnings(record=True) as w: GPIO.setup(3, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) self.assertEqual(w[0].category, RuntimeWarning) with warnings.catch_warnings(record=True) as w: GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) self.assertEqual(w[0].category, RuntimeWarning) GPIO.cleanup() # test non integer channel GPIO.setmode(GPIO.BOARD) with self.assertRaises(ValueError): GPIO.setup('d', GPIO.OUT) with self.assertRaises(ValueError): GPIO.setup(('d', LED_PIN), GPIO.OUT) # test setting pull_up_down on an output GPIO.setmode(GPIO.BOARD) with self.assertRaises(ValueError): GPIO.setup(LOOP_OUT, GPIO.OUT, pull_up_down=GPIO.PUD_DOWN) # test setting initial on an input GPIO.setmode(GPIO.BOARD) with self.assertRaises(ValueError): GPIO.setup(LOOP_IN, GPIO.IN, initial=GPIO.LOW)
'''Setup and instantiate GPIO, then launch tkinter GUI''' print(TITLE_2) # Turn off warnings... # May report "This channel is already in use continuing anyway." gpio.setwarnings(False) if (not PIN_ADDRESSING_METHOD == "BOARD" and not PIN_ADDRESSING_METHOD == "BCM"): print( "Invalid Pin addressing method: {}".format(PIN_ADDRESSING_METHOD)) sys.exit() # Set the method python uses of addressing the signals / P1 connector pins. mode = "gpio.{}".format(PIN_ADDRESSING_METHOD) gpio.setmode(eval(mode)) if gpio.getmode() == gpio.BOARD: print("Pin numbering is set to BOARD") # 10 if gpio.getmode() == gpio.BCM: print("Signal numbering is set to BCM") # 11 # Setup board pin for the PWM output gpio.setup(SIGNAL, gpio.OUT) # Instantiate pwm_channel pwm_channel = gpio.PWM(SIGNAL, 1) # Initialize at 1Hz # Launch tkinter GUI. root = Tk() #root.geometry('400x80+50+50') main_gui = PWM(root, pwm_channel) root.mainloop()
# Alternatively load a TTF font. Make sure the .ttf font file is in the same directory as the python script! # Some other nice fonts to try: http://www.dafont.com/bitmap.php #font = ImageFont.truetype('Minecraftia.ttf', 8) #font = ImageFont.truetype('visitor1.ttf', 14) #font = ImageFont.truetype('pixelmix.ttf', 14) # -- top row of 16 px different colour bottomfontName = 'visitor1.ttf' topfontName = 'visitor1.ttf' topfontSize = 18 bottomfontSize = 38 # GPIO setup GPIO.setmode(GPIO.BCM) print "GPIO.BOARD: %s" % GPIO.BOARD print "GPIO.BCM: %s" % GPIO.BCM print "GPIO mode: %s" % GPIO.getmode() # Pin button tied to pin_in = 18 GPIO.setup(pin_in, GPIO.IN, pull_up_down=GPIO.PUD_UP) try: GPIO.add_event_detect(pin_in, GPIO.RISING, callback=callback_rising, bouncetime=300) # add rising edge detection on a channel while True: # convert to F #bmp_temp = (pres_sensor.read_temperature() * 9)/5 + 32 # Draw a black filled box to clear the image. draw.rectangle((0,0,width,height), outline=0, fill=0) # <<< this is used if obtaning data from remote sensor response = urllib2.urlopen('http://rpi3:8088/')
def getmode(self): self.logger.log.debug('getmode') return GPIOlib.getmode()
import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) print(GPIO.getmode()) chan_list = [36,32,26,24,22,18,16,8,7,11,13,15,29,31,33,37] GPIO.setup(chan_list, GPIO.OUT, initial=GPIO.HIGH) print("Testing...") try: while True: #GPIO.output(11, GPIO.LOW) GPIO.output(chan_list, GPIO.LOW) time.sleep(.3) GPIO.output(chan_list, GPIO.HIGH) time.sleep(.4) except KeyboardInterrupt: GPIO.cleanup() time.sleep(0.2) print(""" kthxbai!""") exit(0)
import RPi.GPIO as IO import time as time gpio_mode = IO.getmode() BARCODE_GPIO = 8 COFFEE_GPIO = 10 BARCODE_TO_COFFEE_TIME = 3 IO.setwarnings(False) if gpio_mode == -1: IO.setmode(IO.BOARD) IO.setup(COFFEE_GPIO, IO.OUT) IO.setup(BARCODE_GPIO, IO.OUT) class Tassimo: def make_coffee(self): IO.output(BARCODE_GPIO, IO.HIGH) time.sleep(0.5) IO.output(BARCODE_GPIO, IO.LOW) time.sleep(BARCODE_TO_COFFEE_TIME) IO.output(COFFEE_GPIO, IO.HIGH) time.sleep(0.5) IO.output(COFFEE_GPIO, IO.LOW) time.sleep(0.5)
def which_mode(self): return GPIO.getmode()
#!/usr/bin/env python # GPIO test import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) #GPIO.setwarnings(False) mode = 'UNOWN' if GPIO.getmode() == GPIO.BOARD: mode = 'BOARD' elif GPIO.getmode() == GPIO.BCM: mode = 'BCM' print("Using board mode: {}".format(mode)) pin = 22 GPIO.setup(pin, GPIO.OUT) print('Ping {} is going HIGH'.format(pin)) GPIO.output(pin, GPIO.HIGH) raw_input('press enter when done: ') print('Ping {} is going LOW'.format(pin)) GPIO.output(pin, GPIO.LOW) # Test Input pinin = 11 #GPIO.setup(pinin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(pinin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
def detective(self, index): return GPIO.getmode(self.trace_number[index])
def getmode(self): GPIO.getmode()
def _configure_gpio(self): if not self._hasGPIO: self._logger.error("RPi.GPIO is required.") return self._logger.info("Running RPi.GPIO version %s" % GPIO.VERSION) if GPIO.VERSION < "0.6": self._logger.error("RPi.GPIO version 0.6.0 or greater required.") GPIO.setwarnings(False) for pin in self._configuredGPIOPins: self._logger.debug("Cleaning up pin %s" % pin) try: GPIO.cleanup(self._gpio_get_pin(pin)) except (RuntimeError, ValueError) as e: self._logger.error(e) self._configuredGPIOPins = [] if GPIO.getmode() is None: if self.GPIOMode == 'BOARD': GPIO.setmode(GPIO.BOARD) elif self.GPIOMode == 'BCM': GPIO.setmode(GPIO.BCM) else: return if self.sensingMethod == 'GPIO': self._logger.info( "Using GPIO sensing to determine PSU on/off state.") self._logger.info("Configuring GPIO for pin %s" % self.senseGPIOPin) if self.senseGPIOPinPUD == 'PULL_UP': pudsenseGPIOPin = GPIO.PUD_UP elif self.senseGPIOPinPUD == 'PULL_DOWN': pudsenseGPIOPin = GPIO.PUD_DOWN else: pudsenseGPIOPin = GPIO.PUD_OFF try: GPIO.setup(self._gpio_get_pin(self.senseGPIOPin), GPIO.IN, pull_up_down=pudsenseGPIOPin) self._configuredGPIOPins.append(self.senseGPIOPin) except (RuntimeError, ValueError) as e: self._logger.error(e) if self.switchingMethod == 'GPIO': self._logger.info("Using GPIO for On/Off") self._logger.info("Configuring GPIO for pin %s" % self.onoffGPIOPin) try: if not self.invertonoffGPIOPin: initial_pin_output = GPIO.LOW else: initial_pin_output = GPIO.HIGH GPIO.setup(self._gpio_get_pin(self.onoffGPIOPin), GPIO.OUT, initial=initial_pin_output) self._configuredGPIOPins.append(self.onoffGPIOPin) except (RuntimeError, ValueError) as e: self._logger.error(e)
def validate_pi_setup(): if GPIO.getmode() == -1: raise Exception( 'Pi GPIO mode not set, needs to be set to GPIO.BCM or GPIO.BOARD' )
def setup(): if GPIO.getmode() != GPIO.BCM: GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(RelayPin, GPIO.OUT, initial=GPIO.LOW)
def test_setup_one_bcm(): GPIO.setmode(GPIO.BCM) assert GPIO.getmode() == GPIO.BCM GPIO.setup(bcm_pin, GPIO.IN) GPIO.cleanup() assert GPIO.getmode() is None
import keypad import RPi.GPIO as GPIO from time import time, sleep from accelerometer import Accel from datetime import datetime if GPIO.getmode() == -1: GPIO.setmode(GPIO.BOARD) def interp(x, x0, x1, y0, y1): return y0 + (y1 - y0) * (float(x - x0) / (x1 - x0)) class Rover(): def __init__(self, m1, m2, jib=None, dist=None, verbose=False): self.m1 = m1 self.m2 = m2 self.acc = Accel() self.dist = dist self.jib = jib self.motorlog = [] # CURRENT STATE self.power = 0 self.steerpower = 0 self.minpower = 30 self.minsteerpower = 20 # DEBUG self.verbose = verbose print "Hi, I'm Rover... hopefully I won't roll over!" def keycontrol(self):
def main(i2c_channels): number_lidar_sensors_connected = 0 GPIO.setwarnings(False) #these i2c_addresses 30,31,32,33 are arbitrary #but they must match the ones that you reopen #when you spin up the lidar nodes GPIO.setmode(GPIO.BCM) mode = GPIO.getmode() print(mode) GPIO.setup([4, 17, 18, 27], GPIO.OUT) GPIO.setup(4, GPIO.OUT) GPIO.setup(17, GPIO.OUT) GPIO.setup(18, GPIO.OUT) GPIO.setup(27, GPIO.OUT) GPIO.output(4, GPIO.LOW) GPIO.output(17, GPIO.LOW) GPIO.output(18, GPIO.LOW) GPIO.output(27, GPIO.LOW) time.sleep(0.001) GPIO.output(4, GPIO.HIGH) GPIO.output(17, GPIO.HIGH) GPIO.output(18, GPIO.HIGH) GPIO.output(27, GPIO.HIGH) #put all down except 4 GPIO.output(4, GPIO.LOW) GPIO.output(17, GPIO.LOW) GPIO.output(18, GPIO.LOW) GPIO.output(27, GPIO.LOW) #then innit the first one GPIO.output(4, GPIO.HIGH) try: tof1 = VL53L1X.VL53L1X(i2c_bus=1, i2c_address=0x29) tof1.open() tof1.change_address(0x30) tof1 = VL53L1X.VL53L1X(i2c_bus=1, i2c_address=0x30) tof1.open() number_lidar_sensors_connected += 1 except RuntimeError as e: print "Exeption for lidar sensor 4" print e GPIO.output(17, GPIO.HIGH) try: tof2 = VL53L1X.VL53L1X(i2c_bus=1, i2c_address=0x29) tof2.open() tof2.change_address(0x31) tof2 = VL53L1X.VL53L1X(i2c_bus=1, i2c_address=0x31) tof2.open() number_lidar_sensors_connected += 1 except RuntimeError as e: print "Exeption for lidar sensor 4" print e GPIO.setup(18, GPIO.HIGH) try: tof3 = VL53L1X.VL53L1X(i2c_bus=1, i2c_address=0x29) tof3.open() tof3.change_address(0x32) tof3 = VL53L1X.VL53L1X(i2c_bus=1, i2c_address=0x32) tof3.open() number_lidar_sensors_connected += 1 except RuntimeError as e: print "Exeption for lidar sensor 4" print e GPIO.setup(27, GPIO.HIGH) try: tof4 = VL53L1X.VL53L1X(i2c_bus=1, i2c_address=0x29) tof4.open() tof4.change_address(0x33) tof4 = VL53L1X.VL53L1X(i2c_bus=1, i2c_address=0x33) tof4.open() number_lidar_sensors_connected += 1 except RuntimeError as e: print "Exeption for lidar sensor 4" print e GPIO.cleanup() if number_lidar_sensors_connected == 0: sys.exit(10)
#!/usr/bin/env python3 import RPi.GPIO as gpio #gpio.setmode(gpio.BOARD) gpio.setmode(gpio.BCM) ver = gpio.VERSION mode = gpio.getmode() if mode == 11: mode = 'BCM' if mode == 10: mode = 'BOARD' if mode == None: mode = 'not set' board_info = gpio.RPI_INFO print('RPi.GPIO Version: ' + ver) print('GPIO mode: ' + str(mode)) print('Raspberry Pi information:') print('Type: ' + board_info['TYPE']) print('Revision: ' + board_info['REVISION']) print('Processor: ' + board_info['PROCESSOR']) print('Memory: ' + board_info['RAM']) # BCM = 11 # BOARD = 10 # BOTH = 33 # FALLING = 32 # HARD_PWM = 43 # HIGH = 1 # I2C = 42 # IN = 1
def test_setup_one_cvm(): GPIO.setmode(GPIO.CVM) assert GPIO.getmode() == GPIO.CVM GPIO.setup(pin_data['cvm_pin'], GPIO.IN) GPIO.cleanup() assert GPIO.getmode() is None
def initPins(): if GPIO.getmode( ) != GPIO.BOARD: #set the board mode at time of press if not set GPIO.setmode(GPIO.BOARD)
def test_setup_one_tegra_soc(): GPIO.setmode(GPIO.TEGRA_SOC) assert GPIO.getmode() == GPIO.TEGRA_SOC GPIO.setup(pin_data['tegra_soc_pin'], GPIO.IN) GPIO.cleanup() assert GPIO.getmode() is None
#!/usr/bin/env python debug = False import time import RPi.GPIO as GPIO import ConfigParser config = ConfigParser.ConfigParser() config.read('/home/pertneer/Desktop/config.ini') GPIO.setwarnings(False) if (GPIO.getmode() == 10) or (GPIO.getmode() == None): GPIO.setmode(GPIO.BCM) doorOpenPin = int(config.get('Pins', 'doorOpenPin')) doorClosePin = int(config.get('Pins', 'doorClosePin')) if (debug): print doorClosePin print doorOpenPin greenPin = int(config.get('Led', 'greenPin')) redPin = int(config.get('Led', 'redPin')) if (debug): print redPin print greenPin GPIO.setup(doorOpenPin, GPIO.IN, GPIO.PUD_UP) GPIO.setup(doorClosePin, GPIO.IN, GPIO.PUD_UP) GPIO.setup(greenPin, GPIO.OUT) GPIO.setup(redPin, GPIO.OUT) while True: if ((GPIO.input(doorOpenPin) == 0) or (GPIO.input(doorClosePin) == 0)): if (debug):
def test_cleanup_all(): GPIO.setmode(GPIO.BOARD) GPIO.setup((pin_data['in_a'], pin_data['in_b']), GPIO.IN) GPIO.cleanup() assert GPIO.getmode() is None
def test_setup_one_board(): GPIO.setmode(GPIO.BOARD) assert GPIO.getmode() == GPIO.BOARD GPIO.setup(pin_data['in_a'], GPIO.IN) GPIO.cleanup() assert GPIO.getmode() is None
#!/usr/bin/python # -*- coding: utf-8 -*- import RPi.GPIO as GPIO #GPIOピンでいく GPIO.setmode(GPIO.BCM) #どちらのモードに設定されているか確認(勉強のために) mode = GPIO.getmode() #"BCM" or "BOARD" と表示される #チャンネルのモード設定 #今回は複数のチャネルをリストでまとめてやる(勉強のために) chan_list = [10, 11] GPIO.setup(chan_list, GPIO.OUT) #GPIO.IN は入力 #デジタル出力する (アナログ(PWM)出力はPIN番号が少ないからやらない) #さっき定義した出力ピンをHIGHにする GPIO.output(chan_list, GPIO.HIGH) #定義した10pinをHIGH,11pinをLOWにするプログラム(勉強のため)(使うかな? ) #GPIO.output(chan_list,(GPIO.HIGH, GPIO.LOW)) #アナログ出力(PWM)をやってみる(勉強のため) #チャネルと周波数とデューティ比を入力すればできる(らしい) #たとえば、GPIO18に周波数1KHz,デューティ比50%でPWM出力する #pwm = GPIO.PWM(18,1000) #設定 #(追加)設定した周波数で、データを取って0~180にmapすることもできる(方程式を作成) #これを使って、 #pwm.start(50) #出力 #周波数変更したかったら、、 #pwm.ChangeFrequency(2000) #デューティ比を変更したかったら、、
def __init__(self): # Setup ROS node, publishers, and messages rospy.init_node("imu_test_pi") self.imu_pub = rospy.Publisher("/imu/data_array", ImuArray, queue_size=1) self.mag_pub = rospy.Publisher("/imu/mag_array", ImuMag, queue_size=1) self.status_pub = rospy.Publisher("/imu/status", ImuCalibStatus, queue_size=1) self.calib_pub = rospy.Publisher("/imu/calibration", ImuCalibration, queue_size=1) self.rate = 30 # publish at 30 Hz # Set GPIO # FIXME: use the reset pin before starting code, this is required right # now since the code is not able to finish and causes a read error on # the next startup self.reset_pin = 18 gpio.setmode(gpio.BOARD) gpio.setup(self.reset_pin, gpio.OUT) print "Reseting IMU" gpio.output(self.reset_pin, 0) time.sleep(0.3) gpio.output(self.reset_pin, 1) # Set calibration defaults self.calibration = Calibration() # Read in configuration parameters calibration_param_names = ["accel_offset_x", "accel_offset_y", "accel_offset_z", "accel_radius", \ "gyro_offset_x", "gyro_offset_y", "gyro_offset_z", \ "mag_offset_x", "mag_offset_y", "mag_offset_z", "mag_radius"] for param in calibration_param_names: if rospy.has_param("imu/calibration/" + param): eval("self.calibration." + param + " = rospy.get_param('imu/calibration/" + param + "')") else: print "No '" + param + "' found, using {0}".format( eval("self.calibration." + param)) # Begin BNO055 self.serial_port = "/dev/serial0" #self.serial_port = "/dev/ttyUSB0" print "Beginning connection" bno = BNO055.BNO055(serial_port=self.serial_port) result = bno.begin(BNO055.OPERATION_MODE_M4G) print "Connection: {0}".format(result) if not result: raise RuntimeError( "Failed to initialize BNO055. Check sensor connection.") print "Board: %s" % gpio.BOARD print "BCM: %s" % gpio.BCM print "GPIO mode: %s" % gpio.getmode() # Upload calibration parameters calibration_values = [self.calibration.accel_offset_x, \ self.calibration.accel_offset_y, \ self.calibration.accel_offset_z, \ self.calibration.accel_radius, \ self.calibration.gyro_offset_x, \ self.calibration.gyro_offset_y, \ self.calibration.gyro_offset_z, \ self.calibration.mag_offset_x, \ self.calibration.mag_offset_y, \ self.calibration.mag_offset_z, \ self.calibration.mag_radius] # Random values #calibration_values = [1, 5, -17, 10, 25, 567, -3, 4, 9, 20, 55] # Converting calibration values into the data list required by Adafruits # set_calibration method # Convert integers into a list of 22 bytes (11 int16 values) int16_list = [struct.pack('h', x) for x in calibration_values] # combined into one string to easily divide into bytes in the next line bytes_joined = "".join(int16_list) separated = list(bytes_joined) # Convert hex character code bytes into values cal1 = [ord(x) for x in separated] print "cal1: " print cal1 bno.set_calibration(cal1) print "Calibration stored" cal2 = bno.get_calibration() cal2_char = [struct.pack('B', x) for x in cal2] combined = "".join(cal2_char) calib_values = struct.unpack('hhhhhhhhhhh', combined) print calib_values
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) print("Mode used: ", GPIO.getmode()) GPIO.setup(4, GPIO.IN) while True: print("Value of input: ", GPIO.input(4)) time.sleep(1)