]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/generic_linux/i2c.py
Updates to Blinka to use the PureIO SPI library
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / generic_linux / i2c.py
1 import Adafruit_PureIO.smbus as smbus
2 import time
3
4 class I2C:
5     MASTER = 0
6     SLAVE = 1
7     _baudrate = None
8     _mode = None
9     _i2c_bus = None
10
11     def __init__(self, bus_num, mode=MASTER, baudrate=None):
12         if mode != self.MASTER:
13             raise NotImplementedError("Only I2C Master supported!")
14         _mode = self.MASTER
15
16         #if baudrate != None:
17         #    print("I2C frequency is not settable in python, ignoring!")
18         
19         try:
20             self._i2c_bus = smbus.SMBus(bus_num)
21         except FileNotFoundError:
22             raise RuntimeError("I2C Bus #%d not found, check if enabled in config!" % bus_num)
23
24     def scan(self):
25         """Try to read a byte from each address, if you get an OSError it means the device isnt there"""
26         found = []
27         for addr in range(0,0x80):
28             try:
29                 self._i2c_bus.read_byte(addr)
30             except OSError:
31                 continue
32             found.append(addr)
33         return found
34
35     def writeto(self, address, buffer, *, start=0, end=None, stop=True):
36         if end is None:
37             end = len(buffer)
38         self._i2c_bus.write_bytes(address, buffer[start:end])
39
40     def readfrom_into(self, address, buffer, *, start=0, end=None, stop=True):
41         if end is None:
42             end = len(buffer)
43         
44         readin = self._i2c_bus.read_bytes(address, end-start)
45         for i in range(end-start):
46             buffer[i+start] = readin[i]
47
48     def writeto_then_readfrom(self, address, buffer_out, buffer_in, *,
49                        out_start=0, out_end=None,
50                        in_start=0, in_end=None, stop=False):
51         if out_end is None:
52             out_end = len(buffer_out)        
53         if in_end is None:
54             in_end = len(buffer_in)
55         if stop:
56             # To generate a stop in linux, do in two transactions
57             self.writeto(address, buffer_out, start=out_start, end=out_end, stop=True)
58             self.readfrom_into(address, buffer_in, start=in_start, end=in_end)
59         else:
60             # To generate without a stop, do in one block transaction
61             readin = self._i2c_bus.read_i2c_block_data(address, buffer_out[out_start:out_end], in_end-in_start)
62             for i in range(in_end-in_start):
63                 buffer_in[i+in_start] = readin[i]
64