Beispiel #1
0
class ad7606():
    try:
        start_acq_fd = open("/sys/class/gpio/gpio145/value", 'w', 0)
    except IOError as e:
        print("Error opening start acquire gpio pin: %s" % e)
        raise

    def __init__(self, dev):
        self.dev = SpiDev()
        try:
            self.dev.open(3, dev)
            self.dev.mode = 2
        except IOError as e:
            print("Error opening /dev/spidev3.%d: %s" % (dev, e))
            raise

    def trigger_acquire(self):
        self.start_acq_fd.write(b'1')
        self.start_acq_fd.write(b'0')

    def read(self):
        self.trigger_acquire()
        buf = self.dev.readbytes(16)
        samples = [0, 0, 0, 0, 0, 0, 0, 0]
        for i in xrange(8):
            samples[i] = buf[2 * i] << 8 | buf[2 * i + 1] << 0
        return samples
Beispiel #2
0
	def __init__(self, bus, cs_pin, slave_select_pin, reset_pin):
                print('setting up dspin interface on pins: ', bus, cs_pin, slave_select_pin, reset_pin)
                Dspin_motor.init_toggle_reset_pin(reset_pin)

                self.reset_gpio = LED(reset_pin)
                self.reset_gpio.on()
                time.sleep(0.1)
                self.reset_gpio.off()
                time.sleep(0.1)
                self.reset_gpio.on()
                time.sleep(0.1)



                self.slave_select_gpio = LED(slave_select_pin)
                self.spi = SpiDev()

                self.slave_select_gpio.on()

                self.spi.open(bus, cs_pin)
                self.spi.max_speed_hz = 10000
                self.spi.mode = 3
                self.spi.lsbfirst = False
                #spi.no_cs = True
                #spi.loop = False

                self.connect_l6470()
                self.last_steps_count_time = datetime.datetime.now()
                self.current_speed = 0
                self.absolute_pos_manual_count = 0
Beispiel #3
0
class MCP3008:
    """Class representing an MCP3008 ADC"""
    def __init__(self, bus=0, device=0):
        """
        Initialize SPI device for MCP3008
        :param bus: SPI bus (usually 0)
        :param device: SPI slave (SS/CS/CE)
        """
        self.spi = SpiDev()
        self.spi.open(bus, device)
        self.spi.max_speed_hz = 100000

    def read_channel(self, ch):
        """
        Perform measurement on an ADC channel
        :param ch: ADC channel (0-7)
        :return: 10-bit integer measurement (0-1023)
        """

        digit = int("1" + bin(ch)[2:] + "0000")
        cb = [0x01, digit, 0x00]
        for i in range(len(cb)):
            print(cb)
        bytes_in = self.spi.xfer2(cb)
        B9B8 = (bytes_in[1] & 0x03) << 8
        byte = B9B8 | bytes_in[2]
        return byte
Beispiel #4
0
class MCP3008Controller(object):
    def __init__(self, bus = 0, device = 0):
        self.bus, self.device = bus, device
        self.spi = SpiDev()
        self.open()
        self.spi.max_speed_hz = 1000000 # 1MHz
        self.myLogger = MyLogger(self.__class__.__name__)
        self.myLogger.info('Init MCP3008')
 
    def open(self):
        self.spi.open(self.bus, self.device)
        self.spi.max_speed_hz = 1000000 # 1MHz
    
    def read(self, channel = 0):
        cmd1 = 4 | 2 | (( channel & 4) >> 2)
        cmd2 = (channel & 3) << 6
 
        adc = self.spi.xfer2([cmd1, cmd2, 0])
        self.myLogger.debug("Read SPI: %s" % adc)

        data = ((adc[1] & 15) << 8) + adc[2]
        return data
            
    def close(self):
        self.spi.close()
Beispiel #5
0
class dac8568():
    def __init__(self, dev):
        self.dev = SpiDev()
        try:
            self.dev.open(4,dev)
        except IOError as e:
            print("Error opening /dev/spidev4.%d: %s" % (dev, e))
            raise

    def build_command(self, control, addr, data):
        prefix = 0
        features = 0
        cmd = [0,0,0,0]
        cmd[3] = (0xf    & features) << 0 | (0xf & data) << 4
        cmd[2] = (0x0ff0 & data) >> 4
        cmd[1] = (0xf000 & data) >> 12    | (0xf & addr) << 4
        cmd[0] = (0xf    & control) << 0  | (0xf & prefix) << 4
        return cmd
       
    # indexed by label number, mapping to DAC channel number
    channel_map = (0,2,4,6,7,5,3,1)
    write_mode = { 'WRITE': 0x0,
                   'UPDATE': 0x1,
                   'WRITE_UPDATE_ALL': 0x2,
                   'WRITE_UPDATE': 0x3 }

    def write(self, addr, data, mode = write_mode['WRITE_UPDATE']):
        addr = self.channel_map[addr]
        cmd  = self.build_command(mode, addr, data)
        self.dev.writebytes(cmd)
class MCP3008(object):
    """
    MCP3008 ADC (Analogue-to-Digital converter).
    """
    def __init__(self, bus=0, device=0, channel=0):
        self.bus = bus
        self.device = device
        self.channel = channel
        self.spi = SpiDev()

    def __enter__(self):
        self.open()
        return self

    def open(self):
        self.spi.open(self.bus, self.device)

    def read(self):
        adc = self.spi.xfer2([1, (8 + self.channel) << 4, 0])
        data = ((adc[1] & 3) << 8) + adc[2]
        return data

    def __exit__(self, type, value, traceback):
        self.close()

    def close(self):
        self.spi.close()
class MCP3008:
    def __init__(self, bus=0, device=0):
        self.spi = SpiDev()
        self.spi.open(bus, device)  #Connect to the specified SPI device (CS)

############################### Read ######################################
# Input: the channel to read from (default is 0)
# Output: raw digital ADc reading
# Remarks: Technical Note: this is a 12-bit ADC
###########################################################################

    def read(self, channel=0):
        # to initiate communication with MCP, send 3 bytes
        # 0000 0001 | 0         0  0  0  0000 | 0000 00000
        # start bit | SNGL/DIFF D2 D1 D0 XXXX | XXXX XXXXX
        # Perform SPI transaction. CS on RPi will be held active between blocks
        adc = self.spi.xfer2([1, (8 + channel) << 4,
                              0])  # (0000 1000 + channel) << 4
        # ???? ?nullB9B8 | B7B6B5B4 B3B2B1B0
        # bitmask: keep B9B0 and shift'em to the beginning, the resulted integer + last byte value
        return ((adc[1] & 3) << 8) + adc[2]

############################### Close ######################################
# Disconnects from the interface.
###########################################################################

    def close(self):
        self.spi.close()
Beispiel #8
0
class HWSPI(SPI):
    """ Hardware SPI
    """
    def __init__(self, device, ce, config):
        """
        Args:
            device (int): the number of SPI device
            ce (int): the number of chip select of SPI device
            config (SPIConfig):
        """
        self._device = device
        self._ce = ce
        self._config = config
        self._spi = SpiDev()

    def open(self):
        logger.info("Open SPI(%d,%d)", self._device, self._ce)
        self._spi.open(self._device, self._ce)
        self._spi.mode = self._config.mode
        self._spi.max_speed_hz = self._config.speed

    def close(self):
        logger.info("Close SPI(%d,%d)", self._device, self._ce)
        self._spi.close()

    def transfer(self, writedata, readsize):
        buf = self._spi.xfer(writedata + [0] * readsize)
        return buf[len(writedata):]
Beispiel #9
0
class ad7606():
    try:
        start_acq_fd = open("/sys/class/gpio/gpio145/value", 'w', 0)
    except IOError as e:
        print("Error opening start acquire gpio pin: %s" % e)
        raise

    def __init__(self, dev):
        self.dev = SpiDev()
        try:
            self.dev.open(3,dev)
            self.dev.mode = 2
        except IOError as e:
            print("Error opening /dev/spidev3.%d: %s" % (dev, e))
            raise

    def trigger_acquire(self):
        self.start_acq_fd.write(b'1')
        self.start_acq_fd.write(b'0')

    def read(self):
        self.trigger_acquire()
        buf = self.dev.readbytes(16)
        samples = [0,0,0,0,0,0,0,0]
        for i in xrange(8):
            samples[i] = buf[2*i] << 8 | buf[2*i+1] << 0
        return samples
Beispiel #10
0
    def __init__(self, address, direction, bitrate=976000, theta_max=0.15):
        """
        Initialize and open an SPI connection with a CUI AMT20 encoder.
        :param bus: SPI address in the bus (e.g. 0 or 1).
        :type bus: int
        :param direction: Direction of rotation of the encoder, must be either
            'ccw' or 'cw'.
        :type direction: string
        :param bitrate: Frequency of the SPI bus. The encoder defaults to 
            976[kHz].
        :type bitrate: int
        :param theta_max: Max angle variation between samples, in radians. 
            Defaults to 0.15[rad/sample].
        :type theta_max: float
        """
        assert address == 0 or address == 1, "SPI address must be 0 or 1"
        assert direction == "ccw" or direction == "cw", "Direction must be either 'ccw' or 'cw'"
        self.RESOLUTION = 4096
        self.direction = direction
        self.theta_max = theta_max

        self.encoder = SpiDev()
        self.encoder.open(0, address)
        self.encoder.max_speed_hz = bitrate

        self._warm_up()
        self.last = {"angle": self.angle(), "time": datetime.now()}
class MCP3008(object):
    """
    MCP3008 ADC (Analogue-to-Digital converter).
    """
    def __init__(self, bus=0, device=0, channel=0):
        self.bus = bus
        self.device = device
        self.channel = channel
        self.spi = SpiDev()

    def __enter__(self):
        self.open()
        return self

    def open(self):
        self.spi.open(self.bus, self.device)

    def read(self):
        adc = self.spi.xfer2([1, (8 + self.channel) << 4, 0])
        data = ((adc[1] & 3) << 8) + adc[2]
        return data

    def __exit__(self, type, value, traceback):
        self.close()

    def close(self):
        self.spi.close()
Beispiel #12
0
class MCP3008:
    def __init__(self, bus=0, dev=0, max_speed_hz=7629):
        self.bus = bus
        self.dev = dev
        self.max_speed_hz = max_speed_hz

        self.spi = SpiDev()

    def __enter__(self):
        self.open()
        return self

    def __exit__(self, type, value, traceback):
        self.close()

    def read(self, ch=0):
        if ch > 7 or ch < 0:
            return -1

        r = self.spi.xfer2([1, 8 + ch << 4, 0])
        data = ((r[1] & 3) << 8) + r[2]

        return data

    def open(self):
        self.spi.open(self.bus, self.dev)
        self.spi.max_speed_hz = self.max_speed_hz

    def close(self):
        self.spi.close()
Beispiel #13
0
 def __init__(self, bus = 0, device = 0):
     self.bus, self.device = bus, device
     self.spi = SpiDev()
     self.open()
     self.spi.max_speed_hz = 1000000 # 1MHz
     self.myLogger = MyLogger(self.__class__.__name__)
     self.myLogger.info('Init MCP3008')
Beispiel #14
0
class MCP3208:
    def __init__(self, bus=0, device=0, channel=0):
        self.bus, self.device, self.channel = bus, device, channel
        self.spi = SpiDev()

    def __enter__(self):
        self.open()
        self.spi.max_speed_hz = 200000
        return self

    def open(self):
        self.spi.open(self.bus, self.device)

    def read(self):
        if self.channel > 7 or self.channel < 0:
            return -1
        adc = self.spi.xfer2([(24 + self.channel) << 2, 0, 0])
        data = (adc[1] << 4) | (adc[2] >> 4)
        return data

    def __exit__(self, type, value, traceback):
        self.close()

    def close(self):
        self.spi.close()
Beispiel #15
0
def setup(keymap=FULL):
    global _is_setup, spi, callbacks, pins, leds, buf, states
    if _is_setup:
        return
    _is_setup = True

    callbacks = [None for key in keymap]
    pins = [key[0] for key in keymap]
    leds = [key[1] for key in keymap]
    buf = [[0, 0, 0, 1.0] for key in keymap]
    states = [True for key in keymap]

    GPIO.setmode(GPIO.BCM)
    GPIO.setup(pins, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    for pin in pins:
        GPIO.add_event_detect(pin,
                              GPIO.BOTH,
                              callback=_handle_keypress,
                              bouncetime=1)

    spi = SpiDev()
    spi.open(0, 0)
    spi.max_speed_hz = 1000000

    atexit.register(_on_exit)
Beispiel #16
0
class dac8568():
    def __init__(self, dev):
        self.dev = SpiDev()
        try:
            self.dev.open(4, dev)
        except IOError as e:
            print("Error opening /dev/spidev4.%d: %s" % (dev, e))
            raise

    def build_command(self, control, addr, data):
        prefix = 0
        features = 0
        cmd = [0, 0, 0, 0]
        cmd[3] = (0xf & features) << 0 | (0xf & data) << 4
        cmd[2] = (0x0ff0 & data) >> 4
        cmd[1] = (0xf000 & data) >> 12 | (0xf & addr) << 4
        cmd[0] = (0xf & control) << 0 | (0xf & prefix) << 4
        return cmd

    # indexed by label number, mapping to DAC channel number
    channel_map = (0, 2, 4, 6, 7, 5, 3, 1)
    write_mode = {
        'WRITE': 0x0,
        'UPDATE': 0x1,
        'WRITE_UPDATE_ALL': 0x2,
        'WRITE_UPDATE': 0x3
    }

    def write(self, addr, data, mode=write_mode['WRITE_UPDATE']):
        addr = self.channel_map[addr]
        cmd = self.build_command(mode, addr, data)
        self.dev.writebytes(cmd)
Beispiel #17
0
 def __init__(self, dev):
     self.dev = SpiDev()
     try:
         self.dev.open(4, dev)
     except IOError as e:
         print("Error opening /dev/spidev4.%d: %s" % (dev, e))
         raise
Beispiel #18
0
 def _open(self):
     if not self._spi:
         self._spi = SpiDev()
         try:
             self._spi.open(self.bus, self.dev)
         except FileNotFoundError:
             raise SPIError(self.bus, self.dev)
         self._spi.max_speed_hz = self.freq
Beispiel #19
0
 def __init__(self):
     self.__spi = SpiDev()
     self.__spi.open(0, 0)
     self.__sensors = []
     self.__thread = Thread(target=self.__run, daemon=True)
     self.__stop = Event()
     self.__lock = Lock()
     self.__thread.start()
Beispiel #20
0
 def __init__(self, bus=0, device=0):
     """initializes the SPI bus for the ADS1293
     """
     self.bus, self.device = bus, device
     self.spi = SpiDev()
     self.open()
     self.inax_max = [0, 0, 0]
     self.inax_min = [0, 0, 0]
     self.inax_zero = [0, 0, 0]
Beispiel #21
0
 def __init__(self, bus=0, device=0):
     """
     Initialize SPI device for MCP3008
     :param bus: SPI bus (usually 0)
     :param device: SPI slave (SS/CS/CE)
     """
     self.spi = SpiDev()
     self.spi.open(bus, device)
     self.spi.max_speed_hz = 100000
Beispiel #22
0
 def __init__(self, port, device):
     self._port = port
     self._device = device
     self._interface = None
     if SpiDev is None:
         raise ImportError('failed to import spidev')
     self._interface = SpiDev()
     self._interface.open(port, device)
     self._interface.max_speed_hz = 1000000
Beispiel #23
0
 def open(self):
     """Open an SPI connection to a slave"""
     self._spi_port = SpiDev()
     self._spi_port.open(0, 0)
     self._spi_port.max_speed_hz = int(3E6)
     self._spi_port.mode = 0b00
     GPIO.setup(self.DC_PIN, GPIO.OUT)
     GPIO.setup(self.RESET_PIN, GPIO.OUT)
     GPIO.setup(self.BUSY_PIN, GPIO.IN)
Beispiel #24
0
    def __init__(self, spinum, sipmpins, chippins):
        self.spi = SpiDev(spinum, 0)
        self.spi.mode = 3
        self.spi.max_speed_hz = 1000000

        self.sipmpins = ['P9_%i' % num for num in sipmpins]
        self.chippins = ['P9_%i' % num for num in chippins]
        for pin in self.sipmpins + self.chippins:
            GPIO.setup(pin, GPIO.OUT)
            GPIO.output(pin, GPIO.LOW)
Beispiel #25
0
 def __init__(self, device=0, bits=None):
     if bits is None:
         raise InputDeviceError('you must specify the bit resolution of the device')
     if device not in (0, 1):
         raise InputDeviceError('device must be 0 or 1')
     self._device = device
     self._bits = bits
     self._spi = SpiDev()
     self._spi.open(0, self.device)
     super(AnalogInputDevice, self).__init__()
Beispiel #26
0
 def _setup_spi(self):
     if self.spi is None:
         from spidev import SpiDev
         self.spi = SpiDev()
         self.spi.open(0, 1)
         self.spi.max_speed_hz = 9600
         self.spi.mode = 0b00
         self.spi.bits_per_word = 8
         self.spi.cshigh = True
         self.spi.lsbfirst = False
Beispiel #27
0
    def __init__(self, DO_DIRECTION_PIN, DO_RESET_PIN, DI_FAULT_PIN, ARGS):

        self.REG = {  # AMIS-30543 Registers
            'WR': 0x00,
            'CR0': 0x01,
            'CR1': 0x02,
            'CR2': 0x03,
            'CR3': 0x09,
            'SR0': 0x04,
            'SR1': 0x05,
            'SR2': 0x06,
            'SR3': 0x07,
            'SR4': 0x0A
        }

        self.CMD = {  # AMIS-30543 Command constants
            'READ': 0x00,
            'WRITE': 0x80
        }

        self.dirctrl = ARGS[0]
        self.pwmf = ARGS[1]
        self.pwmj = ARGS[2]
        self.sm = ARGS[3]
        self.mult = ARGS[4]
        self.dist = ARGS[5]
        self.step = ARGS[6]

        self.VAL = {
            'WR': 0b00000000,  # no watchdog
            'CR0': 0b00010111 | self.sm,  # & 2.7 A current limit
            'CR1': 0b00000000 | self.dirctrl | self.pwmf
            | self.pwmj,  # & step on rising edge & fast slopes
            'CR2':
            0b00000000,  # motor off & no sleep & SLA gain @ 0.5 & SLA no transparent
            'CR3':
            0b00000000  #,                                         # no extended step mode
            #'dist': self.dist,
            #'step': self.step
        }

        # InitGPIO

        PWM.setup(5, 0)  # 5 us pulse_incr, 0 delay_hw
        PWM.init_channel(0, 3000)  # DMA channel 0, 3000 us subcycle time

        self.DO_RESET = gpiozero.DigitalOutputDevice(DO_RESET_PIN)
        self.DO_DIRECTION = gpiozero.DigitalOutputDevice(DO_DIRECTION_PIN)
        self.DI_NO_FAULT = gpiozero.DigitalInputDevice(DI_FAULT_PIN)

        self.spi = SpiDev()
        self.spi.open(0, 0)
        self.spi.max_speed_hz = 1000000

        self.RegisterSet()
    def open(self):
        if self.__connection:
            return

        self.acquire_lock()

        self.__connection = SpiDev()
        self.__connection.open(self.__bus, self.__device)

        self.__connection.mode = self.__mode
        self.__connection.max_speed_hz = self.__max_speed
Beispiel #29
0
 def __init__(
     self,
     bus=1,
     channel=0,
     device=1,
 ):
     """Define which SPI device is the A/D Converter on."""
     self.bus = bus
     self.device = device
     self.channel = channel
     self.spi = SpiDev()
Beispiel #30
0
class SPIDataLink(DataLink):
    """Clase que gestiona un enlace Serial Peripheral Interface (SPI).

    :param max_speed: máxima velocidad en herzios del enlace de datos.
    :param bus: Identificador del bus SPI que se usa para el enlace de datos.
    :param device: Línea de selección de chip SPI activa en el enlace de datos.

    Ejemplo de uso para pedir una medida del primer canal analógico de un
    conversor ADC MCP3202 conectado a la línea de selección de chip 0 de Raspberry Pi:

    >>> from pida.links import SPIDataLink
    >>> link = SPIDataLink(1000000, 0, 0)
    >>> link.open()
    >>> request = [1, 2 << 6, 0]
    >>> response = link.transfer(request)
    >>> link.close()
    """
    def __init__(self, max_speed, bus, device):
        DataLink.__init__(self, max_speed)
        self._bus = bus
        self._device = device
        self._spi = SpiDev()
        
    @property
    def bus(self):
        """Identificador del bus SPI que se usa para el enlace de datos.

        .. note:: Raspberry Pi ofrece a través de su puerto GPIO
                  un único bus SPI cuyo identificador es 0.

        Es una propiedad de sólo lectura.
        """
        return self._bus

    @property
    def device(self):
        """Línea de selección de chip SPI activa en el enlace de datos.

        .. note:: El bus SPI 0 de Raspberry Pi puede, a través del puerto GPIO,
                  activar dos líneas de selección de chip SPI: 0 y 1.

        Es una propiedad de sólo lectura.
        """
        return self._device

    def open(self):
        self._spi.open(self._bus, self._device)
        self._spi.max_speed_hz = self.max_speed

    def close(self):
        self._spi.close()

    def transfer(self, data):
        return self._spi.xfer2(data)
Beispiel #31
0
 def __init__(self, device, ce, config):
     """
     Args:
         device (int): the number of SPI device
         ce (int): the number of chip select of SPI device
         config (SPIConfig):
     """
     self._device = device
     self._ce = ce
     self._config = config
     self._spi = SpiDev()
Beispiel #32
0
class AnalogSensors(SensorApi):
    def __init__(self):
        self.__spi = SpiDev()
        self.__spi.open(0, 0)
        self.__sensors = []
        self.__thread = Thread(target=self.__run, daemon=True)
        self.__stop = Event()
        self.__lock = Lock()
        self.__thread.start()

    def __del__(self):
        self.__stop.set()
        self.__thread.join(10)

    def __len__(self):
        return self.__sensors.__len__()

    def __contains__(self, item):
        return len([i for i in self if i.sensor_id == item]) > 0

    def __iter__(self):
        return self.__sensors.__iter__()

    def __getitem__(self, item):
        return [i for i in self if i.sensor_id == item][0]

    def __run(self):
        while not self.__stop.wait(1):
            self.__update_sensors()

    def __update_sensors(self):
        sensors = self.__poll_sensors()
        with self.__lock:
            self.__sensors = sensors

    def __readadc(self, adcnum):
        r = self.__spi.xfer2([1, 8 + adcnum << 4, 0])
        adcout = ((r[1] & 3) << 8) + r[2]
        return adcout

    def __get_values(self):
        values = {}
        for i in range(8):
            name = 'analog-{}'.format(i)
            values[name] = self.__readadc(i)
        return values

    def __poll_sensors(self):
        sensors = [
            SensorInfo(sensor_id=k, value=v, unit="C")
            for k, v in self.__get_values().items()
        ]
        return sensors
Beispiel #33
0
class AnalogInputDevice(CompositeDevice):
    """
    Represents an analog input device connected to SPI (serial interface).
    """
    def __init__(self, device=0, bits=None):
        if bits is None:
            raise InputDeviceError(
                'you must specify the bit resolution of the device')
        if device not in (0, 1):
            raise InputDeviceError('device must be 0 or 1')
        self._device = device
        self._bits = bits
        self._spi = SpiDev()
        self._spi.open(0, self.device)
        super(AnalogInputDevice, self).__init__()

    def close(self):
        """
        Shut down the device and release all associated resources.
        """
        if self._spi:
            s = self._spi
            self._spi = None
            s.close()
        super(AnalogInputDevice, self).close()

    @property
    def bus(self):
        """
        The SPI bus that the device is connected to. As the Pi only has a
        single (user accessible) SPI bus, this always returns 0.
        """
        return 0

    @property
    def device(self):
        """
        The select pin that the device is connected to. The Pi has two select
        pins so this will be 0 or 1.
        """
        return self._device

    def _read(self):
        raise NotImplementedError

    @property
    def value(self):
        """
        A value read from the device. This will be a floating point value
        between 0 and 1 (scaled according to the number of bits supported by
        the device).
        """
        return self._read() / (2**self._bits - 1)
Beispiel #34
0
class AnalogInputDevice(CompositeDevice):
    """
    Represents an analog input device connected to SPI (serial interface).
    """

    def __init__(self, device=0, bits=None):
        if bits is None:
            raise InputDeviceError('you must specify the bit resolution of the device')
        if device not in (0, 1):
            raise InputDeviceError('device must be 0 or 1')
        self._device = device
        self._bits = bits
        self._spi = SpiDev()
        self._spi.open(0, self.device)
        super(AnalogInputDevice, self).__init__()

    def close(self):
        """
        Shut down the device and release all associated resources.
        """
        if self._spi:
            s = self._spi
            self._spi = None
            s.close()
        super(AnalogInputDevice, self).close()

    @property
    def bus(self):
        """
        The SPI bus that the device is connected to. As the Pi only has a
        single (user accessible) SPI bus, this always returns 0.
        """
        return 0

    @property
    def device(self):
        """
        The select pin that the device is connected to. The Pi has two select
        pins so this will be 0 or 1.
        """
        return self._device

    def _read(self):
        raise NotImplementedError

    @property
    def value(self):
        """
        A value read from the device. This will be a floating point value
        between 0 and 1 (scaled according to the number of bits supported by
        the device).
        """
        return self._read() / (2**self._bits - 1)
Beispiel #35
0
 def __init__(self, factory, port, device):
     self._port = port
     self._device = device
     self._interface = None
     if SpiDev is None:
         raise ImportError('failed to import spidev')
     super(LocalPiHardwareSPI, self).__init__()
     pins = SPI_HARDWARE_PINS[port]
     self.pin_factory.reserve_pins(self, pins['clock'], pins['mosi'],
                                   pins['miso'], pins['select'][device])
     self._interface = SpiDev()
     self._interface.open(port, device)
     self._interface.max_speed_hz = 500000
class SpiDevice(object):
    def __init__(self, bus, device):
        self.spi = SpiDev()
        self.bus = bus
        self.device = device

    def init(self):
        self.spi.open(self.bus, self.device)

    def transfer(self, data):
        return self.spi.xfer2(data)

    def close(self):
        self.spi.close()
Beispiel #37
0
def run():
    """
    Launches the main loop
    """
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(ALERT_PIN, GPIO.OUT)
    try:
        spi = SpiDev()
        spi.open(0, 0)
        api = XivelyAPIClient(XIVELY_API_KEY)
        feed = api.feeds.get(XIVELY_FEED_ID)

        moisture = get_datastream(feed, "water")
        light = get_datastream(feed, "light")
        temp = get_datastream(feed, "temp")

        sent_notification = False

        while True:
            moisture.current_value = readadc(spi, ADC_MOISTURE_PIN)
            moisture.at = datetime.utcnow()
            light.current_value = readadc(spi, ADC_LIGHT_PIN)
            light.at = datetime.utcnow()
            temp.current_value = "%.2f" % convert_temp(readadc(spi, ADC_TMP_PIN))
            temp.at = datetime.utcnow()
            if(DEBUG):
                print("Moisture: %d, light: %d, temp: %s" % (
                    moisture.current_value,
                    light.current_value,
                    temp.current_value))
            if(moisture.current_value < MOISTURE_THRESHOLD):
                if(not sent_notification):
                    send_pushover_msg(
                            "Please water your plant: %s" % moisture.current_value)
                    sent_notification = True
                GPIO.output(ALERT_PIN, GPIO.HIGH)
            else:
                sent_notification = False
                GPIO.output(ALERT_PIN, GPIO.LOW)
            try:
                moisture.update()
                light.update()
                temp.update()
            except Exception as e:
                print("%s" % e.strerror)
            time.sleep(UPDATE_DELAY)
    finally:
        GPIO.cleanup()
Beispiel #38
0
 def __init__(self, dev):
     self.dev = SpiDev()
     try:
         self.dev.open(4,dev)
     except IOError as e:
         print("Error opening /dev/spidev4.%d: %s" % (dev, e))
         raise
Beispiel #39
0
 def __init__(self, bus = 0, channel_select = 1):
     self.bus = SpiDev()
     self.bus.open(bus,channel_select)
     self.reset()
     self.buff=[]
     self.run = True
     self.timestamp = time()
Beispiel #40
0
class MCP3008:
    def __init__(self, bus = 0, device = 0):
        self.bus, self.device = bus, device
        self.spi = SpiDev()
        self.open()

    def open(self):
        self.spi.open(self.bus, self.device)
    
    def read(self, channel = 0):
        adc = self.spi.xfer2([1, (8 + channel) << 4, 0])
        data = ((adc[1] & 3) << 8) + adc[2]
        return data
            
    def close(self):
        self.spi.close()
 def __init__(self, device=0, bits=None):
     if bits is None:
         raise InputDeviceError("you must specify the bit resolution of the device")
     if device not in (0, 1):
         raise InputDeviceError("device must be 0 or 1")
     self._device = device
     self._bits = bits
     self._spi = SpiDev()
     self._spi.open(0, self.device)
Beispiel #42
0
 def __init__(self, device=0, bits=None):
     if bits is None:
         raise InputDeviceError('you must specify the bit resolution of the device')
     if device not in (0, 1):
         raise InputDeviceError('device must be 0 or 1')
     self._device = device
     self._bits = bits
     self._spi = SpiDev()
     self._spi.open(0, self.device)
     super(AnalogInputDevice, self).__init__()
class AnalogInputDevice(object):
    """
    Represents an analog input device connected to SPI (serial interface).
    """

    def __init__(self, device=0, bits=None):
        if bits is None:
            raise InputDeviceError("you must specify the bit resolution of the device")
        if device not in (0, 1):
            raise InputDeviceError("device must be 0 or 1")
        self._device = device
        self._bits = bits
        self._spi = SpiDev()
        self._spi.open(0, self.device)

    def close(self):
        if self._spi:
            s = self._spi
            self._spi = None
            s.close()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, exc_tb):
        self.close()

    @property
    def bus(self):
        return 0

    @property
    def device(self):
        return self._device

    def _read(self):
        raise NotImplementedError

    @property
    def value(self):
        return self._read() / (2 ** self._bits - 1)
Beispiel #44
0
class MCP3008(object):

    """Class for MCP3008 ADC"""

    def __init__(self, port=0, device=0):
        self.spi = SpiDev()
        # connect spi object to specified spi device
        self.spi.open(port, device)

    def readValueChannel(self, channel=0):
        """
        read SPI data from MCP3008 on channel -> digital value
            spi.xfer2() send three bytes to the device
                the first byte is 1 -> 00000001
                the second byte is 8 + channel and left shift with 4 bits
                the third byte is 0 -> 00000000
            the device return 3 bytes as responce
        """
        # perform spi transaction
        adc = self.spi.xfer2([1, (8 + channel) <<4, 0])
        # extract value from data bytes
        data = ((adc[1] & 3) << 8) + adc[2]
        return data

    def readVoltChannel(self, channel=0, vmax=3.3, places=5):
        """
        read the digital data from MCP3008 and convert it to voltage
            MCP3008: 10bit ADC -> value in number range 0-1023
            spi value -> voltage
                   0  ->  0v
                1023  ->  vmax
        """
        # read spi digital value
        adc = self.spi.xfer2([1, (8 + channel) <<4, 0])
        data = ((adc[1] & 3) << 8) + adc[2]
        # convert it to voltage
        volts = (data * vmax) / float(1023)
        # round to specified number of decimal places
        volts = round(volts, places)
        return volts
class MCP3008:
    def __init__(self, bus = 0, device = 0, channel = 0):
        self.bus, self.device, self.channel = bus, device, channel
        self.spi = SpiDev()

    def __enter__(self):
        self.open()
        return self

    def open(self):
        self.spi.open(self.bus, self.device)
    
    def read(self):
        adc = self.spi.xfer2([1, (8 + self.channel) << 4, 0])
        data = ((adc[1] & 3) << 8) + adc[2]
        return data

    def __exit__(self, type, value, traceback):
            self.close()
            
    def close(self):
        self.spi.close()
Beispiel #46
0
	def __init__(self, device=0, chipselect=0, debug=False):
		self.device = device
		self.chipselect = chipselect
		self.debug = debug

		try:
			try:
				# Initialize GPIOs
				GPIO.setmode(GPIO.BCM) # Use Broadcom numbers
				GPIO.setwarnings(False)
				GPIO.setup(self.GPIO_RESET, GPIO.OUT, initial=GPIO.LOW)
				GPIO.setup(self.GPIO_IRQ, GPIO.IN, pull_up_down=GPIO.PUD_OFF)
				GPIO.add_event_detect(self.GPIO_IRQ, GPIO.RISING)
				time.sleep(0.05)
			except RuntimeError as e:
				raise PhyError("Failed to initialize GPIOs: %s" %\
					str(e))

			# Initialize SPI
			try:
				self.spi = SpiDev()
				self.spi.open(device, chipselect)
			except IOError as e:
				raise PhyError("Failed to open SPI device %d.%d: %s" %\
					(device, chipselect, str(e)))
			try:
				self.spi.mode = 0;
				self.spi.bits_per_word = 8;
				self.spi.cshigh = False
				self.spi.lsbfirst = False
				self.spi.max_speed_hz = 200000;
			except IOError as e:
				try:
					self.spi.close()
					self.spi = None
				except:
					pass
				raise PhyError("Failed to configure SPI device %d.%d: %s" %\
					(device, chipselect, str(e)))

			# Get the controller out of hardware reset
			GPIO.output(self.GPIO_RESET, GPIO.HIGH)
			time.sleep(0.2)

			# Send a software reset
			self.sendReset()
			# Upload default config
			self.profibusSetPhyConfig()
		except:
			GPIO.cleanup()
			raise
Beispiel #47
0
class Temperature(object):
    def __init__(self, major=0, minor=0):
        self.spi = SpiDev()
        self.spi.open(major, minor)

    def rawread(self):
        return self.spi.xfer2([0, 0])

    def read(self):
        return self.calc_temp(self.rawread())

    @staticmethod
    def calc_temp(buf):
        return (((buf[0] << 8) | buf[1]) >> 3) * 0.0625

    def cleanup(self):
        self.spi.close()

    def __enter__(self):
        return self

    def __exit__(self, type_, value, traceback):
        self.cleanup()
Beispiel #48
0
 def __init__(self, factory, port, device):
     self._port = port
     self._device = device
     self._interface = None
     if SpiDev is None:
         raise ImportError('failed to import spidev')
     super(LocalPiHardwareSPI, self).__init__()
     pins = SPI_HARDWARE_PINS[port]
     self.pin_factory.reserve_pins(
         self,
         pins['clock'],
         pins['mosi'],
         pins['miso'],
         pins['select'][device]
         )
     self._interface = SpiDev()
     self._interface.open(port, device)
     self._interface.max_speed_hz = 500000
Beispiel #49
0
 def __init__(self, port, device):
     self._device = None
     super(SPIHardwareInterface, self).__init__()
     # XXX How can we detect conflicts with existing GPIO instances? This
     # isn't ideal ... in fact, it's downright crap and doesn't guard
     # against conflicts created *after* this instance, but it's all I can
     # come up with right now ...
     conflicts = (11, 10, 9, (8, 7)[device])
     with _PINS_LOCK:
         for pin in _PINS:
             if pin.number in conflicts:
                 raise GPIOPinInUse(
                     'pin %r is already in use by another gpiozero object' % pin
                 )
     self._device_num = device
     self._device = SpiDev()
     self._device.open(port, device)
     self._device.max_speed_hz = 500000
Beispiel #50
0
    def __init__(self, spidevice=0):
        '''
            Basic constructor for our driver class.

            @param: spidevice - the SPI device to be used.
                Acts as a chip-enable. The Raspberry PI B+ has two such device
                output pins in-built.
                Defaults to 0.

            @return: None
        '''
        if spidevice != 1:
            spidevice = 0

        self.__spi = SpiDev()
        self.__spi.mode = 0b01
        self.__spi.open(0, spidevice)

        self.__buffer = [0] * 24
Beispiel #51
0
 def __init__(self, port=0, device=0):
     self.spi = SpiDev()
     # connect spi object to specified spi device
     self.spi.open(port, device)
 def __init__(self, bus = 0, device = 0, channel = 0):
     self.bus, self.device, self.channel = bus, device, channel
     self.spi = SpiDev()
Beispiel #53
0
 def __init__(self, bus, device, configuration):
     self._bus = bus
     self._device = device
     self._configuration = configuration
     self._spi = SpiDev()
Beispiel #54
0
class cc2500:

    REG_MARCSTATE = 0xC0 | 0x35
    CMD_SRES = 0x30
    CMD_SFSTXON = 0x31
    CMD_SXOFF = 0x32
    CMD_XCAL = 0x33
    CMD_SRX  = 0x34
    CMD_STX  = 0x35
    CMD_SIDLE = 0x36
    CMD_SWOR = 0x38
    CMD_SPWD = 0x39
    CMD_SFRX = 0x3A
    CMD_SFTX = 0x3B
    CMD_SWORRST = 0x3C
    CMD_SNOP = 0x3D
    CMD_PATABLE = 0x3E
    CMD_TXFIFO = 0x3F

    CMD_SINGLE_WRITE = 0x00
    CMD_BRUST_WRITE = 0x40
    CMD_SINGLE_READ  = 0x80
    CMD_BRUST_READ = 0xC0



    # get Main Radio Control State Machine State
    def __init__(self, bus = 0, channel_select = 1):
        self.bus = SpiDev()
        self.bus.open(bus,channel_select)
        self.reset()
        self.buff=[]
        self.run = True
        self.timestamp = time()

    def get_STATE(self):
        return self.bus.xfer2([self.REG_MARCSTATE,0x00])[1]

    def set_reg(self,reg, byte):
        return self.bus.xfer2([reg, byte])

    def get_reg(self, reg):
        return self.bus.xfer2([0x80 | reg, 0x00])

    def info(self):
        state = self.get_STATE()
        txbyte = self.get_TXBYTES()
        rxbyte = self.get_RXBYTES()
        print "state : %d , tx: %d , rx: %d " % (state, txbyte, rxbyte)


    ## 
    ## COMMAND  
    ##
    def STX(self):
        return self.bus.xfer2([self.CMD_STX])

    def SRX(self):
        return self.bus.xfer2([self.CMD_SRX])

    def SIDLE(self):
        return self.bus.xfer2([self.CMD_SIDLE])

    def SFRX(self):
        return self.bus.xfer2([self.CMD_SFRX])
    
    def SFTX(self):
        return self.bus.xfer2([self.CMD_SFTX])

    def SRES(self):
        return self.bus.xfer2([self.CMD_SRES])

    def reset(self):
        self.SRES()
        reg_config = [0x0B, 0x2E, 0x06, 0x07, 0xD3, 0x91, 0x61, 0x04,
                      0x45, 0x00, 0x00, 0x09, 0x00, 0x5D, 0x93, 0xB1,
                      0x2D, 0x3B, 0x73, 0x22, 0xF8, 0x01, 0x07, 0x00,
                      0x18, 0x1D, 0x1C, 0xC7, 0x00, 0xB2, 0x87, 0x6B,
                      0xF8, 0xB6, 0x10, 0xEA, 0x0A, 0x00, 0x11, 0x41,
                      0x00, 0x59, 0x7F, 0x3F, 0x88, 0x31, 0x0B ]
        for reg, val in enumerate(reg_config):
            self.bus.xfer2([reg, val])
        self.SIDLE()
        self.SFRX()
        self.SFTX()



    ## FIFO buffer 64byte
    def send(self,package):
        tmp = []
        if type(package) == str:
            tmp = [ord(i) for i in package]
        else:
            tmp = list(package)
        tmp = [self.CMD_TXFIFO | self.CMD_BRUST_WRITE ,len(tmp)] + tmp
        print "send"
        print tmp
        self.bus.xfer2(tmp)    # write package to fifo buffer (max 64byte)
        if self.get_STATE() == 22:
            self.SFTX()
            self.SIDLE()
            return -1
        self.STX()
        return 0

    def get_package_RXFIFO(self):
        len_FIFO = self.get_RXBYTES()
        p_len = self.get_byte_RXFIFO()
        data = self.bus.xfer2([self.CMD_BRUST_READ | 0x3F for i in range(len_FIFO)])
        self.buff.append(data)
            
    def get_byte_RXFIFO(self):
        return self.bus.xfer2( [ self.CMD_SINGLE_READ | 0x3F , 0x00])[1]

    def set_byte_TXFIFO(self, byte):
        return self.bus.xfer2( [ self.CMD_SINGLE_WRITE | 0x3F , byte])[1]

    def get_TXBYTES(self):
        return self.bus.xfer2([0xC0 | 0x3A, 0x00])[1]

    def get_RXBYTES(self):
        return self.bus.xfer2([0xC0 | 0x3B, 0x00])[1]

    def stop(self):
        self.run = False

    def start(self):
        self.thread = Thread(target=self.receive_loop, args=())
        self.run = True
        self.thread.start()

    def receive_loop(self):
        while self.run :
            state = self.get_STATE()
            rxbytes = self.get_RXBYTES()
            txbytes = self.get_TXBYTES()

            if(state in [13,8,9,10,11]):
                #print state
                sleep(0.1)
                continue

            elif( (state == 1) and (rxbytes > 0)):
                #print state
                self.get_package_RXFIFO()
                self.SRX()

            elif(state == 1):
                #print state
                self.SIDLE()
                self.SRX()

            elif(state == 17):
                #print state
                self.SFRX()
                self.SIDLE()
                self.SRX()

            else:
                #print state
                self.reset()
                sleep(0.1)

            if time() > (self.timestamp + 10 ):
                print "reset"
                self.timestamp = time()
                self.reset()

            sleep(0.1)
            if len(self.buff) > 0:
                data = self.buff.pop(0)[1:-2]
                msg = ''.join([chr(i) for i in data])
                print(msg)
import Adafruit_BBIO.GPIO as GPIO
from spidev import SpiDev
import time
import datetime

spi = SpiDev(1, 0)
spi.mode = 3
spi.max_speed_hz = 200000
#spi.xfer2([0x0])

GPIO.setup("P9_11", GPIO.OUT) # A0 sipm select bit0
GPIO.setup("P9_12", GPIO.OUT) # A1 sipm select bit1
GPIO.setup("P9_13", GPIO.OUT) # A2 sipm select bit2
GPIO.setup("P9_14", GPIO.OUT) # A3 sipm select bit3


GPIO.setup("P9_15", GPIO.OUT) # A5 chip select bit0
GPIO.setup("P9_16", GPIO.OUT) # A6 chip select bit1

#chip select map
# 0: nc
# 1: pga
# 2: temp
# 3: mem


GPIO.output("P9_11", GPIO.LOW)
GPIO.output("P9_12", GPIO.LOW)
GPIO.output("P9_13", GPIO.LOW)
GPIO.output("P9_14", GPIO.LOW)
GPIO.output("P9_15", GPIO.LOW)
Beispiel #56
0
 def __init__(self, bus = 0, device = 0):
     self.bus, self.device = bus, device
     self.spi = SpiDev()
     self.open()
Beispiel #57
0
class CpPhy(object):
	# Profibus baud-rates
	PB_PHY_BAUD_9600	= 0
	PB_PHY_BAUD_19200	= 1
	PB_PHY_BAUD_45450	= 2
	PB_PHY_BAUD_93750	= 3
	PB_PHY_BAUD_187500	= 4
	PB_PHY_BAUD_500000	= 5
	PB_PHY_BAUD_1500000	= 6
	PB_PHY_BAUD_3000000	= 7
	PB_PHY_BAUD_6000000	= 8
	PB_PHY_BAUD_12000000	= 9

	# RTS mode
	PB_PHY_RTS_ALWAYS_LO	= 0
	PB_PHY_RTS_ALWAYS_HI	= 1
	PB_PHY_RTS_SENDING_HI	= 2
	PB_PHY_RTS_SENDING_LO	= 3

	# GPIO numbers (BCM)
	GPIO_RESET		= 17
	GPIO_IRQ		= 27
	GPIO_SS			= 8
	GPIO_MISO		= 9
	GPIO_MOSI		= 10
	GPIO_SCK		= 11

	baud2id = {
		9600		: PB_PHY_BAUD_9600,
		19200		: PB_PHY_BAUD_19200,
		45450		: PB_PHY_BAUD_45450,
		93750		: PB_PHY_BAUD_93750,
		187500		: PB_PHY_BAUD_187500,
		500000		: PB_PHY_BAUD_500000,
		1500000		: PB_PHY_BAUD_1500000,
		3000000		: PB_PHY_BAUD_3000000,
		6000000		: PB_PHY_BAUD_6000000,
		12000000	: PB_PHY_BAUD_12000000,
	}

	def __init__(self, device=0, chipselect=0, debug=False):
		self.device = device
		self.chipselect = chipselect
		self.debug = debug

		try:
			try:
				# Initialize GPIOs
				GPIO.setmode(GPIO.BCM) # Use Broadcom numbers
				GPIO.setwarnings(False)
				GPIO.setup(self.GPIO_RESET, GPIO.OUT, initial=GPIO.LOW)
				GPIO.setup(self.GPIO_IRQ, GPIO.IN, pull_up_down=GPIO.PUD_OFF)
				GPIO.add_event_detect(self.GPIO_IRQ, GPIO.RISING)
				time.sleep(0.05)
			except RuntimeError as e:
				raise PhyError("Failed to initialize GPIOs: %s" %\
					str(e))

			# Initialize SPI
			try:
				self.spi = SpiDev()
				self.spi.open(device, chipselect)
			except IOError as e:
				raise PhyError("Failed to open SPI device %d.%d: %s" %\
					(device, chipselect, str(e)))
			try:
				self.spi.mode = 0;
				self.spi.bits_per_word = 8;
				self.spi.cshigh = False
				self.spi.lsbfirst = False
				self.spi.max_speed_hz = 200000;
			except IOError as e:
				try:
					self.spi.close()
					self.spi = None
				except:
					pass
				raise PhyError("Failed to configure SPI device %d.%d: %s" %\
					(device, chipselect, str(e)))

			# Get the controller out of hardware reset
			GPIO.output(self.GPIO_RESET, GPIO.HIGH)
			time.sleep(0.2)

			# Send a software reset
			self.sendReset()
			# Upload default config
			self.profibusSetPhyConfig()
		except:
			GPIO.cleanup()
			raise

	def cleanup(self):
		self.spi.close()
		self.spi = None
		GPIO.cleanup()

	# Poll for received packet.
	# timeout => In seconds. 0 = none, Negative = unlimited.
	def poll(self, timeout=0):
		limit = TimeLimited(timeout)
		while GPIO.event_detected(self.GPIO_IRQ):
			if limit.exceed():
				return None
			limit.sleep(0.001)
		limit.add(0.5)
		while not limit.exceed():
			fc = self.spi.readbytes(1)[0]
			if fc != CpPhyMessage.RPI_PACK_NOP:
				break
		else:
			return None
		reply = [ fc ]
		reply.extend(self.spi.readbytes(CpPhyMessage.RASPI_PACK_HDR_LEN - 1))
		payloadLen = reply[1] & 0xFF
		if payloadLen:
			reply.extend(self.spi.readbytes(payloadLen))
		message = CpPhyMessage(0)
		message.setRawData(reply)
		if self.debug:
			print("[PHY] recv msg:", message)
		return message

	def __sendMessage(self, message):
		if self.debug:
			print("[PHY] send msg:", message)
		self.spi.writebytes(message.getRawData())

	def sendReset(self):
		self.__sendMessage(CpPhyMessage(CpPhyMessage.RPI_PACK_RESET))
		reply = self.poll(timeout=-1)
		if reply.fc != CpPhyMessage.RPI_PACK_ACK:
			raise PhyError("Failed to reset PHY")

	def profibusSetPhyConfig(self, baudrate=19200,
				 rxTimeoutMs=100,
				 bitErrorChecks=True,
				 rtsMode=PB_PHY_RTS_SENDING_HI):
		try:
			baudID = self.baud2id[baudrate]
		except KeyError:
			raise PhyError("Invalid baud-rate")
		if rxTimeoutMs < 1 or rxTimeoutMs > 255:
			raise PhyError("Invalid RX timeout")
		payload = [ baudID,
			    rxTimeoutMs,
			    1 if bitErrorChecks else 0,
			    rtsMode & 0xFF ]
		message = CpPhyMessage(CpPhyMessage.RPI_PACK_SETCFG, payload)
		self.__sendMessage(message)
		reply = self.poll(timeout=-1)
		if reply.fc != CpPhyMessage.RPI_PACK_ACK:
			raise PhyError("Failed to upload config")

	def profibusSend_SDN(self, telegramData):
		self.__sendMessage(CpPhyMessage(CpPhyMessage.RPI_PACK_PB_SDN,
						telegramData))

	def profibusSend_SRD(self, telegramData):
		self.__sendMessage(CpPhyMessage(CpPhyMessage.RPI_PACK_PB_SRD,
						telegramData))
Beispiel #58
0
class SPIHardwareInterface(Device):
    def __init__(self, port, device):
        self._device = None
        super(SPIHardwareInterface, self).__init__()
        # XXX How can we detect conflicts with existing GPIO instances? This
        # isn't ideal ... in fact, it's downright crap and doesn't guard
        # against conflicts created *after* this instance, but it's all I can
        # come up with right now ...
        conflicts = (11, 10, 9, (8, 7)[device])
        with _PINS_LOCK:
            for pin in _PINS:
                if pin.number in conflicts:
                    raise GPIOPinInUse(
                        'pin %r is already in use by another gpiozero object' % pin
                    )
        self._device_num = device
        self._device = SpiDev()
        self._device.open(port, device)
        self._device.max_speed_hz = 500000

    def close(self):
        if self._device:
            try:
                self._device.close()
            finally:
                self._device = None
        super(SPIHardwareInterface, self).close()

    @property
    def closed(self):
        return self._device is None

    def __repr__(self):
        try:
            self._check_open()
            return (
                "hardware SPI on clock_pin=11, mosi_pin=10, miso_pin=9, "
                "select_pin=%d" % (
                    8 if self._device_num == 0 else 7))
        except DeviceClosed:
            return "hardware SPI closed"

    def read(self, n):
        return self.transfer((0,) * n)

    def write(self, data):
        return len(self.transfer(data))

    def transfer(self, data):
        """
        Writes data (a list of integer words where each word is assumed to have
        :attr:`bits_per_word` bits or less) to the SPI interface, and reads an
        equivalent number of words, returning them as a list of integers.
        """
        return self._device.xfer2(data)

    def _get_clock_mode(self):
        return self._device.mode

    def _set_clock_mode(self, value):
        self._device.mode = value

    def _get_clock_polarity(self):
        return bool(self.mode & 2)

    def _set_clock_polarity(self, value):
        self.mode = self.mode & (~2) | (bool(value) << 1)

    def _get_clock_phase(self):
        return bool(self.mode & 1)

    def _set_clock_phase(self, value):
        self.mode = self.mode & (~1) | bool(value)

    def _get_lsb_first(self):
        return self._device.lsbfirst

    def _set_lsb_first(self, value):
        self._device.lsbfirst = bool(value)

    def _get_select_high(self):
        return self._device.cshigh

    def _set_select_high(self, value):
        self._device.cshigh = bool(value)

    def _get_bits_per_word(self):
        return self._device.bits_per_word

    def _set_bits_per_word(self, value):
        self._device.bits_per_word = value

    clock_polarity = property(_get_clock_polarity, _set_clock_polarity)
    clock_phase = property(_get_clock_phase, _set_clock_phase)
    clock_mode = property(_get_clock_mode, _set_clock_mode)
    lsb_first = property(_get_lsb_first, _set_lsb_first)
    select_high = property(_get_select_high, _set_select_high)
    bits_per_word = property(_get_bits_per_word, _set_bits_per_word)
Beispiel #59
0
class SPIDataLink(FullDuplexDataLink):
    """Clase que gestiona un enlace Serial Peripheral Interface (SPI).

    :param bus: Identificador del bus SPI que se usa para el enlace de datos.
    :param device: Línea de selección de chip SPI activa en el enlace de datos.
    :param configuration: Configuración del enlace de datos

    Ejemplo de uso:

    >>> from pida.links import SPIDataLinkConfiguration, SPIDataLink
    >>> configuration = SPIDataLinkConfiguration(mode=0, max_speed_hz=32000000)
    >>> with SPIDataLink(0, 0, configuration) as link:
            request = [0x00, 0x01, 0xFF]
            response = link.transfer(request)
    >>> response
    [0, 1, 255]
    """
    def __init__(self, bus, device, configuration):
        self._bus = bus
        self._device = device
        self._configuration = configuration
        self._spi = SpiDev()

    def _apply_configuration(self):
        self._spi.mode = self._configuration.mode
        self._spi.max_speed_hz = self._configuration.max_speed_hz

    @property
    def bus(self):
        """Identificador del bus SPI que se usa para el enlace de datos.

        .. note:: Raspberry Pi ofrece a través de su puerto GPIO
                  un único bus SPI cuyo identificador es 0.

        Es una propiedad de sólo lectura.
        """
        return self._bus

    @property
    def device(self):
        """Línea de selección de chip SPI activa en el enlace de datos.

        .. note:: El bus SPI 0 de Raspberry Pi puede, a través del puerto GPIO,
                  activar dos líneas de selección de chip SPI: 0 y 1.

        Es una propiedad de sólo lectura.
        """
        return self._device

    def open(self):
        self._spi.open(self._bus, self._device)
        self._apply_configuration()

    def close(self):
        self._spi.close()

    def transfer(self, data):
        return self._spi.xfer2(data)

    def __enter__(self):
        self.open()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

    @property
    def max_speed_hz(self):
        return self._configuration.max_speed_hz

    @property
    def mode(self):
        return self._configuration.mode
	print "read eeprom"
	cmd = [0x03, 0] + [0 for i in range(8*16)]
	res = spi.xfer2(cmd)
	print res


if __name__ == "__main__":
	GPIO.setup("P9_11", GPIO.OUT)
	GPIO.setup("P9_12", GPIO.OUT)
	GPIO.setup("P9_13", GPIO.OUT)
	GPIO.setup("P9_14", GPIO.OUT)
	GPIO.setup("P9_15", GPIO.OUT)

	#spi = SPI()
	#spi.open(0, 0)
	#spi.msh = 0

	spi = SpiDev(1,0)
	spi.mode = 3
	spi.max_speed_hz = 100000


	check_eeprom_status()
	write_eeprom(3, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])

	GPIO.cleanup()
	spi.close()