繁体   English   中英

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

[英]Reading String on Serial COM Port

我正在研究串行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;
}

有多个错误:使用C字符串代替std :: string,没有绑定检查,等等:

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM