![](/img/trans.png)
[英]How to get data from I2C device BH1750 over USB-I2C module in Python3?
[英]I2C data-get in Python on Raspberry Pi providing strange data
使用 PCF8591 模數轉換器 (ADC) 構建設備以讀取模數電壓。
ADC 通過 i2c 連接,並成功地為通過端子連接時的各種輸入電壓提供對應於 0 到 255 之間的值的 HEX 值:
pi@raspberrypi:~ $ sudo i2cget -y 0 0x48
0x38
pi@raspberrypi:~ $ sudo i2cget -y 0 0x48
0x3a
pi@raspberrypi:~ $ sudo i2cget -y 0 0x48
0x44
pi@raspberrypi:~ $ sudo i2cget -y 0 0x48
0x3d
0x38 = 56 ; 0x3a = 58 .. 等等。
通過 Python 運行相同的應用程序時,我得到一個錯誤。
以下是我的源代碼:
import time
import smbus
i2c_ch = 0 #channel we're running on with i2c
#address on the I2C bus of the ADC
i2c_address = 0x48
bus = smbus.SMBus(i2c_ch)
# Print out temperature every second
while True:
temperature = bus.read_i2c_block_data(i2c_address, 0)
print(temperature)
time.sleep(1)
這是輸出:
[0, 0, 16, 12, 9, 7, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 5, 3, 3, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 5, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 12, 8, 6, 5, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 12, 9, 7, 5, 3, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 6, 4, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 5, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 9, 7, 6, 4, 3, 3, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
這些錯誤是什么,它們是什么意思,如何更新我的 Python 腳本以正確讀取 I2C 上的模數轉換器?
根據文檔, read_i2c_block_data
將返回一個包含 32 個字節的數組。
要一次讀取一個字節,您需要使用read_byte_data
while True:
temperature = bus.read_byte_data(i2c_address, 0)
print(f"byte: {temperature}, hex: {temperature.hex()}")
time.sleep(1)
下面的代碼有效,問題是三方面的:
一些文檔還建議您先閱讀一次 pin,然后再閱讀一次,與第一次閱讀有關的內容只是讀取之前的內容。
下面的代碼將成功讀取 0 - 255 范圍內的電壓:
bus = smbus.SMBus(0) # (0) Ensures the i2c bus used in the Pi
bus.write_byte(0x48, 0x02) # Before you can read, you need to write
# 0x02 represents Analog in Pin #2
while True:
temperature = bus.read_byte_data(i2c_address, 0x02)
print(temperature)
time.sleep(1)
這適用於 PCF8591 模數轉換器 (ADC) 上的所有輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.