简体   繁体   English

在C#中从串行端口接收数据有问题吗?

[英]Problem with receiving data form serial port in c#?

hello i have problem with receiving data from serial port in c# in am inserting a new line operator at the end of data buffer. 您好,我在从C#的串行端口接收数据时遇到了问题,正在在数据缓冲区的末尾插入新的行运算符。 then i send this data buffer on serial port, after this my c# GUI receiver will take this data via Readline() function but it always give me raw data not the actual one how to resolve this problem. 然后我在串行端口上发送此数据缓冲区,此后我的c#GUI接收器将通过Readline()函数获取此数据,但它始终为我提供原始数据,而不是实际的如何解决此问题的数据。

//configuring the serial port this code in c# with problem
                serialPort.PortName = "COM1";
                serialPort.BaudRate = 9600;
                serialPort.DataBits = 8;
                serialPort.Parity = Parity.None;
                serialPort.StopBits = StopBits.One;

                //opening the serial port
                if(!serialPort.IsOpen)
                    serialPort.Open();

                //read 2byte data for msG code from serial port


                string strReadData=serialPort.ReadLine();
                char[] temp=new char[350];
                //strReadData.CopyTo(1, temp, 0, strReadData.Length - 2);

                //strReadData = temp.ToString();

                //string strReadData = serialPort.ReadExisting();

                //strReadData.Replace(' ', '\0');

                //strReadData.Replace(' ', '');

                byte[] RecievedData = Encoding.ASCII.GetBytes(strReadData);

                RecievedDataDecoder(RecievedData);


 //close the port
                if(serialPort.IsOpen)
                    serialPort.Close();

but my c++ receiver is working perfectly i dont know what is the problem here is working c++ code 但是我的C ++接收器工作正常,我不知道这里的问题是在工作C ++代码

// variables used with the com port
BOOL     m_bPortReady;
HANDLE   m_hCom;
DCB      m_dcb;
COMMTIMEOUTS m_CommTimeouts;
BOOL     bWriteRC;
BOOL     bReadRC;
DWORD iBytesWritten;
DWORD iBytesRead;
DWORD dwCommEvent;
DWORD dwRead;

char       sBuffer[128];

m_hCom = CreateFile("Com1", 
        GENERIC_READ | GENERIC_WRITE,
        0, // exclusive access
        NULL, // no security
        OPEN_EXISTING,
        0, // no overlapped I/O
        NULL); // null template 

m_bPortReady = SetupComm(m_hCom, 128, 128); // set buffer sizes

m_bPortReady = GetCommState(m_hCom, &m_dcb);
m_dcb.BaudRate = 9600;
m_dcb.ByteSize = 8;
m_dcb.Parity = NOPARITY;
m_dcb.StopBits = ONESTOPBIT;
m_dcb.fAbortOnError = TRUE;

m_bPortReady = SetCommState(m_hCom, &m_dcb);

m_bPortReady = GetCommTimeouts (m_hCom, &m_CommTimeouts);

m_CommTimeouts.ReadIntervalTimeout = 50;
m_CommTimeouts.ReadTotalTimeoutConstant = 50;
m_CommTimeouts.ReadTotalTimeoutMultiplier = 10;
m_CommTimeouts.WriteTotalTimeoutConstant = 50;
m_CommTimeouts.WriteTotalTimeoutMultiplier = 10;

m_bPortReady = SetCommTimeouts (m_hCom, &m_CommTimeouts);


    if (!SetCommMask(m_hCom, EV_RXCHAR))
    {
        printf("Error in set comm mask");
    }

while(1)
{

   if (WaitCommEvent(m_hCom, &dwCommEvent, NULL)) 
   {
      if (ReadFile(m_hCom, &sBuffer, 128, &iBytesRead, NULL))
            printf("");

      else
      {
         printf("Error in reading");
         break;
      }
   }
   else
   {
    printf("Error in Waiting");
       break;
   }


    printf("%s",sBuffer);   
    strcpy(sBuffer,"");

}


CloseHandle(m_hCom);
getch();
exit(0);

Your question is a bit vague, but the ReadLine() method will return when the port receives a carriage return and line feed byte combination by default on Windows. 您的问题有点含糊,但是默认情况下,在Windows上,当端口接收到回车和换行字节组合时,ReadLine()方法将返回。 Or \\r\\n, or 0x0d 0x0a if you prefer. 或\\ r \\ n,或根据需要选择0x0d 0x0a。

If the 'buffer' you are sending in the fist place contains several messages delimited by \\r\\n, then ReadLine() will only return the first one, then the port will close in the C# code you have posted. 如果要在第一个位置发送的“缓冲区”包含由\\ r \\ n分隔的几条消息,则ReadLine()将仅返回第一个消息,然后该端口将在您发布的C#代码中关闭。

Maybe your code is in a loop, but it is not shown. 也许您的代码处于循环中,但未显示。

Beyond that, after any data that you have received, your are converting it back to an array of bytes, determined by ASCII encoding. 除此之外,在收到任何数据之后,您会将其转换回由ASCII编码确定的字节数组。 Are you sending ASCII in the first place? 首先要发送ASCII吗? If not, it is likely that you could be missing information. 如果不是,很可能您会丢失信息。

Also, if all you do is convert the received string into bytes, you could just receive the data as bytes in the first place. 另外,如果您要做的只是将接收到的字符串转换为字节,那么您可以首先将数据作为字节接收。

I think you need to explain in a bit more detail exactly what is in the buffer you are sending, and what exactly do you receive. 我认为您需要更详细地说明发送缓冲区中到底包含什么,以及收到什么。

Most of my serial port errors are caused by bad baude rate settings. 我的大多数串行端口错误是由错误的波特率设置引起的。 This might be your problem too. 这也可能是您的问题。 (You can set the baude rate in some constructors of the SerialPort class, or with the BaudRate property ) (您可以在SerialPort类的某些构造函数中或使用BaudRate属性来设置波特率

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

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