【问题标题】:How to read data form an UART如何从 UART 读取数据
【发布时间】:2016-02-11 10:56:45
【问题描述】:

我有一个通过 uart 连接到 mcu 的传感器。传感器的输出是 ascii chapital R,后跟四个 ascii 字符数字,并以回车结束。例如R1234CR

以下是从 uart 一次读取一个字符的代码。

我正在尝试编写一个函数,当它检测到大写 R 并将接下来的四个字符放入数组中时。

我有下面写的大部分功能,但我在逻辑流程上苦苦挣扎。

还有如何返回数组?

谢谢

【问题讨论】:

  • 一些有助于逻辑的事情:有一个无限循环; ndx 是静态的,您是否缩进多次调用 getdatagetdata的返回类型是int,这是否满足你返回数组的要求,是否需要getdata返回的int
  • 不要使用魔法值。并且不存在“if”循环。
  • 而C除了枚举常量外没有符号常量。 const 没有声明一个常量! C 不是 C++!

标签: c function uart


【解决方案1】:

我想这就是你想要的..我转移了一些代码并进行了一些更改..我无法编译它,因为我当然没有真正的 UART 接口..希望它能工作..

我连续扫描 UART 接收到的数据,直到所有数据都被提取或接收到 -1。 但是我没有遇到任何回车,因为我希望您只对 5 个字节的数据感兴趣请随意更改此代码。..

#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <string.h>

int main() {
    char receivedChars[5] = {0};
    bool status = getdata(receivedChars);
}


char getchar(void) {
    int ret;    
    if ( (ret = ti_uart_read(TI_UART_0, &c)) == TI_RC_OK)
        return ((char) c);
    return -1;
}

bool getdata(char *receivedChars) {
    int count = 0;
    char retchar;
    char buffer[5] = {0};
    while(1){
        retchar = getchar(); 
        if ((retchar == 'R') && (count == 0)){
            // It means the first occurance of 'R'
            buffer[count] = 'R';
            count++;
        }else if ((count > 0) && (count < 5) &&  isdigit(retchar) != 0){
            buffer[count] = retchar;
            count++;
        }else if(retchar == -1){
            // Assumed that -1 means error in recieving the data from UART
            return false;
        }else{
            continue;
        }

        if (count == 5){
         strncpy(receivedChars, buffer, count); 
         return true;
        }
    }
}

【讨论】:

  • 在第一个if循环if (retchar != 'R') {continue;}时,除了'R'以外的所有情况都不会执行低位逻辑。它不会填充输入序列的数组,例如R1234
【解决方案2】:

您在代码中尝试做两件事

我正在尝试编写一个函数,当它检测到大写 R 并将接下来的四个字符放入数组中时

//如果字符是1-9,则将它们写入数组

两者兼而有之有时是矛盾的。所以你需要决定你需要完成什么。

第一个比较复杂,所以我会帮你解决那个。

void getdata(char *receivedChars) 
{    
    static uint8_t detected, ndx;
    int retchar;
    retchar= getchar();

    if ((retchar == 'R') && (detected == 0))
    {
        detected = 1;
        ndx = 0;
    }

    if ((detected == 1) && (ndx < 4))
    {
       receivedChars[ndx] = retchar;
       ndx++;
    }

    if (retchar == '\r'){
      receivedChars[ndx] = '\0';
      ndx = 0;
      ti_uart_writebuffer(UART_0, (uint8_t *)receivedChars, sizeof(receivedChars));
    }
}

编辑:将类型更改为 void 并在 getdata 函数中添加了 ti_uart_writebuffer 调用。现在应该从main 函数中删除此调用。

【讨论】:

  • getdata 函数返回的内容是什么?
  • 大家好,请看我上面的帖子,我不得不回复这个问题,因为我无法将它放在评论中。谢谢
  • @Rishikesh 要么将 getdata 的返回类型更改为 void 要么返回一些东西..否则您的程序将在语法上出错。
  • @MayukhSarkar 类型应该更改为 void,我只是从 OP 确认这是否是预期的行为。
  • @RishikeshRaje,我应该在do while(1) 循环中调用getdata() main()。来自传感器的数据以 9600 波特连续输入。我不需要在 main() 中连续调用 getdata() 或在 'getdata()` 中使用 do while(1) 吗?
猜你喜欢
  • 2016-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
相关资源
最近更新 更多