在 python 中写入数据以向 i2c 注册

Write data to register with i2c in python

我需要使用 raspberry pi 和 python 更改 MLX96014 温度传感器 eeprom 中的值。我可以毫无问题地读取它的 ram 和 eeprom,但我不能写入它。此外,由于某种原因,我发现每个 python MLX96014 库都没有实现此功能。我试着用 arduino 做这个,它很适合这个功能:

void Adafruit_MLX90614::write16(uint8_t a, uint16_t v) {
  // a is register address
  // v value to write to eeprom 
  // _addr is device address (0x5a)
  uint8_t pec;
  uint8_t pecbuf[4];

  pecbuf[0] = _addr << 1;
  pecbuf[1] = a;
  pecbuf[2] = v & 0xff;
  pecbuf[3] = v >> 8;
  pec = crc8(pecbuf, sizeof pecbuf);

  Wire.beginTransmission(_addr); // start transmission to device
  Wire.write(a);                 // sends register address to write
  Wire.write(v & 0xff);          // lo
  Wire.write(v >> 8);            // hi
  Wire.write(pec);               // pec
  Wire.endTransmission(true);    // end transmission
}

所以我尝试在python中重写这个函数:

import board
import busio as io
import adafruit_mlx90614
import time
from smbus2 import SMBus, i2c_msg
import crc8
import sys

i2c = io.I2C(board.SCL, board.SDA, frequency=100000)
mlx = adafruit_mlx90614.MLX90614(i2c)

buf = bytearray(4)
buf[0] = 0x5a<<1
buf[1] = 0x24
buf[2] = 0 & 0xff
buf[3] = 0 >>8
pec = crc8.crc8()
pec.update(buf)
pec = pec.hexdigest() # = 0x28

i2c.writeto(0x5a, bytes([0x24]), stop=False)
buffer = bytearray(3)
buffer[0] = 0 & 0xFF
buffer[1] = (0 >> 8) & 0xFF
buffer[2] = 0x28
i2c.writeto(0x5a, buffer, stop=True)

i2cbus = SMBus(1)
emissivity=i2cbus.read_word_data(0x5a,0x24)
print(emissivity) # prints 65535 which is default

代码执行无误。 i2c.writeto() returns “None”。那么我在那里缺少什么?

编辑:

我在数据表中找到了这个 (link),但它让我很困惑。在数据表中它说写命令位低而读高。但在示例中,两个操作都使用低。而且看起来我应该发送 0xb4 字节而不是 0x5a,但是把它放在 pyhton 代码中的什么地方?如果我把它放在 i2c.writeto() 第一个参数中,那么我会得到 I/O 错误,因为模块在地址 5a 上(i2cdetect 显示)。

顺便说一下,我现在无法访问示波器。

communication example

我不知道为什么提供的 python 代码不起作用,但我尝试了其他 i2c 库,它开始工作了。这是代码片段:

import board
import busio as io
import crc8
import adafruit_mlx90614
import adafruit_bus_device.i2c_device as ada_i2c
import time

def change_emissivity(value,i2c):
    new_emissivity=round(65535*value)
    buf=bytearray(4)
    buf[0]=0x24
    buf[1]=0x00
    buf[2]=0x00
    buf[3]=0x28  # kai irasomi nuliai
    
    device=ada_i2c.I2CDevice(i2c,0x5a)
    
    with device:
        device.write(buf)
        
    time.sleep(0.01)
    
    buf[0]=0x5a<<1
    buf[1]=0x24
    buf[2]=new_emissivity & 0xff
    buf[3]=(new_emissivity >> 8) & 0xFF
    pec=crc8.crc8()
    pec.update(buf)
    pec=int(pec.hexdigest(),base=16)
    
    buf[0]=0x24
    buf[1]=new_emissivity & 0xff
    buf[2]=(new_emissivity >> 8) & 0xFF
    buf[3]=pec
    
    print(new_emissivity)
    
i2c = io.I2C(board.SCL, board.SDA, frequency=100000)
mlx = adafruit_mlx90614.MLX90614(i2c)
change_emissivity(0.8, i2c)

print("New emissivity: %.2f" %mlx._read_16(0x24))

while(True):
    
    print("Ambient Temp: %.2f" %mlx.ambient_temperature
    print("Object Temp: %.2f" %mlx.object_temperature

    time.sleep(3)