0

我正在尝试修改一个函数以使其更适合我的目的;

int getc0 (void)
{
    while ( (U0LSR & 0x01) == 0 ); //Wait for character
    return U0RBR;
}

上面的代码导致函数挂起,直到在串口 0 上接收到一个字符,然后返回它。我用这样的while循环来调用它;

while((str = getc0())!='\r'){
    strcat(&route_buffer,&str);
}

所以现在我让它等到通过串行端口接收到回车,并且在此之前的每个字符都被复制到缓冲区中。现在我的问题是,我目前在读取数据时遇到了一些问题,我无法确定问题出在哪里,无论它无法正确识别回车或换行符,但它正在接收一些输出!我知道这一点,因为一旦完成,我就会将所有内容保存到文件中,但要做到这一点,我必须在 while 循环中设置 ai!=5 并读取 5 个字符。如果我执行到 20,它会再次挂起并且似乎没有读取任何其他内容(即使我通过 uart 发送数据)

有没有办法可以修改它以读取 X 时间,然后继续执行其余功能?

编辑:

char route_data[512], route_buffer[200];

编辑2:

char *str;

好的,这是我编写的用于读取用户输入的函数;

char* readInput(void){

    userinput = 0;
    str = 0;

    while((str=getc0())!='\r'){
        strcat(&userinput,&str);

    }
    return &userinput;

}

它是这样称呼的;

strcat(config.nodeid,readInput());

它被称为很多,但这是我如何称呼它的一个例子。然后我将它输出到一个文件中,它可以 100% 的工作。

这可能有助于解释整个问题;我有一个带有无线模块的 ARM 板,连接到串行端口(RX 和 TX)。上面的 readInput 函数用于读取已远程登录到无线模块的用户的输入,并使 ARM 板能够读取用户的所有输入。我现在想要实现的是在对其执行命令后从无线模块读取输入。使用 printf 语句,我可以通过将命令放入语句来执行命令。我需要完成的是读取无线模块的输出,这是我遇到困难的地方。我得到了一些输出,但它非常有限,不是预期的,但它显然来自模块。

4

1 回答 1

3

str is not a nul terminated string passing its address to strcat() will concatenate an indeterminate amount of data to route_buffer.

Using strcat() is a bad idea in any case for a number of reasons, and your usage is especially ill-advised. You have no protection against buffer overrun, and strcat() must needlessly redetermine the length of the string in route_buffer every time it is called.

A marginally better solution would be:

int index = strlen(route_buffer) ;
int ch ;
while( index < sizeof(route_buffer) - 1 && (ch = getc0()) != '\r')
{
    route_buffer[index] = ch ;
    index++ ;
}
route_buffer[index] = 0 ;

I have made a number of assumptions from your original code here, such as route_buffer is in fact a nul terminated string. Those are your design decisions; they may or may not be correct or good ones.

解决问题的更好方法是将接收到的字符放入 UART Rx 中断处理程序的环形缓冲区中,然后让读取函数从缓冲区异步获取数据。然后,您可以在必要时轻松实现阻塞、阻止和超时访问。您甚至可以让 ISR 计算缓冲的换行数,这样您就可以提前知道缓冲区中有多少行可用。缓冲还可以让您的代码不必担心及时为 UART 提供服务,以防止字符溢出和数据丢失。

如果您想要超时行为,getc0() 中的 while 循环和行输入循环都必须另外测试一些计时器源。

于 2011-03-10T21:14:27.917 回答