当我尝试从MCP3424 ADC读取数据时,得到了意外的错误结果。我知道设备已连接,但是我正在阅读的结果是错误的
我写入ADC的通道3和4。当我读回结果时,配置寄存器中的数据与我编程的数据不匹配
import smbus
import time
# Get I2C bus
bus = smbus.SMBus(1)
# I2C address of the device
MCP3425_DEFAULT_ADDRESS = 0x68
# MCP3425 Configuration Command Set
MCP3425_CMD_NEW_CNVRSN = 0x80 # Initiate a new conversion(One-Shot Conversion mode only)
MCP3425_CMD_MODE_CONT = 0x10 # Continuous Conversion Mode
MCP3425_CMD_MODE_ONESHOT = 0x00 # One-Shot Conversion Mode
MCP3425_CMD_SPS_240 = 0x00 # 240 SPS (12-bit)
MCP3425_CMD_SPS_60 = 0x04 # 60 SPS (14-bit)
MCP3425_CMD_SPS_15 = 0x08 # 15 SPS (16-bit)
MCP3425_CMD_GAIN_1 = 0x00 # PGA Gain = 1V/V
MCP3425_CMD_GAIN_2 = 0x01 # PGA Gain = 2V/V
MCP3425_CMD_GAIN_4 = 0x02 # PGA Gain = 4V/V
MCP3425_CMD_GAIN_8 = 0x03 # PGA Gain = 8V/V
MCP3425_CMD_READ_CNVRSN = 0x00 # Read Conversion Result Data
MCP3425_CMD_CH4 =0x60
MCP3425_CMD_CH3 =0x40
class MCP3425():
def __init__(self):
self.config_command()
def config_command(self):
"""Select the Configuration Command from the given provided values"""
CONFIG_CMD4 = (MCP3425_CMD_CH4| MCP3425_CMD_MODE_CONT | MCP3425_CMD_SPS_60 | MCP3425_CMD_GAIN_2)
bus.write_byte(MCP3425_DEFAULT_ADDRESS, CONFIG_CMD4)
CONFIG_CMD3 = (MCP3425_CMD_CH3| MCP3425_CMD_MODE_CONT | MCP3425_CMD_SPS_240 | MCP3425_CMD_GAIN_1)
bus.write_byte(MCP3425_DEFAULT_ADDRESS, CONFIG_CMD3)
print ('-C-', CONFIG_CMD4, CONFIG_CMD3)
def read_adc(self, channel):
"""Read data back from MCP3425_CMD_READ_CNVRSN(0x00), 2 bytes
raw_adc MSB, raw_adc LSB"""
data = bus.read_i2c_block_data(MCP3425_DEFAULT_ADDRESS, (MCP3425_CMD_READ_CNVRSN | channel), 3)
print (channel, data)
# Convert the data to 12-bits
raw_adc = ((data[0] & 0x0F) * 256) + data[1]
if raw_adc > 2047 :
raw_adc -= 4095
return {'r' : raw_adc}
#from MCP3425 import MCP3425
mcp3425 = MCP3425()
while True :
adc = mcp3425.read_adc(MCP3425_CMD_CH4)
print ("Digital Value of Analog Input 4: %d "%(adc['r']))
adc = mcp3425.read_adc(MCP3425_CMD_CH3)
print ("Digital Value of Analog Input 3: %d "%(adc['r']))
print (" ********************************* ")
time.sleep(0.8)
我将117(01110101)写入通道4,并将80(01010000)写入通道3配置寄存器。这意味着对于两个通道,我都应该取回3个字节:2个数据字节和1个配置寄存器字节
这是我得到的打印输出,没有读取任何值(Ch4 +连接到分压器(2.5v),Ch4-和Ch3-连接到地,Ch3 +悬空),字节3只是地址,不是配置寄存器
-C- 117 80
96 [0, 0, 96]
Digital Value of Analog Input 4: 0
64 [0, 0, 64]
Digital Value of Analog Input 3: 0
*********************************
答案 0 :(得分:0)
现在花了一些时间,但我发现了问题。 诀窍在于,MCP3434不是4通道ADC,而是具有4输入多路复用器的单个ADC。一旦意识到这一点,数据表中的原理图就显而易见了。只是在有关如何处理I2C总线上的数据流的说明中没有很好地解释。
因此,您不能配置两个ADC进行并行测量,但是当您需要读取更多通道时,您必须
1)配置/启动频道1
2)读取数据
3)配置/启动频道2
4)读取数据
因此,读取数据步骤与通道无关。