我正在为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 */
}
}
}
您需要关键部分。交换缓冲区时禁用用户中断。
不需要btw零