C# VS2010 SerialPort串口通信简单代码 大家帮忙看看什么问题吧。。
只是实现简单的打开串口,接收数据 现在是串口打开了 但接收不到数据啊。。想实现接收到数据Label3变色。。。private void button3_Click(object sender, EventArgs e)
{
try
{
if (comboBox1.Items.Count > 0)
{
this.serialPort1.PortName = comboBox1.SelectedItem.ToString();
}
this.serialPort1.Open();
}
catch (System.IO.IOException ee)
{
MessageBox.Show("没发现次串口", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
button3.Text = "连接报警";
}
catch (UnauthorizedAccessException ee)
{
MessageBox.Show("串口被占用!", "信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
button3.Text = "连接报警";
}
// this.serialPort1.Close();
}
bool SerialPortIsReceiving = false;
public void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
SerialPortIsReceiving = true;
byteread = new byte[serialPort1.BytesToRead];//接收到的参考节点(x,y)
serialPort1.Read(byteread, 0, 8);//new
serialPort1.DiscardInBuffer();
if (byteread[3] != 0)
{
button3.Text = "断开连接";
Light.ForeColor = Color.Lime;
MessageBox.Show("与Location Dongle连接成功!", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
try
{
if ((byteread[3] == 0x03))
{
label3.ForeColor = Color.Green;
}
}
catch
{
return;
}
}
SerialPortIsReceiving = false;
Application.DoEvents();
} --------------------编程问答-------------------- 线程不同呢,在VS中,serialPort1_DataReceived与窗体界面线程是不同嘀,请使用invoke方法
补充:.NET技术 , 其他语言