第一步:使用System.IO.Ports命名空间
using System.IO.Ports
第二步:实例化串口
SerialPort comm = new SerialPort();初始化SerialPort对象
StringBuilder builder = new StringBuilder();
第三步:初始化串口参数
comm 是实例化的串口,comboPortName是串口下拉框的Name,comboBaudrate是波特率下拉框的Name。其它像停止位、奇偶校验位等的参数默认就好。comm_DataReceived是数据接收函数名
string[] ports = SerialPort.GetPortNames();//获取串口号
Array.Sort(ports);//对串口号排序
comboPortName.Items.AddRange(ports);//将串口号添加到comboPortName下拉框的列表
comboPortName.SelectedIndex = comboPortName.Items.Count > 0 ? 0 : -1;//将串口号最小的设置为默认选择值
comboBaudrate.SelectedIndex = comboBaudrate.Items.IndexOf("9600");//将9600设置为默认选择值
comm.NewLine = "\r\n";
comm.RtsEnable = true;//根据实际情况吧。
//添加事件注册
comm.DataReceived += comm_DataReceived;//添加串口数据接收事件
第四步:开启或关闭串口
if (comm.IsOpen)
{
//打开时点击,则关闭串口
comm.Close();
}
else
{
//关闭时点击,则设置好端口,波特率后打开
comm.PortName = comboPortName.Text;
comm.BaudRate = int.Parse(comboBaudrate.Text);
try
{
comm.Open();
}
catch (Exception ex)
{
//捕获到异常信息,创建一个新的comm对象,之前的不能用了。
comm = new SerialPort();
//现实异常信息给客户。
MessageBox.Show(ex.Message);
}
}
第五步:接收数据处理
checkBoxHexView是窗体工具checkbox的Name,Lift_txGet是窗体工具textbox的Name,labelGetCount是窗体工具lable的Name。
的名字
void comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int n = comm.BytesToRead;//获取接收缓冲区中数据的字节数
byte[] buf = new byte[n];//初始化接收数组
received_count += n;//接收字节数计数
comm.Read(buf, 0, n);//将读取的字节写入buf中,0表示从接收数据的第一位数据开始,n表示写入的字节数。
builder.Clear();
//因为要访问ui资源,所以需要使用invoke方式同步ui。
this.Invoke((EventHandler)(delegate
{
if (checkBoxHexView.Checked) //hex
{
foreach (byte b in buf)
{
builder.Append(b.ToString("X2") + " ");//十六进制
}
}
else//ASCII
{
builder.Append(Encoding.ASCII.GetString(buf));//字符
}
this.Lift_txGet.AppendText(builder.ToString());//
labelGetCount.Text = "接收:" + received_count.ToString();//
}));
}
第六步:发送数据
三个重载函数皆可实现串口数据发送,可根据通讯协议选择其中一个使用
// 参数:
// buffer:
// 包含要写入端口的数据的字节数组。
//
// offset:
// buffer 参数中从零开始的字节偏移量,从此处开始将字节复制到端口。
//
// count:
// 要写入的字节数。
//
public void Write(byte[] buffer, int offset, int count);
// 参数:
// text:
// 输出字符串。
//
public void Write(string text);
// 参数:
// buffer:
// 包含要写入端口的数据的字符数组。
//
// offset:
// buffer 参数中从零开始的字节偏移量,从此处开始将字节复制到端口。
//
// count:
// 要写入的字符数。
//
public void Write(char[] buffer, int offset, int count);