我是stackoverflow的新手。我遇到VC#Serial Communication问题。我需要从串口连续接收数据,但我的代码只能工作一次。那就是我发送“这是一个串行通信项目”。数据按预期接收,但如果我再次发送数据则无效。请提供解决方案。
private void button1_Click(object sender, EventArgs e)
{
mySerialPort.PortName = cbxCOMPort.Text;
mySerialPort.BaudRate = int.Parse(cbxBaudrate.Text);
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.RequestToSend;
mySerialPort.ReadTimeout = int.Parse(cbxTimeout.Text);
mySerialPort.WriteTimeout = 2000;
mySerialPort.DtrEnable = true;
mySerialPort.RtsEnable = true;
mySerialPort.Encoding = Encoding.ASCII;
mySerialPort.NewLine = "\r\n";
mySerialPort.ReadBufferSize = 512;
mySerialPort.DataReceived += port_DataReceived;
mySerialPort.Open();
button1.Enabled = false;
button2.Enabled = true;
gbxMsgDel.Enabled = true;
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{// Event for receiving data
// Read the buffer to text box.
this.Invoke(new EventHandler(DoUpdate));
}
private void DoUpdate(object s, EventArgs e)
{
receivedMessage += mySerialPort.ReadExisting();
}
receivedMessage是一个私有字符串类型。这是私人的。
答案 0 :(得分:1)
我之前遇到过类似的问题......
来自MSDN
“不保证每个字节都会引发DataReceived事件 接收到的“
一种选择是使用计时器来检查可用数据而不是事件,如下所示:
private void checkPortDataTimer_Tick(object sender, EventArgs e)
{
//You may want to check available bytes instead of this.
string recievedData = comPort.ReadExisting();
if (!string.IsNullOrEmpty(recievedData))
someTextBox.Text += recievedData;
}
干杯