我正在STM32F处理器上为UART使用双缓冲区。每次UART ISR运行时,以下示例将数据添加到缓冲区。然后,当主进程要从中提取数据时,将交换此缓冲区。
我担心可能出现的转弯情况。在交换缓冲区之后但在重置接收缓冲区计数之前,ISR可能会触发。这意味着我的缓冲区大小和计数将不同步。
处理这种极端情况的最佳方法是什么?
uint8_t rxBufferA[MAX_RX_BUFFER_SIZE];
uint8_t rxBufferB[MAX_RX_BUFFER_SIZE];
uint8_t *receivingBuffer;
uint8_t *processingBuffer;
volatile uint32_t rxBufferSize;
uart_isr() {
receivingBuffer[rxBufferSize++] = RECEIVE_DATA_REGISTER
}
main() {
receivingBuffer = &rxBufferA;
processingBuffer = &rxBufferB;
while(1) {
if (rxBufferSize > 0) {
uint32_t i = 0;
uint8_t *ptemp = receivingBuffer;
uint8_t bufferSize = 0;
/* zero out processing buffer */
memset(processingBuffer, 0, MAX_RX_BUFFER_SIZE);
/* swap receiving and processing buffers */
receivingBuffer = processingBuffer
processingBuffer = ptemp;
/* WHAT IF THE ISR FIRES HERE??? */
/* save off buffer size and reset count */
bufferSize = rxBufferSize;
rxBufferSize = 0;
/* process rx data */
}
}
}
答案 0 :(得分:4)
您需要关键部分。交换缓冲区时禁用用户中断。
不需要BTW调零