在串行COM端口上读取字符串

时间:2014-08-13 07:32:08

标签: c++ serial-port dev-c++

我正在进行串行COM端口ANSI Char读取项目。我可以处理发送数据,但我无法处理收到它。任何帮助都是适当的。

这是读函数:

BOOL ReadString(char *outstring)
{
    int *length;
    *length = sizeof(int);
    BYTE data;
    BYTE dataout[8192]={0};
    int index = 0;
    while(ReadByte(data)== TRUE)
    {
        dataout[index++] = data;
    }
    memcpy(outstring, dataout, index);
    *length = index;
    return TRUE;
}

Main.cpp是:

int main(void)
{
    //  Configs
    hPort = ConfigureSerialPort("COM1");
    if(hPort == NULL)
    {
        printf("Com port configuration failed\n");
        return -1;
    }


    char* cPTR;
    for(;;)
           {
                ReadString(cPTR);
                if(cPTR!=NULL) cout << "Scanned Data: " << cPTR << endl;
                else cout << "No data recieved." << endl;
    }
    ClosePort();
    return 0;
}

1 个答案:

答案 0 :(得分:1)

有多个错误:使用C-strings而不是std :: string,没有绑定检查,e.t.c。:

BOOL ReadString(char *outstring)
{
    int *length; // !!!! length is not initialized, it may point to any address
    *length = sizeof(int);

    BYTE data;
    BYTE dataout[8192]={0};
    int index = 0;

    while(ReadByte(data)== TRUE) // !!!! No bound check. What if index will become more than 8192?
    {
        dataout[index++] = data;
    }
    memcpy(outstring, dataout, index);
    *length = index; // Hmm, length is not static it is automatic variable and will not keep the index between the calls

    return TRUE;
}

主要:

int main(void)
{
    //  Configs
    hPort = ConfigureSerialPort("COM1");
    if(hPort == NULL)
    {
        printf("Com port configuration failed\n");
        return -1;
    }


    char* cPTR; // !!!! Not initialized, points to any place in memory
    for(;;)
    {
      ReadString(cPTR); // !!!! cPTR not allocated, you pass the pointer to somwhere

      if(cPTR!=NULL)
        cout << "Scanned Data: " << cPTR << endl;
      else
        cout << "No data recieved." << endl;
    }
    ClosePort();
    return 0;
}

我的读取字符串函数的建议:

void ReadString(
  std::string& result,
  std::size_t& size)
{
  result.clear(); // If you need to keep track - don't clear

  BYTE byteIn;
  while (ReadByte(byteIn))
  {
    result.append(byteIn); // Maybe static_cast<char>(byteIn) required for BYTE to char
    size++;
  }
}

现在我们可以将main重写为:

std::string buffer;
std::size_t length = 0;

while (true)
{
  ReadString(buffer, length);

  if(buffer.size())
    cout << "Scanned Data: " << buffer << endl;
  else
    cout << "No data recieved." << endl;

  // Some condition to break the cycle after 1Mb
  if (length > 1024 * 1024)
    break;
}