在小型 ARM 微控制器中实现 uart 接收缓冲区的正确方法?
我正在寻找一个小型应用程序的接收缓冲区的想法,该应用程序通过 rs485 以 921.6Kbaud 处理 15 字节数据包。我正在考虑使用循环缓冲区作为 UART ISR 和 main 之间的接口。由于它是一个微处理器,我想放入
while (uartindex!=localindex) { do stuff }
主
while (;;) {do forever}
部分,但我被告知这是不可接受的。
在类似情况下人们如何处理他们的UART?
I am looking for ideas for a receive buffer for a small application dealing with 15 byte packets at 921.6Kbaud over rs485. I am thinking of using a circular buffer as the interface between the UART ISR and main. As it is a microprocessor I was wanting to put
while (uartindex!=localindex) { do stuff }
in the
while (;;) {do forever}
part of main but I have been told this is not acceptable.
How do people deal with their uarts under similar circumstances?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ISR 应填充 FIFO。主要应该消耗它。
下面是一个非常简单的 fifo 算法:(
必须注意这个 FIFO 算法,大小必须是 2 的幂)
ISR 应该像这样运行:
而 Main:
这个算法直接从主循环读取 FIFO,你应该使用中间层检查缓冲区中是否有完整的数据包并对其进行处理,其方式主要如下所示:
ISR should fill a FIFO. Main should consume it.
Bellow a very simple fifo algorithm:
(Care must be taken with this FIFO algorithm, size MUST be power of 2)
The ISR should behave like this:
And the Main:
This algorithm reads the FIFO directly from the main loop, you should use a intermediate layer that checks if there is a full packet in the buffer, and deals with it, in such a manner that main would be like this:
如果
uartindex
从未在主循环中写入(除了在禁用中断时初始化它),并且localindex
从未被触及,那么您建议的方法可能是可行的。中断例程。我建议您将缓冲区大小设置为 2 的幂,对两个索引使用无符号整数,并允许它们在完整的 32 位大小上自由计数;在“stuff”和“fetch”例程中索引缓冲区时使用位掩码。如果这样做,那么
应该指示缓冲区中有多少个字符,即使缓冲区完全满了,也不需要在缓冲区已满的情况下采取特殊行为,并且不限制 N 字节缓冲区容纳 N-1 个项目。
请注意,虽然上述表达式中的类型转换并不是绝对必要的,但我建议将其包括在内,因为很明显,减去无符号数量时的包装行为是故意和预期 。
The approach you suggest would probably be workable if the
uartindex
is never written in the main loop (except to initialize it while interrupts are disabled), andlocalindex
is never touched by the interrupt routine.I would suggest that you make your buffer size be a power of 2, use unsigned integers for the two indices, and allow them to count freely over their full 32-bit size; use bit masking when indexing your buffer in both the "stuff" and "fetch" routines. If you do that, then
should indicate how many characters are in the buffer, even when it's completely full, without requiring special-case behavior in the buffer-full case and without limiting an N-byte buffer to holding N-1 items.
Note that while the typecast in the aforementioned expression isn't strictly necessary, I would recommend including it since it makes obvious that the wrapping behavior when subtracting unsigned quantities is deliberate and expected.