0

我需要向串行端口发送命令以与 Enfora 调制解调器通信。对于每个命令,我都会收到回复,但回复字符串的长度可能会有所不同。我需要知道如何写,然后等待回复,直到它完成......

所以我想制作一个从串口读取的线程,而程序只写......

线程函数

private void thread_Handler()
{
    while(true)
        this.read();
}
private void read()
{
    if (this.rtbMessages.InvokeRequired)
    {
        try
        {
            SetTextCallback d = new SetTextCallback(read);
            this.Invoke(d);
        }
        catch{}
    }
    else
    {
        readBuffer = serialPort.ReadExisting();
        rtbMessages.AppendText(readBuffer);
    }
}

所以这个线程总是试图从 com 端口读取,我以这种方式发送消息

writeBuffer = "COMMAND 1";
serialPort.Write(writeBuffer);
writeBuffer = "COMMAND 2";
serialPort.Write(writeBuffer);

但是,我没有从使用 Write() 发送的第二个命令中得到答复...我尝试在每次 Write() 之后删除线程并使用 ReadExisting() 但这也不起作用。

我可以让它工作的唯一方法是添加一个

System.Threading.Thread.Sleep(1000);

每次调用 Write 后,我都会从每个 Write() 命令中获得所有回复...但我不想使用它,我想知道另一种有效写入并从我发送的每个命令中获得每个回复的方法无论回复字符串的长度以及我收到回复消息需要多长时间。

有时我会一直收到消息,直到我发送另一个命令来停止生成消息。

谢谢!

4

2 回答 2

1

.Net 将为您做这一切。

只需创建一个 SerialPort 并订阅其DataReceived事件。(请注意,在某些情况下,您可能需要将以这种方式接收的几块数据拼接在一起,以组装一个完整的数据包,但如果它是来自调制解调器命令的简短回复,您可能总是/通常会找到您每次引发事件时获取完整的数据包。

于 2012-09-06T21:31:55.223 回答
0

Use an Event to receive the data.

Here is an example from DreamInCode (you will have to customize it to your particular needs):

/// <summary>
/// This method will be called when there's data waiting in the comport buffer
/// </summary>
void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    //determine the mode the user selected (binary/string)
    switch (CurrentTransmissionType)
    {
        //user chose string
        case TransmissionType.Text:
            //read data waiting in the buffer
            string msg = comPort.ReadExisting();
            //display the data to the user
            DisplayData(MessageType.Incoming, msg + "\n");
            break;
        //user chose binary
        case TransmissionType.Hex:
            //retrieve number of bytes in the buffer
            int bytes = comPort.BytesToRead;
            //create a byte array to hold the awaiting data
            byte[] comBuffer = new byte[bytes];
            //read the data and store it
            comPort.Read(comBuffer, 0, bytes);
            //display the data to the user
            DisplayData(MessageType.Incoming, ByteToHex(comBuffer) + "\n");
            break;
        default:
            //read data waiting in the buffer
            string str = comPort.ReadExisting();
            //display the data to the user
            DisplayData(MessageType.Incoming, str + "\n");
            break;
    }
}

http://www.dreamincode.net/forums/topic/35775-serial-port-communication-in-c%23/

于 2012-09-06T21:29:38.983 回答