HELLO WORLD的COM串口回声中的奇怪字符

时间:2015-03-31 02:53:53

标签: c++ c serial-port

我有代码将HELLO WORLD:$从我的PC发送到COM6到TIVAC板。我已通过IAR确认董事会收到了正确的信息。请注意,$是终止字符。

我在TIVAC板上设置了通过UART回显相同的消息,并通过Putty手动确认回声是正确的。但是当使用以下程序发送相同的消息并侦听回声时,我会在回声中得到奇怪的字符,如下图所示:

编码中可能出错,但我该如何解决呢?

#include <string>
#include <windows.h>
#include <conio.h>
#include <stdio.h>
#include <io.h>
#include <stdlib.h>
#include <iostream>
#include <winbase.h>
#include <tchar.h>

HANDLE GetSerialPort(char *);
void delay();
int main(void)
{
    //
    COMMTIMEOUTS timeouts;


    HANDLE h1;
    char h1_buffer[] = {"HELLO WORLD:$"};
    char h2_buffer[24];
    DWORD byteswritten, bytesread;
    char c1[] = {"COM6"};
    char c2[] = {"COM6"};
    h1 = GetSerialPort(c1);

    timeouts.ReadIntervalTimeout = 1;
    timeouts.ReadTotalTimeoutMultiplier = 1;
    timeouts.ReadTotalTimeoutConstant = 1;
    timeouts.WriteTotalTimeoutMultiplier = 1;
    timeouts.WriteTotalTimeoutConstant = 1;
    WriteFile(h1, h1_buffer, strlen(h1_buffer), &byteswritten, NULL);
    do
    {
        bool exit = FALSE;

        ReadFile(h1, h2_buffer, strlen(h2_buffer) + 1, &bytesread, NULL);

        if(bytesread)
        {
            h2_buffer[strlen(h2_buffer)] = '\0';
            std::string mystring(h2_buffer);
            std::cout << "String is  : " << mystring << "\n" ;
            printf("GOT IT %d\n", strlen(h2_buffer));
            ReadFile(h1, h2_buffer, strlen(h2_buffer) + 1, &bytesread, NULL);
            printf("%s\n", h2_buffer);
            printf("GOT IT %d\n", strlen(h2_buffer));
        }
        else
        {    
            char stop;
            printf("Nothing read\n");
            printf("Do you want to exit? ");
            scanf(" %c", stop);
            if(stop == 'N' || stop == 'n')
            {
                exit = TRUE;
            }

        }
    }while(1);
    printf("EXIT ");
    CloseHandle(h1);
}
HANDLE GetSerialPort(char *p)
{
    HANDLE hSerial;
    hSerial = CreateFile(p,GENERIC_READ | GENERIC_WRITE, 0,0,OPEN_EXISTING,0, 0);

    DCB dcbSerialParams = {0};
    dcbSerialParams.DCBlength=sizeof(dcbSerialParams);
    dcbSerialParams.BaudRate=CBR_115200;
    dcbSerialParams.StopBits=ONESTOPBIT;
    dcbSerialParams.Parity=NOPARITY;
    dcbSerialParams.fParity = 0;
    dcbSerialParams.ByteSize=DATABITS_8;
    dcbSerialParams.fDtrControl = 0;
    dcbSerialParams.fRtsControl = 0;

    return hSerial;
}
void delay ()
{
   int i = 1000000000;
   printf("In delay\n");
   while(i>0)
   {
       i--;
   }
}

1 个答案:

答案 0 :(得分:4)

此代码中存在许多问题。

  • 在未初始化的内存上调用strlen()会产生未定义的行为。
  • 您不会检查WriteFile()来电的部分写入。
  • 请勿检查ReadFile()
  • 上的返回值
  • strlen()收到的数据拨打ReadFile(),而不是使用bytesread

您不应该对从其他地方获得的数据使用strlen() - 您应该检查数据并注意I / O调用的字节数。