当前位置: 首页>>代码示例>>Python>>正文


Python SpiDev.open方法代码示例

本文整理汇总了Python中spidev.SpiDev.open方法的典型用法代码示例。如果您正苦于以下问题:Python SpiDev.open方法的具体用法?Python SpiDev.open怎么用?Python SpiDev.open使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在spidev.SpiDev的用法示例。


在下文中一共展示了SpiDev.open方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: dac8568

# 需要导入模块: from spidev import SpiDev [as 别名]
# 或者: from spidev.SpiDev import open [as 别名]
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)
开发者ID:bgamari,项目名称:libbeagledaq,代码行数:32,代码来源:beagledaq.py

示例2: ad7606

# 需要导入模块: from spidev import SpiDev [as 别名]
# 或者: from spidev.SpiDev import open [as 别名]
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
开发者ID:bgamari,项目名称:libbeagledaq,代码行数:29,代码来源:beagledaq.py

示例3: MCP3008

# 需要导入模块: from spidev import SpiDev [as 别名]
# 或者: from spidev.SpiDev import open [as 别名]
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()
开发者ID:TheRinger,项目名称:python-gpiozero,代码行数:29,代码来源:input_devices.py

示例4: AnalogInputDevice

# 需要导入模块: from spidev import SpiDev [as 别名]
# 或者: from spidev.SpiDev import open [as 别名]
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)
开发者ID:tjguk,项目名称:python-gpiozero,代码行数:55,代码来源:input_devices.py

示例5: SpiDevice

# 需要导入模块: from spidev import SpiDev [as 别名]
# 或者: from spidev.SpiDev import open [as 别名]
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()
开发者ID:cberes,项目名称:raspberry-pi-weather,代码行数:16,代码来源:spi_device.py

示例6: run

# 需要导入模块: from spidev import SpiDev [as 别名]
# 或者: from spidev.SpiDev import open [as 别名]
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()
开发者ID:paulollivier,项目名称:greenpi,代码行数:50,代码来源:GreenPi.py

示例7: __init__

# 需要导入模块: from spidev import SpiDev [as 别名]
# 或者: from spidev.SpiDev import open [as 别名]
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()
开发者ID:joneskys7,项目名称:pi,代码行数:18,代码来源:MCP3008.py

示例8: AnalogInputDevice

# 需要导入模块: from spidev import SpiDev [as 别名]
# 或者: from spidev.SpiDev import open [as 别名]
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)
开发者ID:chatzin,项目名称:python-gpiozero,代码行数:43,代码来源:input_devices.py

示例9: MCP3008

# 需要导入模块: from spidev import SpiDev [as 别名]
# 或者: from spidev.SpiDev import open [as 别名]
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
开发者ID:stevelorenz,项目名称:codes-on-rasp,代码行数:42,代码来源:mcp3008.py

示例10: __init__

# 需要导入模块: from spidev import SpiDev [as 别名]
# 或者: from spidev.SpiDev import open [as 别名]
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()
开发者ID:martinohanlon,项目名称:PiLadyAnneRadio,代码行数:24,代码来源:MCP3008.py

示例11: Temperature

# 需要导入模块: from spidev import SpiDev [as 别名]
# 或者: from spidev.SpiDev import open [as 别名]
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()
开发者ID:bwduncan,项目名称:autoboiler,代码行数:25,代码来源:autoboiler.py

示例12: LocalPiHardwareSPI

# 需要导入模块: from spidev import SpiDev [as 别名]
# 或者: from spidev.SpiDev import open [as 别名]
class LocalPiHardwareSPI(SPI, Device):
    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

    def close(self):
        if getattr(self, '_interface', None):
            self._interface.close()
        self._interface = None
        self.pin_factory.release_all(self)
        super(LocalPiHardwareSPI, self).close()

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

    def __repr__(self):
        try:
            self._check_open()
            return 'SPI(port=%d, device=%d)' % (self._port, self._device)
        except DeviceClosed:
            return 'SPI(closed)'

    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._interface.xfer2(data)

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

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

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

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

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

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

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

    def _set_bits_per_word(self, value):
        self._interface.bits_per_word = value
开发者ID:DirkUK,项目名称:python-gpiozero,代码行数:71,代码来源:local.py

示例13: AnalogInputDevice

# 需要导入模块: from spidev import SpiDev [as 别名]
# 或者: from spidev.SpiDev import open [as 别名]
class AnalogInputDevice(CompositeDevice):
    """
    Represents an analog input device connected to SPI (serial interface).

    Typical analog input devices are `analog to digital converters`_ (ADCs).
    Several classes are provided for specific ADC chips, including
    :class:`MCP3004`, :class:`MCP3008`, :class:`MCP3204`, and :class:`MCP3208`.

    The following code demonstrates reading the first channel of an MCP3008
    chip attached to the Pi's SPI pins::

        from gpiozero import MCP3008

        pot = MCP3008(0)
        print(pot.value)

    The :attr:`value` attribute is normalized such that its value is always
    between 0.0 and 1.0 (or in special cases, such as differential sampling,
    -1 to +1). Hence, you can use an analog input to control the brightness of
    a :class:`PWMLED` like so::

        from gpiozero import MCP3008, PWMLED

        pot = MCP3008(0)
        led = PWMLED(17)
        led.source = pot.values

    .. _analog to digital converters: https://en.wikipedia.org/wiki/Analog-to-digital_converter
    """

    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 bits(self):
        """
        The bit-resolution of the device/channel.
        """
        return self._bits

    @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):
        """
        The current value read from the device, scaled to a value between 0 and
        1.
        """
        return self._read() / (2 ** self.bits - 1)

    @property
    def raw_value(self):
        """
        The raw value as read from the device.
        """
        return self._read()
开发者ID:calufrax,项目名称:python-gpiozero,代码行数:93,代码来源:input_devices.py

示例14: Matrix

# 需要导入模块: from spidev import SpiDev [as 别名]
# 或者: from spidev.SpiDev import open [as 别名]
class Matrix(object):
    '''
        The class which models the operation of the Olimex 8x8 RGB LED matrix.
        The numbering scheme used when defining the pins are with respect to
        the BCM numbering scheme.

        Wiring:
            - VCC = driving voltage for the matrix. 5 volts.
            - GND = ground connection from the matrix.
            - DIN = data in for the matrix, GPIO pin 10 (SPI MOSI).
            - CS = chip select, depending on SPI channel selection.
            - CLK = serial clock, GPIO pin 11 (SPI SCK).

    '''
    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

    def drawpixel(self, pixel):
        '''
            Draws a given Pixel object to the internal buffer.
            The buffer is formed of 24 bytes.
            Each byte represents a single color, the n'th bit being whether
            that particular color is active in the n'th led of that row.
            The colors are ordered in reverse. (BGR).

            @param: pixel - a Pixel object.

            @return: the Pixel encoded as a byte.
        '''
        # current row we're on:
        row = 3 * pixel.y

        # clear currently present color by unsetting the corresponding bit from
        # the three color bytes:
        self.__buffer[row] &= ~(1 << pixel.x)       # clear red.
        self.__buffer[row + 1] &= ~(1 << pixel.x)   # clear green.
        self.__buffer[row + 2] &= ~(1 << pixel.x)   # clear blue.

        # set red bit for this pixel, if necessary:
        if pixel.color in [Color.red, Color.white, Color.brown, Color.purple]:
            self.__buffer[row] |= 1 << pixel.x
        # set green bit:
        if pixel.color in [Color.green, Color.white, Color.turquoise, Color.brown]:
            self.__buffer[row + 1] |= 1 << pixel.x
        # set blue bit:
        if pixel.color in [Color.blue, Color.white, Color.turquoise, Color.purple]:
            self.__buffer[row + 2] |= 1 << pixel.x

    def write(self):
        '''
            Serially writes the whole of the video buffer to the matrix.
        '''
        self.__spi.xfer(self.__buffer)

    def clear(self):
        '''
            Clears both the internal buffer and the matrix.
        '''
        self.__buffer = [0] * 24
        self.write()

    def cleanup(self):
        '''
            Clears all registers and terminates the SPI connection.
        '''
        self.clear()
        self.__spi.close()
开发者ID:aznashwan,项目名称:pytris,代码行数:86,代码来源:matrix.py

示例15: SPIHardwareInterface

# 需要导入模块: from spidev import SpiDev [as 别名]
# 或者: from spidev.SpiDev import open [as 别名]
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)
开发者ID:EdwardBetts,项目名称:python-gpiozero,代码行数:100,代码来源:spi.py


注:本文中的spidev.SpiDev.open方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。