Reputation: 92
I am testing an I2C protocol with an STM32 microcontroller. I made a function that should read 16-bit content of a register within the slave device the microcontroller will be talking to. My question does not really revolve around the hardware, but of two variables (one returned by the function while the other modified by the function through a pointer argument).
Here is the function:
uint16_t __SimpleReadRegister(uint8_t cRegAddress, uint16_t *pRxBuff)
{
/* Transmit the register address to read from to the IC - register address is 1 byte */
HAL_I2C_Master_Transmit(&hi2c1, SLAVEDEVICE_ADDRESS, &cRegAddress, 1, i2cTimeout);
uint8_t tempRxBuff[2];
uint8_t retval;
/* Receive 2 bytes (contents of cRegAddress register from the IC */
HAL_I2C_Master_Receive(&hi2c1, SLAVEDEVICE_ADDRESS, (uint8_t*)tempRxBuff, 2, i2cTimeout);
retval = (tempRxBuff[1] << 8) | tempRxBuff[0]; // BREAKPOINT 1 PLACED HERE
*pRxBuff = (tempRxBuff[1] << 8) | tempRxBuff[0]; // BREAKPOINT 2 PLACED HERE
return retval;
}
Here is a portion of the main function:
uint16_t status1 = 0x0000;
uint16_t status2 = 0xFFFF;
status2 = __SimpleReadRegister(0x00, &status1);
printf("0x%04X, 0x%04X\n\n", (unsigned int)(status1 & 0xFFFF), (unsigned int)(status2 & 0xFFFF));
What is printed out here is:
status1 = 0x0319, status2 = 0x0019
even though I assumed they both should be the same value. status1
is basically passed as a pointer into the function, which was assigned after status2
was assigned a value. At BREAKPOINT1: tempRxBuff[0] = 0x19
and tempRxBuff[1] = 0x03
, which means that status2 holds the wrong value.
What could be the reason why status1
is holding the wrong value here? I also tried placing a delay after HAL_I2C_Master_Receive()
but it did not change the outcome.
Thanks!
Upvotes: 0
Views: 56
Reputation: 67526
retval
is 8 bits long and it will hold only tempRxBuff[0]
value
*pRxBuff
is 16 bits long and it will hold the value of tempRxBuff[1] << 8) | tempRxBuff[0];
They can be the same if tempRxBuff[1] == tempRxBuff[0]
Upvotes: 1
Reputation: 7057
You have retval declared as a uint8_t within the function. When you make the assignment to retval, the most significant byte gets masked off leaving only the least significant byte. Then only the least significant byte is returned.
Change retval to a uint16_t.
Upvotes: 1