两个假定相同的变量以某种方式持有不同的值
Two supposedly same variables somehow hold different values
我正在使用 STM32 微控制器测试 I2C 协议。我创建了一个函数,该函数应该读取微控制器将与之通信的从属设备中寄存器的 16 位内容。我的问题并不真正围绕硬件,而是两个变量(一个由函数返回,另一个由函数通过指针参数修改)。
函数如下:
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;
}
这是主要功能的一部分:
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));
这里打印出来的是:
状态 1 = 0x0319,状态 2 = 0x0019
即使我认为它们应该是相同的值。 status1
基本上作为指针传递到函数中,它是在 status2
赋值之后赋值的。在 BREAKPOINT1:tempRxBuff[0] = 0x19
和 tempRxBuff[1] = 0x03
,这意味着 status2 持有错误的值。
status1
在这里持有错误值的原因可能是什么?我也尝试在 HAL_I2C_Master_Receive()
之后延迟,但它并没有改变结果。
谢谢!
您在函数中将 retval 声明为 uint8_t。当您对 retval 进行赋值时,最重要的字节被屏蔽掉,只留下最不重要的字节。然后只返回最低有效字节。
将 retval 更改为 uint16_t。
retval
是 8 位长,它将只包含 tempRxBuff[0]
值
*pRxBuff
是 16 位长,它将保存 tempRxBuff[1] << 8) | tempRxBuff[0];
的值
它们可以相同,如果 tempRxBuff[1] == tempRxBuff[0]
我正在使用 STM32 微控制器测试 I2C 协议。我创建了一个函数,该函数应该读取微控制器将与之通信的从属设备中寄存器的 16 位内容。我的问题并不真正围绕硬件,而是两个变量(一个由函数返回,另一个由函数通过指针参数修改)。
函数如下:
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;
}
这是主要功能的一部分:
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));
这里打印出来的是:
状态 1 = 0x0319,状态 2 = 0x0019
即使我认为它们应该是相同的值。 status1
基本上作为指针传递到函数中,它是在 status2
赋值之后赋值的。在 BREAKPOINT1:tempRxBuff[0] = 0x19
和 tempRxBuff[1] = 0x03
,这意味着 status2 持有错误的值。
status1
在这里持有错误值的原因可能是什么?我也尝试在 HAL_I2C_Master_Receive()
之后延迟,但它并没有改变结果。
谢谢!
您在函数中将 retval 声明为 uint8_t。当您对 retval 进行赋值时,最重要的字节被屏蔽掉,只留下最不重要的字节。然后只返回最低有效字节。
将 retval 更改为 uint16_t。
retval
是 8 位长,它将只包含 tempRxBuff[0]
值
*pRxBuff
是 16 位长,它将保存 tempRxBuff[1] << 8) | tempRxBuff[0];
它们可以相同,如果 tempRxBuff[1] == tempRxBuff[0]