2017-05-31 52 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