C# 简单串口通信示例
- 串口通信
- 示例代码
串口通信
C# 串口通信主要操作:
- 命名空间:using System.IO.Ports;
- 获取端口:string[] ports = System.IO.Ports.SerialPort.GetPortNames();
- 设置端口名:serialPort1.PortName = “COM1”; // 字符串
- 设置波特率:serialPort1.BaudRate = 115200;// int.Parse(“115200”);
- 设置数据位:serialPort1.DataBits = 1; // int.Parse(“1”);
- 设置停止位:serialPort1.StopBits = StopBits.One;
- StopBits.One:停止位1
- StopBits.OnePointFive:停止位1.5
- StopBits.Two:停止位2
- 设置校验位:serialPort1.Parity = Parity.None;
- Parity.None:无
- Parity.Even:奇校验
- Parity.Odd:偶校验
- 打开串口:serialPort1.Open();
- 关闭串口:serialPort1.Close();
- 可读字节:serialPort1.BytesToRead;
- 读取数据:serialPort1.Read(buffer, 0, len);
- 写入数据:serialPort1.Write(buffer);
- 接收事件: XXX_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e);
示例代码
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;
using System.IO.Ports;
namespace serial_tools
{
public partial class Form1 : Form
{
String serialPortName;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] ports = System.IO.Ports.SerialPort.GetPortNames(); // 获取本机可用串口端口
comboBoxPort.Items.AddRange(ports);
comboBoxPort.SelectedIndex = comboBoxPort.Items.Count > 0 ? 0 : -1; // 有可用端口显示第一个
comboBoxBaudrate.Text = "115200"; // 默认波特率
comboBoxDataBits.Text = "8"; // 默认数据位:8
comboBoxStopbit.Text = "1"; // 默认停止位:1
comboBoxCheck.Text = "无"; // 默认无校验
}
/// <summary>
/// 重写 系统消息函数
/// </summary>
/// <param name="m"></param>
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
}
/// <summary>
/// 串口数据接收
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
int len = serialPort1.BytesToRead; // 获取可读字节数
byte[] buff = new byte[len]; // 创建缓存数据数组
serialPort1.Read(buff, 0, len); // 把数据读取到buff数组
string str = Encoding.Default.GetString(buff); // Byte值转ASCII字符串
Invoke((new Action(() => {
if (checkBoxHexShow.Checked)
{
textBoxRecv.AppendText(byteToHexStr(buff));
}
else
{
textBoxRecv.AppendText(str);
}
}))); // 对话框追加显示数据
}
public static string byteToHexStr(byte[] bytes)
{
string hexStr = "";
try
{
if (bytes != null) {
for (int i = 0; i < bytes.Length; i++)
{
hexStr += bytes[i].ToString("X2");
hexStr += " "; // 两个Hex数值以空格隔开
}
}
return hexStr;
}
catch (Exception)
{
return hexStr;
}
}
/// <summary>
/// 打开关闭串口
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonPortOnOff_Click(object sender, EventArgs e)
{
if (buttonPortOnOff.Text == "打开串口") {
try
{
serialPort1.PortName = comboBoxPort.Text; // 获取选择的串口端口
serialPortName = comboBoxPort.Text;
serialPort1.BaudRate = int.Parse(comboBoxBaudrate.Text); // 获取选择的波特率
serialPort1.DataBits = int.Parse(comboBoxDataBits.Text); // 获取选择的数据位
// 设置停止位
if (comboBoxStopbit.Text == "1") { serialPort1.StopBits = StopBits.One; }
else if (comboBoxStopbit.Text == "1.5") { serialPort1.StopBits = StopBits.OnePointFive; }
else if (comboBoxStopbit.Text == "2") { serialPort1.StopBits = StopBits.Two; }
// 设置奇偶校验
if (comboBoxCheck.Text == "无") { serialPort1.Parity = Parity.None; }
else if (comboBoxCheck.Text == "奇校验") { serialPort1.Parity = Parity.Even; }
else if (comboBoxCheck.Text == "偶校验") { serialPort1.Parity = Parity.Odd; }
// 打开串口
serialPort1.Open();
buttonPortOnOff.Text = "关闭串口";
}
catch (Exception ex)
{
MessageBox.Show("串口打开失败"+ ex.ToString(), "警告",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
try
{
serialPort1.Close();
}
catch (Exception ex)
{
}
buttonPortOnOff.Text = "打开串口";
}
}
/// <summary>
/// 清空接收数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonClearRecv_Click(object sender, EventArgs e)
{
textBoxRecv.Clear();
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSendData_Click(object sender, EventArgs e)
{
String Str = textBoxSend.Text.ToString(); // 获取发送文本框里的数据
try
{
if (Str.Length > 0) {
serialPort1.Write(Str); // 串口发送数据
}
}
catch (Exception)
{
}
}
/// <summary>
/// 清除发送数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonClearSend_Click(object sender, EventArgs e)
{
textBoxSend.Clear();
}
private void comboBoxPort_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void comboBoxPort_MouseClick(object sender, MouseEventArgs e)
{
}
}
}
窗体界面设计
运行效果