我有以下情况。我有一个微控制器,它通过一个SPI外设与两个外部I/O扩展器芯片通信。每个芯片都有8个数字输入,并配备有锁存输入,这确保了数字输入的两个字节可以在同一时刻被采样。为了将这两个字节的状态传送到我的微控制器中,我需要执行两个SPI事务。同时,我需要确保我的微控制器中的软件将在两个字节的一致状态下工作。
我解决这个问题的第一个想法是使用某种双缓冲。下面是描述我的想法的伪代码。
uint8_t di_array_01[2] = {0};
uint8_t di_array_02[2] = {0};
uint8_t *ready_data = di_array_01;
uint8_t *shadow_data = di_array_02;
uint8_t *temp;
if(chip_0_data_received) {
*shadow_data = di_state_chip_0;
chip_0_data_received = false;
} else if(chip_1_data_received) {
*(shadow_data + 1) = di_state_chip_1;
temp = ready_data;
ready_data = shadow_data;
shadow_data = temp;
chip_1_data_received = false;
}更高的软件层将始终使用ready_data指针所指向的数组内容。我的意图是,布尔标志chip_0_data_received (chip_1_data_received)的设置将在“事务结束”中断中完成,并且将从后台循环中调用以下代码以及用于启动SPI事务的代码。
有没有人看到我遗漏的任何潜在问题?
发布于 2021-02-19 15:13:36
如果你的数据总共只有16位,你可以原子地读写它。
uint16_t combined_data;
// in reading function
if (chip_0_data_received && chip_1_data_received)
{
combined_data = (((uint16_t)di_state_chip_1 << 8) | di_state_chip_0);
}
// in using function
uint16_t get_combined_data = combined_data;
uint8_t data_chip_1 = ((get_combined_data >> 8) & 0xFF);
uint8_t data_chip_0 = ((get_combined_data >> 0) & 0xFF);https://stackoverflow.com/questions/66265587
复制相似问题