C#程序读取传感器的数据,传感器由串口连接。现在问题是,我如果在运行程序前就连接好了传感器,然后打开串口就报出“COM3拒绝访问”,然后我只要把传感器拔了重插一下,再打开就可以了。或者在程序运行前不要连接传感器,等程序打开后再连接传感器,然后打开串口也没问题。 private void com_data_receive(object sender, SerialDataReceivedEventArgs e) { if (Closing) return; try { Listening = true; byte[] buf = new byte[24]; receive_count += 1; COM.Read(buf, 0, 24); COM.DiscardInBuffer(); string receive_data = ""; for (int i = 0; i < buf.Length; i++) { receive_data += buf[i].ToString("X2"); } string temperature = get_temperature(receive_data.Substring(36, 4)).ToString("0.00"); string humility = get_humility(receive_data.Substring(40, 4)).ToString("0.00"); string illumination = get_illumination(receive_data.Substring(44, 4)).ToString("0.00"); this.Invoke((EventHandler)(delegate { ListViewItem lvi = new ListViewItem(receive_count.ToString()); lvi.SubItems.Add(temperature); lvi.SubItems.Add(humility); lvi.SubItems.Add(illumination); listView1.Items.Add(lvi); })); } private void button4_Click(object sender, EventArgs e) { if (comboBox1.SelectedItem != null && comboBox2.SelectedItem != null && comboBox3.SelectedItem != null && comboBox4.SelectedItem != null && comboBox5.SelectedItem != null) { if (COM.IsOpen) { Closing = true; while (Listening) Application.DoEvents(); COM.Close(); COM.Dispose(); Closing = false; } else { com_setting(); try { COM.Open(); COM.DataReceived += new SerialDataReceivedEventHandler(com_data_receive); } catch (Exception ex) { COM.Close(); COM.Dispose(); COM = new SerialPort(); MessageBox.Show(ex.Message); } } button4.Text = COM.IsOpen ? "关闭" : "开始"; } else { MessageBox.Show("请设置参数"); } } private void com_setting() { COM.PortName = comboBox1.Text; COM.NewLine = "\r\n"; COM.RtsEnable = true; COM.BaudRate = int.Parse(comboBox2.Text); COM.DataBits = int.Parse(comboBox3.Text); switch (comboBox4.SelectedIndex) { case 0: COM.Parity = Parity.None; break; case 1: COM.Parity = Parity.Odd; break; case 2: COM.Parity = Parity.Even; break; case 3: COM.Parity = Parity.Mark; break; case 4: COM.Parity = Parity.Space; break; default: COM.Parity = Parity.None; break; } switch (comboBox5.SelectedIndex) { case 0: COM.StopBits = StopBits.One; break; case 1: COM.StopBits = StopBits.OnePointFive; break; case 2: COM.StopBits = StopBits.Two; break; default: COM.StopBits = StopBits.One; break; } } |
|
5分
#1 |
在程序打开串口的时候,先看串口状态,如果打开的可以先关闭一下在打开
|
#2 |
http://download.csdn.net/detail/wc_ling/8812747
我写的,你看看吧 |
10分
#3 |
while (Listening) Application.DoEvents();
这是要闹哪样? |
5分
#4 |
|
#5 |
回复4楼: 抢生意是吧 |
#6 |
回复1楼: 我打开前判断了一下啊,我先看看你的,谢谢 |
#7 |
回复4楼: 我先看看,谢谢 |
#8 |
回复4楼: 文件损坏。 |
#9 |
回复8楼: 已测试,可以正常打开 |
#10 |
另,我用VS2005编写的
用更高的版本应该都能正常打开 但是不要试图用低于2005的版本打开 |