miss掉数据,大概就3种原因吧
1 比特率不对
2 干扰
3 单片机太忙
1 比特率不对
2 干扰
3 单片机太忙
<code class="lang-c">using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO.Ports; namespace SerialPortTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); //display(); } private void Form1_Load(object sender, EventArgs e) { try { foreach (string com in System.IO.Ports.SerialPort.GetPortNames()) comboBox1.Items.Add(com); } catch (Exception er) { MessageBox.Show("端口加载失败!" + er.Message, "提示"); } comboBox2.SelectedIndex = 4; comboBox3.SelectedIndex = 2; comboBox4.SelectedIndex = 0; comboBox5.SelectedIndex = 1; // comboBox1.SelectedIndex = 0; } //打开串口 private void btnOpen_Click(object sender, EventArgs e) { try { if (serialPort1.IsOpen) { serialPort1.Close(); } else { serialPort1.BaudRate = int.Parse(comboBox2.Text.Trim()); serialPort1.DataBits = int.Parse(comboBox3.Text.Trim()); serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox4.Text.Trim()); serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox5.Text.Trim()); serialPort1.PortName = comboBox1.Text; serialPort1.Open(); } groupBox1.Enabled = !serialPort1.IsOpen; if (btnOpen.Text == "打开串口") { btnOpen.Text = "关闭串口"; pictureBox1.Visible = true; pictureBox2.Visible = false; } else if (btnOpen.Text == "关闭串口") { btnOpen.Text = "打开串口"; pictureBox1.Visible = false; pictureBox2.Visible = true; } } catch (Exception er) { MessageBox.Show("串口打开失败!" + er.Message, "提示"); } } private void btnSend_Click(object sender, EventArgs e) { if (serialPort1.IsOpen == false) { MessageBox.Show("请先打开串口!"); return; } SendData();//发送数据传递textBox1.text中数据 //display(); } //接收数据 string Recive; private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) { Invoke (new EventHandler (delegate { // textBox2.Text += serialPort1.ReadExisting(); //这里注释掉,经试验,textBox和Repeat同时接受会互相干扰,出现收到奇怪的数据 Recive = serialPort1.ReadExisting(); if (Recive.Trim() == "1E") { pictureBox3.Visible = true; pictureBox4.Visible = false; } MessageBox.Show(Repeat); //查看当前收到了什么,排查故障用 if (Recive.Trim() == "1D") { pictureBox3.Visible = false; pictureBox4.Visible = true; } MessageBox.Show(Repeat); //查看当前收到了什么,排查故障用 } ) ); } //向串口发送数据 public void SendData() { for (int i = 0; i < textBox1.Lines.Count(); i++) { serialPort1.WriteLine(textBox1.Lines<i>); } }</i></code>
[修改于 8年8个月前 - 2016/04/29 22:46:15]
时段 | 个数 |
---|---|
{{f.startingTime}}点 - {{f.endTime}}点 | {{f.fileCount}} |
200字以内,仅用于支线交流,主线讨论请采用回复功能。