MCU串口如何接收数据包?
考虑在我的微控制器单元 (MCU) 上运行的这段代码:
while(1){
do_stuff;
if(packet_from_PC)
send_data_via_gpio(new_packet); //send via general purpose i/o pins
else
send_data_via_gpio(default_packet);
do_other_stuff;
}
MCU 还通过 UART 连接到 PC。每当 PC 向 MCU 发送数据时,都会发送 new_packet, 否则将发送 default_packet。每个数据包可以是 5 个或更多字节,具有预定义的数据包结构。
我的问题是:
1.我应该使用 UART 中断服务例程 (ISR) 从 PC 接收整个数据包吗?在这种情况下,我必须实施 ISR 内的状态机用于组装数据包(如果使用 if-else 或 switch-case 块,数据包可能会很长)。
OR
2.让PC发送某种REQUEST命令(一个字节),在我的ISR中检测它,设置一个标志,单独禁用UART中断,并通过检查标志和轮询UART在我的while(1)循环中形成数据包在这种情况下,在整个数据包形成后,UART 中断将在 while(1) 循环中重新启用。
Consider this code running on my microcontroller unit(MCU):
while(1){
do_stuff;
if(packet_from_PC)
send_data_via_gpio(new_packet); //send via general purpose i/o pins
else
send_data_via_gpio(default_packet);
do_other_stuff;
}
The MCU is also interfaced to a PC via a UART.Whenever the PC sends data to the MCU, the new_packet is sent,
otherwise the default_packet is sent.Each packet can be 5 or more bytes with a pre defined packet structure.
My question is:
1.Should i receive the entire packet from PC using inside the UART interrut service routine (ISR)? In this case, i have to implement
a state machine inside the ISR to assemble the packet (which can be lengthy with if-else or switch-case blocks).
OR
2.Have the PC send some sort of a REQUEST command (one byte),detect it in my ISR set a flag, disable UART interrupt alone and form the packet in my while(1) loop by checking for the flag and polling the UART?In this case the UART interrupt would be re-enabled in the while(1) loop after the entire packet is formed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这些并不是唯一的两个选择,第二个似乎不太理想。
我的第一种方法是使用一个简单的循环队列,从 ISR 中将字节推入其中,并从主循环中读取字节。这样你就有了一个小而简单的 ISR,并且可以在主循环中进行处理而无需禁用中断。
假设您可以明智地编写 ISR 代码,则第一个选择是可能的。您可能希望在处理构建数据包时有超时;您需要能够在 ISR 中正确处理该问题。这取决于线路速度、MCU 的速度以及您还需要做什么。
更新:
在 ISR 中这样做当然是合理的。然而,使用循环队列非常简单,在你的技巧包中有一个标准实现。这是一个循环队列的实现;读者和作者可以独立操作。
像这样使用它:
Those are not the only two choices, and the second one seems suboptimal.
My first approach would be to a simple circular queue, and push bytes into it from the ISR and read bytes from in your main loop. That way you have a small and simple ISR and you and do the processing in your main loop without disabling interrupts.
The first choice is possible assuming you can code the ISR sensibly. You probably want to have timeouts when dealing with constructing packets; you need to be able to handle that correctly in your ISR. It depends on the line speed, the speed of your MCU and what else you need to do.
Update:
Doing it in the ISR is certainly reasonable. However, using a circular queue is pretty straightforward with a standard implementation in your bag of tricks. Here is a circular queue implementation; readers and writers can operate independently.
Use it like this: