How to Use I2C with XC16 Using MCC - Microchip

走远了吗. 提交于 2020-03-05 04:58:49

问题


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:

  1. Setup START condition (HIGH to LOW transition of SDA while SCL is HIGH)
  2. Send I2C device address (7 bit address + bit0 = 0 to write)
  3. Slave sends: ACK
  4. Send I2C register address that you want to read (8 bits) (in your case it is the Pressure data)
  5. Slave sends: ACK
  6. Repeated START (HIGH to LOW transition of SDA while SCL is HIGH)
  7. Send I2C device address (7 bit address + bit0 = 1 to read)
  8. Slave sends: ACK
  9. Slave sends: MSB of Pressure Data
  10. Master sends: ACK
  11. Slave sends: LSB of Pressure Data
  12. Master sends: NACK
  13. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!