コード例 #1
0
 def __init__(self,
              spi=None,
              spi_port=0,
              spi_device=0,
              spi_speed=75000000,
              gpio=None,
              gpio_hold=None,
              gpio_wp=None):
     # Create SPI device.
     self.__name__ = "M25PX80"
     self._spi = spi or SPI
     self._device = self._spi.SpiDev(port=spi_port,
                                     device=spi_device,
                                     max_speed_hz=spi_speed)
     self._device.set_mode(SPI.MODE_CPOL0_CPHA0)
     self._device.set_bit_order(SPI.MSBFIRST)
     # Setup GPIO
     self._gpio = gpio or GPIO.get_platform_gpio()
     self._gpio_hold = gpio_hold
     self._gpio_wp = gpio_wp
     if self._gpio_hold is not None:
         self._gpio.setup(self._gpio_hold, GPIO.OUT)
         self.set_spi_hold(False)
     if self._gpio_wp is not None:
         self._gpio.setup(self._gpio_wp, GPIO.OUT)
         self.set_write_protection(False)
コード例 #2
0
 def __init__(self, pin):
     """ capture interrupts """
     self.gpio = GPIO.get_platform_gpio()
     self.queue = queue.Queue()
     self.pin = pin
     self.gpio.setup(self.pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
     self.last_reading = 0
コード例 #3
0
 def __init__(self, pin, gpio=None):
     # create device
     self.__name__ = "SimpleLED"
     self._gpio = gpio or GPIO.get_platform_gpio()
     self._pin = pin
     self._gpio.setup(self._pin, GPIO.OUT)
     self._gpio.output(self._pin, GPIO.LOW)
     self._state = False
コード例 #4
0
ファイル: transmitter.py プロジェクト: milas/rfdevices
    def __init__(self, gpio: int, platform: GPIO.BaseGPIO = None, **kwargs):
        """Initialize the RF device."""
        self.gpio = gpio
        self.platform = platform or GPIO.get_platform_gpio(**kwargs)

        self.tx_enabled = False
        self.lock = threading.Lock()

        log.debug("Using GPIO " + str(gpio))
コード例 #5
0
 def __init__(self, sclk, miso, mosi, gpio=None):
     # create device
     self.__name__ = "MAX127"
     self._gpio = gpio or GPIO.get_platform_gpio()
     self._sclk = sclk
     self._miso = miso
     self._mosi = mosi
     self._gpio.setup(self._sclk, GPIO.OUT)
     self._gpio.setup(self._miso, GPIO.IN)
     self._gpio.setup(self._mosi, GPIO.OUT)
     self._gpio.output(self._sclk, GPIO.LOW)
     self._gpio.output(self._mosi, GPIO.LOW)
コード例 #6
0
 def __init__(self, width, height, rst, dc=None, sclk=None, din=None, cs=None,
              gpio=None, spi=None, i2c_bus=None, i2c_address=SSD1306_I2C_ADDRESS,
              i2c=None):
     self._log = logging.getLogger('Adafruit_SSD1306.SSD1306Base')
     self._spi = None
     self._i2c = None
     self.width = width
     self.height = height
     self._pages = height//8
     self._buffer = [0]*(width*self._pages)
     self.displ_off = True
     # Default to platform GPIO if not provided.
     self._gpio = gpio
     if self._gpio is None:
         self._gpio = GPIO.get_platform_gpio()
     # Setup reset pin.
     self._rst = rst
     if not self._rst is None:
         self._gpio.setup(self._rst, GPIO.OUT)
     # Handle hardware SPI
     if spi is not None:
         self._log.debug('Using hardware SPI')
         self._spi = spi
         self._spi.set_clock_hz(8000000)
     # Handle software SPI
     elif sclk is not None and din is not None and cs is not None:
         self._log.debug('Using software SPI')
         self._spi = SPI.BitBang(self._gpio, sclk, din, None, cs)
     # Handle hardware I2C
     elif i2c is not None:
         self._log.debug('Using hardware I2C with custom I2C provider.')
         self._i2c = i2c.get_i2c_device(i2c_address)
     else:
         self._log.debug('Using hardware I2C with platform I2C provider.')
         import Adafruit_GPIO.I2C as I2C
         if i2c_bus is None:
             self._i2c = I2C.get_i2c_device(i2c_address)
         else:
             self._i2c = I2C.get_i2c_device(i2c_address, busnum=i2c_bus)
     # Initialize DC pin if using SPI.
     if self._spi is not None:
         if dc is None:
             raise ValueError('DC pin must be provided when using SPI.')
         self._dc = dc
         self._gpio.setup(self._dc, GPIO.OUT)
コード例 #7
0
def main():
    gpio = GPIO.get_platform_gpio()
    gpio.setup(GPIO_SWITCH1, GPIO.IN)
    gpio.setup(GPIO_SWITCH2, GPIO.IN)
    gpio.setup(GPIO_LED1, GPIO.OUT)
    gpio.setup(GPIO_LED2, GPIO.OUT)

    running = True

    def led_blinker():
        operations = [
            lambda: gpio.set_high(GPIO_LED1),
            lambda: gpio.set_low(GPIO_LED1),
            lambda: gpio.set_high(GPIO_LED2),
            lambda: gpio.set_low(GPIO_LED2),
        ]
        op_index = 0
        while running:
            operations[op_index]()
            op_index += 1
            if op_index == len(operations):
                op_index = 0
            gevent.sleep(0.5)

    def switch_poller():
        while running:
            switch1 = gpio.is_high(GPIO_SWITCH1)
            switch2 = gpio.is_high(GPIO_SWITCH2)
            print "switch states: sw1={0} sw2={1}".format(switch1, switch2)
            gevent.sleep(0.5)

    thread1 = gevent.spawn(led_blinker)
    thread2 = gevent.spawn(switch_poller)

    try:
        while True:
            gevent.sleep(1)
    except KeyboardInterrupt:
        running = False
        thread1.join()
        thread2.join()
    finally:
        pass
コード例 #8
0
 def __init__(self,
              i2c=None,
              i2c_busnum=None,
              i2c_address=0x50,
              gpio=None,
              gpio_wp=None,
              **kwargs):
     if i2c_address not in range(0x50, 0x57):
         raise ValueError(
             "24LC256 I2C address must be in the range [0x50..0x57]")
     # Create I2C device.
     self.__name__ = "24LC256"
     self._i2c = i2c or I2C
     self._i2c_busnum = i2c_busnum or self._i2c.get_default_bus()
     self._i2c_address = i2c_address
     self._device = self._i2c.get_i2c_device(self._i2c_address,
                                             self._i2c_busnum, **kwargs)
     # Setup GPIO
     self._gpio = gpio or GPIO.get_platform_gpio()
     self._gpio_wp = gpio_wp
     if self._gpio_wp is not None:
         self._gpio.setup(self._gpio_wp, GPIO.OUT)
         self.set_write_protection(False)
コード例 #9
0
ファイル: pi_pico_init.py プロジェクト: ganonp/GardenHub
    def setup_interrupt_to_acm_mapping(self):

        for interrupt in self.interrupts:
            GPIO.setup(interrupt, GPIO.OUT)
            GPIO.output(interrupt, GPIO.HIGH)

        for ser in self.COMs:
            command = "init" + "\n"
            ser.write(command.encode('utf-8'))
            pico_data = ser.readline()
            sensor_response = pico_data[:-2]
            print(sensor_response)
            pico_config = json.loads(sensor_response)
            pico_config['serial_com'] = ser
            self.pico_configs.append(pico_config)

        for interrupt in self.interrupts:
            GPIO.output(interrupt, GPIO.LOW)
コード例 #10
0
    def __init__(self):
        self._gpio = GPIO.get_platform_gpio()
        pipes = [
            [0xE8, 0xE8, 0xF0, 0xF0, 0xE1],  # writing address
            [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]
        ]  # reading address - sensors write to this

        self._gpio.setup(NRF24Radio.IRQ_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        self._gpio.add_event_detect(NRF24Radio.IRQ_PIN, GPIO.FALLING)

        super(NRF24Radio, self).__init__()
        self.begin(0, 17)

        self.setPayloadSize(32)
        self.setChannel(0x76)
        self.setDataRate(NRF24.BR_1MBPS)
        self.setPALevel(NRF24.PA_MIN)

        self.setAutoAck(True)
        self.enableDynamicPayloads()
        self.enableAckPayload()

        self.openReadingPipe(1, pipes[1])
        self.printDetails()
コード例 #11
0
import time
from simple_pid import PID
import globals
import MAX6675
import Adafruit_GPIO
import Adafruit_GPIO.PWM as PWM
import Adafruit_GPIO.GPIO as GPIO

try:
    platform = Adafruit_GPIO.Platform.platform_detect()
    assert (platform == 1)
    gpio_platform = GPIO.get_platform_gpio()
    simulated_mode = False
except:
    simulated_mode = True
    globals.log(
        'warning',
        "Temperature Controller - Platform is not a Raspberry Pi, running in simulated mode"
    )

config = globals.config

#pins
CLK_pin = config['pin_outs']['thermocouple_clk']
DO_pin = config['pin_outs']['thermocouple_do']
TC1_CS_pin = config['pin_outs']['thermocouple_1_cs']
TC2_CS_pin = config['pin_outs']['thermocouple_2_cs']
TC3_CS_pin = config['pin_outs']['thermocouple_3_cs']
TC4_CS_pin = config['pin_outs']['thermocouple_4_cs']
TC5_CS_pin = config['pin_outs']['thermocouple_5_cs']
lid_switch_pin = config['pin_outs']['lid_switch']
コード例 #12
0
 def __init__(self, pin):
     """ control output to pin 4  """
     self.gpio = GPIO.get_platform_gpio()
     self.pin = pin
     self.gpio.setup(self.pin, GPIO.OUT)
     self.gpio.output(self.pin, GPIO.LOW)
コード例 #13
0
#Oliver Chen
#tests fuzzy (i think)

import Adafruit_GPIO.GPIO as GPIO
from drivers.motors import Motors
from drivers.ultrasonic_sensors import UltrasonicSensors as us
from control.fuzzy.fuzzy import fuzzyControl as fuzz
from time import sleep

m = Motors()
u = us()
f = fuzz()

GPIO.setup("P8_9", GPIO.IN)

while 1:
    while GPIO.input("P8_9"):
        pass

    while GPIO.input("P8_9"):
        dist = u.updateDistances()
        ang = u.calculateAngle()
        speed = f.fuzzy((ang[0]+ang[1])/2,[dist[2], dist[3], dist[4], dist[5]])
        m.moveForward(speed[0], speed[1])

    m.moveForward(0,0)


コード例 #14
0
app = create_app()

create_app()
try:
    socketio = SocketIO(app, async_mode=async_mode)
except:
    # Needed for sphinx documentation
    socketio = SocketIO(app)

ws_thread = None
hb_thread = None
payload = None

try:
    pwm = pwmLib.get_platform_pwm(pwmtype="softpwm")
    gpio = gpioLib.get_platform_gpio()
except NameError:
    print "Adafruit_GPIO lib is unavailable"

DEFAULT_SOFTPWM_FREQ = 100

binary_sensors = []

class BinarySensor:
    """
    The binary sensor object contains information for each binary sensor.

    :param name:
        The human readable name of the sensor
    :param pin:
        The hardware pin connected to the sensor
コード例 #15
0
if (len(sys.argv) > 11):
    SAMPLING_RATE = float(sys.argv[10]) / 1000
    REPORTING_RATE = float(sys.argv[11]) / 1000

if (len(sys.argv) > 14):
    SPI_CLK = int(sys.argv[12])
    SPI_DO = int(sys.argv[13])
    SPI_CS = int(sys.argv[14])
    sensor = MAX31855.MAX31855(clk=SPI_CLK, do=SPI_DO, cs=SPI_CS)
else:
    sensor = MAX31855.MAX31855(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))

# Raspberry Pi hardware SPI configuration.

if (MUXING):
    gpio = GPIO.get_platform_gpio()
    for selector in MUXING_SELECTORS:
        gpio.setup(selector, GPIO.OUT)
    gpio.setup(MUXING_ENABLER, GPIO.OUT)
    gpio.setup(MUXING_LATCH, GPIO.OUT)


def disableMuxing():
    gpio.output(MUXING_ENABLER, True)


def enableMuxing():
    gpio.output(MUXING_ENABLER, False)


def enableSelecting():
コード例 #16
0
 def __init__(self, pin):
     self.pin = pin
     self.gpio = GPIO.get_platform_gpio()
     self.gpio.setup(self.pin, GPIO.OUT)
コード例 #17
0
ファイル: buttons.py プロジェクト: aquila12/tetris_table
 def add_callback(self, callback):
     # Setup interupt
     gpio = GPIO.get_platform_gpio()
   
     gpio.setup(interupt_pin, GPIO.IN)
     gpio.add_event_detect(interupt_pin, GPIO.FALLING, callback=callback, bouncetime=5)
コード例 #18
0
def init(config_data={}):
    """
    Initializes the module
    """
    def build_pin(name, pin_config, pin=None, index=0):
        if pin is None:
            if isinstance(pin_config[CONF_KEY_PIN], list):
                pin = pin_config[CONF_KEY_PIN][index]
                index_sub = index + pin_config[CONF_KEY_FIRST_INDEX]
            else:
                pin = pin_config[CONF_KEY_PIN]
                index_sub = ""
        if isinstance(pin_config[CONF_KEY_TOPIC], list):
            topic = pin_config[CONF_KEY_TOPIC][index]
        else:
            topic = pin_config[CONF_KEY_TOPIC]
        return {
            "name":
            name.format(index=index + pin_config[CONF_KEY_FIRST_INDEX]),
            CONF_KEY_TOPIC:
            resolve_topic(topic,
                          subtopics=["{module_topic}"],
                          substitutions={
                              "module_topic": raw_config[CONF_KEY_TOPIC],
                              "module_name": TEXT_NAME,
                              "pin": pin,
                              "pin_name": name,
                              "index": index_sub
                          }),
            CONF_KEY_DIRECTION:
            pin_config[CONF_KEY_DIRECTION],
            CONF_KEY_INTERRUPT:
            pin_config[CONF_KEY_INTERRUPT],
            CONF_KEY_RESISTOR:
            pin_config[CONF_KEY_RESISTOR],
            CONF_KEY_INVERT:
            pin_config[CONF_KEY_INVERT],
            CONF_KEY_INITIAL:
            pin_config[CONF_KEY_INITIAL].format(
                payload_on=raw_config[CONF_KEY_PAYLOAD_ON],
                payload_off=raw_config[CONF_KEY_PAYLOAD_OFF])
        }

    global gpio, GPIO_PINS

    pi_version = Platform.pi_version()
    if pi_version:
        log.debug("Platform is Raspberry Pi {}".format(pi_version))
        if pi_version == 1:
            log.error("No platform config for Raspberry Pi 1")
            return False
        elif pi_version == 2:
            log.error("No platform config for Raspberry Pi 2")
            return False
        elif pi_version == 3:
            GPIO_PINS = GPIO_PINS_RPI3

        gpio = GPIO.get_platform_gpio(mode=11)
    else:
        log.error("Unknown platform")
        return False

    raw_config = parse_config(config_data, CONF_OPTIONS, log)
    if raw_config:
        log.debug("Config loaded")

        for name in [
                key for key in raw_config if isinstance(raw_config[key], dict)
        ]:
            named_config = raw_config.pop(name)
            if isinstance(named_config[CONF_KEY_PIN], int):
                pin = named_config[CONF_KEY_PIN]
                if pin not in pins:
                    pins[pin] = build_pin(name, named_config)
                    log.debug(
                        "Configured GPIO{pin:02d} with options: {options}".
                        format(pin=pin, options=pins[pin]))
                else:
                    log.warn(
                        "Duplicate configuration for GPIO{pin:02d} found in '{name}' will be ignored, pin already configured under '{original}'"
                        .format(pin=pin, name=name,
                                original=pins[pin]["name"]))
            elif isinstance(named_config[CONF_KEY_PIN], list):
                for index in range(len(named_config[CONF_KEY_PIN])):
                    pin = named_config[CONF_KEY_PIN][index]
                    if pin not in pins:
                        pins[pin] = build_pin(name, named_config, index=index)
                        log.debug(
                            "Configured GPIO{pin:02d} with options: {options}".
                            format(pin=pin, options=pins[pin]))
                    else:
                        log.warn(
                            "Duplicate configuration for GPIO{pin:02d} found in '{name}' will be ignored, pin already configured under '{original}'"
                            .format(pin=pin,
                                    name=name,
                                    original=pins[pin]["name"]))

        config.update(raw_config)
        return True
    else:
        log.error("Error loading config")
        return False
コード例 #19
0
def main(duration=0, rate=3300, gain=16, verbose=False, **kwargs):
    """ Take data from the ADS1015 for duration seconds (or until stdin receives
    EOF, if duration is 0) at rate and gain.

    Default argument values may not be the same as for the command line arguments.
    See the ArgumentParser instance below.

    Kwargs:
    lc_channel = the channel of the ads1015 from which to read load cell data.
    comparator = Whether to use the ALERT/RDY pin instead of time.sleep().
        This is highly recommended, provided the hardware is setup.
    comparator_pin = the GPIO pin from which to yoink the comparator.
        This is specified as a BCM number.
    battery_check_freq = frequency to check the battery level. Not exact!
        1 Hz by default... but setting 2 Hz results in ~ 1 Hz measurements.
    battery_channel = obvious.
    Sends the data to stdout.
    We're using common mode, not differential mode.
    At 3300 samples per second, this generates 2.2 MB of ascii per minute,
    which is probably fine.
    """

    if verbose:
        print("Debugging information:", file=stderr)
        for key in kwargs:
            print(key + ": {0}".format(kwargs[key]), file=stderr)
    adc = Adafruit_ADS1x15.ADS1015()

    lc_channel = kwargs['lc_channel'] if 'lc_channel' in kwargs else 0
    use_comp = kwargs['comparator'] if 'comparator' in kwargs else False
    differential = kwargs['differential'] if 'differential' in kwargs else False

    battery_check_freq = (kwargs['battery_check_freq']
                          if 'battery_check_freq' in kwargs else 1)
    battery_channel = (kwargs['battery_channel']
                       if 'battery_channel' in kwargs else 1)
    battery_counter_limit = rate / battery_check_freq
    assert battery_counter_limit > 0
    pretty_time = SimpleTimer()

    print(TITLE_LINE, file=stdout)
    if duration == 0:
        # The test will run until ctrl-D is sent
        end_condition = EndCondition()
        end_condition.start()
        keep_going = lambda: not end_condition.finished
    else:
        # The test will run for the specified number of seconds.
        time_stop = time.time() + duration
        keep_going = lambda: time.time() < time_stop

    # Setup the ADC. See ADS1015 datasheet, pages 12 and 17.

    # A couple things are different depending on whether we're measuring
    # between lc_channel and ground, or between lc_channel and some other
    # analogue input (i.e. kwargs['diff_channel']).
    if differential:
        print("Also differential mode", file=stderr)
        # lc_channel, until this next part executes, has represented a single analog
        # input pin on the ADS1015. To measure the difference between two analog inputs,
        # we need to change it into a special value that's meaningful only to the
        # ads_1015 hardware. See the ADS1015 data sheet, page 16.
        diff_channel = kwargs[
            'diff_channel'] if 'diff_channel' in kwargs else None
        assert 0 <= diff_channel <= 3 and diff_channel != lc_channel
        if lc_channel == 0 and diff_channel == 1:
            lc_channel = 0
        elif lc_channel == 0 and diff_channel == 3:
            lc_channel = 1
        elif lc_channel == 1 and diff_channel == 3:
            lc_channel = 2
        elif lc_channel == 2 and diff_channel == 3:
            lc_channel = 3
        else:
            raise ValueError()
        if use_comp:  # if we're using the comparator
            lc_start_adc_function = adc.start_adc_difference_comparator
        else:
            lc_start_adc_function = adc.start_adc_difference
    else:
        # Single ended mode is the opposite of differential mode, of course.
        print("Also single-ended mode", file=stderr)
        if use_comp:
            lc_start_adc_function = adc.start_adc_comparator
        else:
            lc_start_adc_function = adc.start_adc

    if use_comp:
        # Set up the test, using the ALERT/RDY pin in "conversion-ready" mode.
        print("Comparator mode", file=stderr)
        ready_pin = kwargs['comparator_pin']

        # Setup and fish for debilitating GPIO exceptions:
        GPIO.setup(ready_pin,
                   Adafruit_GPIO.IN,
                   pull_up_down=Adafruit_GPIO.PUD_OFF)
        wait_function = lambda: GPIO.wait_for_edge(ready_pin, Adafruit_GPIO.
                                                   FALLING)

        # Set up the test, using the ALERT/RDY pin in "conversion-ready" mode.
        # We store these functions because we will need to switch modes
        # repeatedly in order to read both the
        start_lc = lambda: lc_start_adc_function(
            lc_channel,
            -1,
            1,
            # Hi_thresh < 0 < Lo_thresh --> conversion ready mode
            data_rate=rate,
            gain=gain,
            latching=False,  # latching is ignored
            num_readings=1,
            traditional=False,
            active_low=True,
            wait_function=wait_function)
        start_battery = lambda: adc.start_adc_comparator(
            battery_channel,
            -1,
            1,  # Same idea.
            data_rate=BATTERY_RATE,
            gain=BATTERY_GAIN,
            latching=False,  # latching is ignored
            num_readings=1,
            traditional=False,
            active_low=True,
            wait_function=wait_function)

        do_cleanup = lambda: GPIO.cleanup(pin=ready_pin)
    else:
        # We have no ALERT/RDY pin, so set up the test to use
        # time.sleep() instead of GPIO interrupts.
        # TODO - test whether the logic to assign lc_start_adc_function
        # earlier is enough to make this code work with both differential
        # and non-differential measurements.
        sleeper = Sleeper(rate, lambda: (time.time(), adc.get_last_result()))
        wait_function = sleeper.sleep  # sleeps roughly the right amount
        start_lc = lambda: lc_start_adc_function(
            lc_channel, gain=gain, data_rate=rate)
        start_battery = lambda: adc.start_adc(
            battery_channel, gain=gain, data_rate=BATTERY_RATE)
        do_cleanup = lambda: None

    # This is the main loop. All the lambdas and complicated stuff above
    # happened so that this loop could be clear and readable.
    start_lc()
    battery_check_counter = 0

    try:
        while keep_going():
            try:
                if battery_check_counter > battery_counter_limit:
                    read_battery(adc,
                                 BATTERY_SAMPLE_SIZE,
                                 start_lc=start_lc,
                                 start_battery=start_battery,
                                 file=stdout,
                                 wait_function=wait_function,
                                 get_time=pretty_time)
                    battery_check_counter = 0
                battery_check_counter += 1
                wait_function()
                print(LC_DATA_FORMAT.format(pretty_time(),
                                            adc.get_last_result()),
                      file=stdout)
            except IOError:
                if verbose:
                    traceback.print_exc()
                start_lc()
                continue
    finally:
        do_cleanup()
        adc.stop_adc()
        print("Cleaned up.", file=stderr)
コード例 #20
0
#Oliver Chen
#tests fuzzy (i think)

import Adafruit_GPIO.GPIO as GPIO
from drivers.motors import Motors
from drivers.ultrasonic_sensors import UltrasonicSensors as us
from control.fuzzy.fuzzy import fuzzyControl as fuzz
from time import sleep

m = Motors()
u = us()
f = fuzz()

GPIO.setup("P8_9", GPIO.IN)

while 1:
    while GPIO.input("P8_9"):
        pass

    while GPIO.input("P8_9"):
        dist = u.updateDistances()
        ang = u.calculateAngle()
        speed = f.fuzzy((ang[0] + ang[1]) / 2,
                        [dist[2], dist[3], dist[4], dist[5]])
        m.moveForward(speed[0], speed[1])

    m.moveForward(0, 0)