]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/raspi_23/spi.py
SPI write/readinto work, tested with BME280
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / raspi_23 / spi.py
1 import spidev
2 import time
3
4 class SPI:
5     MSB = 0
6     LSB = 1
7     CPHA = 1
8     CPOL = 2
9
10     baudrate = 100000
11     mode = 0
12     bits = 8
13
14     def __init__(self, portid):
15         self._port = portid
16         self._spi = spidev.SpiDev()
17
18     def init(self, baudrate=100000, polarity=0, phase=0, bits=8,
19                   firstbit=MSB, sck=None, mosi=None, miso=None):
20         mode = 0
21         if polarity:
22             mode |= CPOL
23         if phase:
24             mode |= CPHA
25
26         self.clock_pin = sck
27         self.mosi_pin = mosi
28         self.miso_pin = miso
29         self.baudrate = baudrate
30         self.mode = mode
31         self.bits = bits
32
33     def write(self, buf):
34         if not buf:
35             return
36         try:
37             self._spi.open(self._port, 0)
38             try:
39               self._spi.no_cs = True  # this doesn't work but try anyways
40             except AttributeError:
41               pass
42             self._spi.max_speed_hz = self.baudrate
43             self._spi.mode = self.mode
44             self._spi.bits_per_word = self.bits
45             self._spi.writebytes([x for x in buf])
46             self._spi.close()
47         except FileNotFoundError as not_found:
48             print("Could not open SPI device - check if SPI is enabled in kernel!")
49             raise
50
51     def readinto(self, buf):
52         if not buf:
53             return
54         try:
55             self._spi.open(self._port, 0)
56             try:
57               self._spi.no_cs = True  # this doesn't work but try anyways
58             except AttributeError:
59               pass
60             self._spi.max_speed_hz = self.baudrate
61             self._spi.mode = self.mode
62             self._spi.bits_per_word = self.bits
63             data = self._spi.readbytes(len(buf))
64             for i in range(len(buf)):  # 'readinto' the given buffer
65               buf[i] = data[i]
66             self._spi.close()
67         except FileNotFoundError as not_found:
68             print("Could not open SPI device - check if SPI is enabled in kernel!")
69             raise