问题
This is the first time I've attempted to use I2C for my design so bear with me. I've used the MCC to set up I2C and I have I2C.c and I2C.h. I'm trying to read a pressure sensor value. The value is 15 bits long. Do I need to write to the slave before I read or can I just read the value straight away? I've put part of my code below. You can see that I'm only trying to read a pressure value. Can anyone point me in the right direction of how to achieve this? Thanks guys.
NOTE: Using a PIC24FJ128GB204 with the xc16 compiler
I2C1_MESSAGE_STATUS status;
uint8_t PressureCommand = 1; //1 indicates a read
uint16_t address = 0xE0;
uint16_t PressureData;
uint8_t length = 2; //2 bytes of data
//Request to read 2 bytes of data
I2C1_MasterRead(&PressureData, length, address, &status);
while(I2C1_MESSAGE_PENDING == status)
回答1:
Yes, you do need to "write" to the slave before being able to read something. The usual procedure looks like this:
- Setup START condition (HIGH to LOW transition of SDA while SCL is HIGH)
- Send I2C device address (7 bit address + bit0 = 0 to write)
- Slave sends: ACK
- Send I2C register address that you want to read (8 bits) (in your case it is the Pressure data)
- Slave sends: ACK
- Repeated START (HIGH to LOW transition of SDA while SCL is HIGH)
- Send I2C device address (7 bit address + bit0 = 1 to read)
- Slave sends: ACK
- Slave sends: MSB of Pressure Data
- Master sends: ACK
- Slave sends: LSB of Pressure Data
- Master sends: NACK
- Send STOP (a LOW to HIGH transition of SDA while SCL is HIGH)
In your case the Pressure data is a two byte value. However, in step 4 you only need to ask for the first byte but still expecting two bytes to receive.
Edit: You might also want to look at this forum thread.
来源:https://stackoverflow.com/questions/60324465/how-to-use-i2c-with-xc16-using-mcc-microchip