2017-05-31 76 views
0

我有一个关于从Raspberry Pi到mcp3008的数据传输的问题。这只是一个理论上的问题。当它们交换字节时,主机发送1个字节并接收1个字节。然后发送第二个字节并接收第二个字节。或者,主机发送3个字节,然后接收3个字节。从我的理解来看,这是第一个,对吗?数据传输Pi/MCP3008

回答

0

Adafruit的MCP3008库有你的答案。检查出read_adc()功能:

def read_adc(self, adc_number): 
    """Read the current value of the specified ADC channel (0-7). The values 
    can range from 0 to 1023 (10-bits). 
    """ 
    assert 0 <= adc_number <= 7, 'ADC number must be a value of 0-7!' 
    # Build a single channel read command. 
    # For example channel zero = 0b11000000 
    command = 0b11 << 6     # Start bit, single channel read 
    command |= (adc_number & 0x07) << 3 # Channel number (in 3 bits) 
    # Note the bottom 3 bits of command are 0, this is to account for the 
    # extra clock to do the conversion, and the low null bit returned at 
    # the start of the response. 
    resp = self._spi.transfer([command, 0x0, 0x0]) 
    # Parse out the 10 bits of response data and return it. 
    result = (resp[0] & 0x01) << 9 
    result |= (resp[1] & 0xFF) << 1 
    result |= (resp[2] & 0x80) >> 7 
    return result & 0x3FF 

看来,它发送一个三字节命令(其中只有一个字节是非零的):

resp = self._spi.transfer([command, 0x0, 0x0]) 

的响应是三个字节含有填充10位ADC值。

resp = self._spi.transfer([command, 0x0, 0x0]) 
# Parse out the 10 bits of response data and return it. 
result = (resp[0] & 0x01) << 9 
result |= (resp[1] & 0xFF) << 1 
result |= (resp[2] & 0x80) >> 7