I have programmed an ATtiny1627 as I2C slave to answer to the read_i2c_block_data()
function. Basically it receives the command indicating which variable to return and answers with 4 bytes
representing a float
. A Raspberry Pi 4 is the I2C master and has to read the data every 500ms, however the following code does not work:
main.py
import time
from smbus import SMBus
from struct import unpack
i2c = SMBus(1)
for i in range(10):
#address: 0x0A, command: 0x54, get 4bytes
bytes = i2c.read_i2c_block_data(0x0A, 0x54, 4)
[result] = unpack('f', bytearray(bytes))
print(result)
time.sleep(.5)
running main.py results in:
>sudo python3 main.py
100
100
nan
nan
nan
nan
nan
nan
nan
nan
Strangely, if the code is as follows it works perfectly:
test.py
from smbus import SMBus
from struct import unpack
i2c = SMBus(1)
bytes = i2c.read_i2c_block_data(0x0A, 0x54, 4)
[result] = unpack('f', bytearray(bytes))
print(result)
and main2.py
import os, time
for i in range(10):
os.system('sudo python3 test.py')
time.sleep(.5)
running main2.py:
>sudo python3 main2.py
100
100
100
100
100
100
100
100
100
100
This is not optimal as I cannot transfer easily the data from test.py
to main2.py
in order to process it.
I have tried other combinations with unsatisfactory results:
- Defining a method in
test.py
and importing it tomain2.py
does not work. - Using multiprocessing and creating a new process for each loop does not work.
- Using
with SMBus(1) as i2c:
raisesAtributeError: __enter__
as the class misses this methods.
I think it has something to do with from smbus import SMBus
as it is the only command that is re-executed when calling sudo python3 test.py
but not re-executed when importing the method into main2.py
.
Am I missing something like read_i2c_block_data()
not sending the Start signal after x seconds or similar?