连接串口
- 界面设计
- 打开串口
- 发送数据
- 通过文件发送
- 发送数据
- 接收数据
首先可以在 工具箱中搜索serialport,将控件拖到你的Winfrom窗口。
界面设计
打开串口
private void Connect_Click(object sender, EventArgs e){serialPort1.PortName = comboBox2.Text;//端口名serialPort1.BaudRate = int.Parse(comboBox3.Text);//比特率serialPort1.StopBits = StopBits.One;//停止位switch (comboBox4.Text)//校验位{case "None":serialPort1.Parity = Parity.None;break;case "Odd":serialPort1.Parity = Parity.Odd;break;case "Even":serialPort1.Parity = Parity.Even;break;case "Mark":serialPort1.Parity = Parity.Mark;break;}serialPort1.DataBits = int.Parse(comboBox5.Text);//数据位try{serialPort1.Open();//打开串口bool b = serialPort1.CtsHolding;//CTS状态label8.Text = b ? "1" : "0";if (checkBox2.CheckState == CheckState.Checked)//判断是否勾选RTS{serialPort1.RtsEnable = true;}}catch (Exception ex){MessageBox.Show(ex.Message);}button3.Text=serialPort1.IsOpen ? "关闭串口" : "打开串口";}
发送数据
liens为全局变量,可以直接在richTextBox里输入,然后再点发送。
通过文件发送
private void OpenFile_Click(object sender, EventArgs e){OpenFileDialog openFileDialog = new OpenFileDialog();openFileDialog.InitialDirectory = "d:\\";//设置默认打开路径// 设置文件过滤选项openFileDialog.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*";// 设置标题openFileDialog.Title = "选择文件";// 显示对话框DialogResult result = openFileDialog.ShowDialog();// 确认用户没有取消操作if (result == DialogResult.OK){// 获取选中的文件路径string filePath = openFileDialog.FileName;comboBox1.Items.Add(filePath);liens = File.ReadAllText(filePath);//读取文件comboBox1.Text = filePath;richTextBox1.Text=liens;}}
发送数据
private void Send_Click(object sender, EventArgs e)
{serialPort1.WriteLine(liens);
}
接收数据
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{int len = serialPort1.BytesToRead;//获取可以读取的字节数byte[] buff = new byte[len];//创建缓存数据数组serialPort1.Read(buff, 0, len);//把数据读取到buff数组if (checkBox1.Checked)//是否勾选十六进制显示{richTextBox1.AppendText(BitConverter.ToString(buff).Replace('-', ' ') + '\n');//转成十六进制显示}else{richTextBox1.AppendText(Encoding.ASCII.GetString(data));//转成ASCII码显示richTextBox1.AppendText("\n");}
}