C#串口通信
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace 串口收发
{
public partial class 串口收发 : Form
{
public 串口收发()
{
InitializeComponent();
}
//以上为系统自动生成的代码,以下为自己写入的代码
private void Form1_Load(object sender, EventArgs e)
{
//serialPort1.PortName = "COM5"; //端口号为COM1
//serialPort1.BaudRate = 9600; //波特率
//serialPort1.DataBits = 8; //数据位数
//serialPort1.Parity = Parity.Even; //偶校验
//serialPort1.StopBits = StopBits.One; //停止位为1
//string[] names = SerialPort.GetPortNames(); //获取当前计算机的串行端口的名称数组
//SN_comboBox.DataSource = names; //把获取的串行端口名称作为 SN_comboBox 控件的数据源
BindPort();
Rate_comboBox.SelectedIndex = 2; //默认为 9600
DataBits_comboBox.SelectedIndex = 3; //默认数据位为8位
Parity_comboBox.SelectedIndex = 0; //默认为无校验
StopBits_comboBox.SelectedIndex = 1; //默认停止位为1位
combo_click();
}
private void open_button_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen == false)
{
combo_click();
combo_Enable_false();
serialPort1.Open(); //如果串口没有打开,则打开串口
MessageBox.Show("串口打开成功");
}
else
{
serialPort1.Close();
combo_Enable_true();
// MessageBox.Show("串口已经关闭");
}
}
private void send_button_Click(object sender, EventArgs e)
{
//要发送的通信命令
serialPort1.Write(Send_textBox.Text + "\r");
}
private void receive_button_Click(object sender, EventArgs e)
{
// 要接收的通信命令
Receive_textBox.Text = serialPort1.ReadTo("\r"); //接收数据,直到遇到回车符
}
private void combo_click()
{
//端口栏中不管哪个combobox控件被单击后,都会调用这个事件
//意思为:如当前为9600,要再选择为115200时,要重新加载下面的函数
serialPort1.PortName = SN_comboBox.Text;
serialPort1.BaudRate = int.Parse(Rate_comboBox.Text); //波特率
serialPort1.DataBits = int.Parse(DataBits_comboBox.Text); //数据位数
serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), Parity_comboBox.Text);
serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), StopBits_comboBox.Text);
}
private void combo_Enable_false()
{ //端口中的COMBOBOX控件,设置成不可选择
SN_comboBox.Enabled = false;
Rate_comboBox.Enabled = false;
DataBits_comboBox.Enabled = false;
Parity_comboBox.Enabled = false;
StopBits_comboBox.Enabled = false;
open_button.Text = "关闭串口";
}
private void combo_Enable_true()
{ //端口中的COMBOBOX控件,设置成可选择
SN_comboBox.Enabled = true;
Rate_comboBox.Enabled = true;
DataBits_comboBox.Enabled = true;
Parity_comboBox.Enabled = true;
StopBits_comboBox.Enabled = true;
open_button.Text = "打开串口";
}
private void BindPort()
{
try
{
//自动获取串行口名称
foreach (string port in SerialPort.GetPortNames())
{
this.SN_comboBox.Items.Add(port);
}
SN_comboBox.SelectedIndex = 0;
}
catch
{
MessageBox.Show("找不到通讯串口!", "串口调试助手");
}
}
}
}