C编程如何将串口取出的数据时、分、秒相加并显示

How to add and display hours, minutes, seconds of data taken from the serial port with C programming

我从Arduino串口获取了温度数据。来自 Arduino 串行监视器的温度数据是:

21.48
21.97
21.48
21.00
21.97
21.97

使用C程序读取串口如下 代码:

char TempChar;
DWORD NoBytesRead;
do{
    ReadFile(hComm,&TempChar,sizeof(TempChar),&NoBytesRead,NULL);
    printf("%c",TempChar);                            }
while(!kbhit());

然后就会出现这个样子

21.48
21.97
21.48
21.00
21.97
21.97

现在我想使用 c 程序添加和显示小时、分钟和秒,如下面的代码:

char TempChar;
DWORD NoBytesRead;

SYSTEMTIME str_t;
GetSystemTime(&str_t);

do{
   ReadFile(hComm,&TempChar,sizeof(TempChar),&NoBytesRead,NULL);
    printf("%c, %d:%d:%d ",TempChar,str_t.wHour+7,str_t.wMinute,str_t.wSecond);
 }while(!kbhit());

但结果是这样的:

, 18:9:38  1, 18:9:38 ., 18:9:38 ., 18:9:38 0, 18:9:38 0, 18:9:38
, 18:9:38 2, 18:9:38 1, 18:9:38 ., 18:9:38 0, 18:9:38 0, 18:9:38
, 18:9:38 2, 18:9:38 1, 18:9:38 ., 18:9:38 0, 18:9:38 0, 18:9:38

我其实想要的结果是

21.48,18:9:38
21.97,18:9:38
21.48,18:9:38
21.00,18:9:38
21.97,18:9:38
21.97,18:9:38

C语言程序代码应该修正什么?

所以 Arduino 发送换行符?然后把你读到的字符收集成一个字符串,当你读到换行时显示(带时间)。

您正在逐字符读取温度数据。因此,您需要在此字符流中检测每个数据包的边界在哪里。很明显,里面有换行符,需要检测一下:

if(tempChar == '\n')
{
    // print separator and date/time
}
printf("%c", TempChar)

现在取决于使用哪个行分隔符,上面与 \n 一起使用,如果您有 \r\n 或只有 \r,您需要调整...

您的数据中似乎有一个前导换行符,因此您可能需要对第一个换行符进行特殊处理。

出现这个错误是因为你写打印语句的方式。

printf("%c, %d:%d:%d ",TempChar,str_t.wHour+7,str_t.wMinute,str_t.wSecond);

因此,这里的 TempChar 存储当前字符值,它在临时数据的每个字符处打印。因此,首先打印所有临时数据,然后打印日期。

do{
   ReadFile(hComm,&TempChar,sizeof(TempChar),&NoBytesRead,NULL);
   if(TempChar!='\n'){printf("%c",TempChar);}
   else{
        printf(", %d:%d:%d \n",str_t.wHour+7,str_t.wMinute,str_t.wSecond);}
}while(!kbhit());