【问题标题】:c programing logic for reading sensor over UART用于通过 UART 读取传感器的 c 编程逻辑
【发布时间】:2016-08-01 14:50:24
【问题描述】:

我正在尝试从通过 UART 连接到单片机的传感器读取数据。通电时,传感器连续输出一个 ASCII 大写“R”,后跟四个代表距离的 ASCII 字符数字(以毫米为单位),然后是回车符(ASCII 13)。

我想知道是否有人可以帮助我找出一个逻辑来阅读,例如9999 作为一个变量称为读数。

我应该使用阻塞功能还是非阻塞功能,如果数据流入,我将如何隔离字符?

【问题讨论】:

  • 你认为你应该使用什么?
  • 阻塞意味​​着函数在字符到达之前不会返回。非阻塞意味着它会返回一个字符是否可用(如果有它会通知你)。你想要阻塞还是非阻塞取决于你的其他逻辑,所以你必须自己回答。

标签: c logic uart


【解决方案1】:

首先我会选择阻塞版本。我想您可能会在一开始就期望缺少字符,因为传感器可能会在您实际读取数据之前开始流式传输字符。因此,如果 UART 已满,那么您可能需要它。所以示例代码是:

#define CR (13)
uart_t my_uart; // You need to setup this
uart_status_t status;
uint8_t c;
int status;
char distance[255] = { 0 }; // Whatever, large enough
int seen_r = 0; // You have not yet seen 'R' 
int offset = 0;

while ((status = uart_read(my_uart, &c, &status)) == 0)
{
   if (seen_r) 
   {
      if (c == CR)
      {
          printf("Distance: %s\n", distance);
          seen_r = 0;
          memset(distance, 0, sizeof(distance));
      }
      if (offset < sizeof(distance)-1)
      {
          distance[offset++] = (char)c;
      }
      else
      {
          printf("Unexpected size, reset!\n"); 
          seen_r = 0;
          memset(distance, 0, sizeof(distance));
      }
   }
   else
   {
      if (c != 'R') continue;
      seen_r = 1;
   }
}

当然,这是未经测试的代码,但它可能会给您一些提示。 基本上,您有一个以'R' 开头并以CR 结尾的状态机。

【讨论】:

  • 建议if (offset &lt; sizeof(distance) - 1) 避免打印非空字符终止的数组。
  • @Aif 感谢您的帮助 - 快速提问 - seen_r 在哪里设置为 1 - 进入第一个 if 循环? 'next' 也是 c 中的关键字吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-17
  • 1970-01-01
  • 1970-01-01
  • 2011-02-15
  • 2020-09-13
  • 2016-11-04
  • 1970-01-01
相关资源
最近更新 更多