试图从串行端口检索数据,但是程序卡在getchar上

问题描述 投票:1回答:1

我正在使用嵌入式系统将数据从25个传感器发送到计算机上的腻子终端。效果很好。

我想向嵌入式系统添加终端读取功能(以便我可以发送命令)。因此,我尝试使用getchar()读取要在腻子终端上写入的内容。首先,我只是想获取字符并将字符打印回腻子上。可以,但是我的传感器数据应该每500毫秒打印一次,直到我在腻子中键入一个字符后才打印。就像我的代码被卡在getchar()上并卡在while循环中,直到getchar()读取某些内容。

这是我的int main()中的永久循环。我没有分享其余部分,因为它并不是真正需要的并且太庞大了(它只是初始化模块)。在此循环中,我正在读取传感器,尝试从腻子中读取,写入腻子并开始下一次扫描:

for(;;)
{

    CapSense_ProcessAllWidgets(); // Process all widgets 
    CapSense_RunTuner();    // To sync with Tuner application           

    read_sensor(curr_elem);  //read curr_elem

    (curr_elem < RX4_TX4)?(curr_elem++):(curr_elem = 0, touchpad_readings_flag++);

// Here is the part to read I added which blocks until I type in something.
// If I remove this if and all of what's in it, I print to putty every 500ms
    if(touchpad_readings_flag) 
        {
                    char received_char = getchar();
                if (received_char) //if something was returned, received_char != 0
                    {
                        printf("%c", received_char);
                    }
        }

//Here I write to putty. works fine when I remove getchar()    
    if (print_counter_flag && touchpad_readings_flag) 
    {
        print_counter_flag = 0;
        touchpad_readings_flag = 0;
        for (int i = 0; i < 25; i++)
        {
            printf("\n");
            printf("%c", 97 + i);
            printf("%c", val[i] >> 8);
            printf("%c", val[i] & 0x00ff);  // For raw counts
            printf("\r");
        }  
    }       


    /* Start next scan */
    CapSense_UpdateAllBaselines();
    CapSense_ScanAllWidgets();
}
serial-port printf putty getchar psoc
1个回答
1
投票

显然,除非有要检索的输入数据,否则您的getchar()呼叫处于阻塞状态。another article on different SE board提供了一种更改此行为的解决方案。

[还请注意,getchar()getc()的包装,如stdin 1所述,该包装正在作用于this site。对于getc(),您可以找到进一步的讨论。在one of those中指出,一些重要的实现甚至会等待换行符,直到将输入传递给函数为止。我认为这取决于您实际使用的标准库/嵌入式系统的种类-请检查工具链供应商的文档。2


1我没有查找规范性资源,这只是我的第一个Google热门。

2该问题未指定嵌入式系统的类型,因此需要一个通用答案,而不是讨论特定目标/工具链组合IMO。

© www.soinside.com 2019 - 2024. All rights reserved.