上位机如何实现串口通信 - (第二讲)
开发环境为 Visual Studio 2019
视频讲解如下:
CSDN源码下载
源码下载,提取码:jwo1
https://pan.baidu.com/s/1EY3xI7cQo5Ea3iQDeYEWfQ
这里给大家讲解一下在winform环境下如何实现串口通信的。
界面设计效果如下:

Form1.cs 代码如下
using System;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace usb
{
public partial class Form1 : Form
{
private MyCom mCom = new MyCom();
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 查找串口
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button_SearchCom_Click(object sender, EventArgs e)
{
string[] names = SerialPort.GetPortNames();
comboBox_com.Items.Clear();
if (names.Length >= 1)
{
for (int i = 0; i < names.Length; i++)
{
comboBox_com.Items.Add(names[i]);
}
comboBox_com.Text = names[0];
}
else
{
comboBox_com.Items.Add("COM0");
comboBox_com.Text = "COM0";
}
}
/// <summary>
/// 打开串口
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button_open_Click(object sender, EventArgs e)
{
Res.com_name = comboBox_com.Text; // 串口号
Res.Box_Bound = int.Parse(comboBox1.Text); // 波特率
Res.Box_DataBit = int.Parse(comboBox2.Text); // 数据位
Res.Box_StopBit = comboBox3.Text;// 停止位
Res.Box_Verify = comboBox4.Text;// 校验位
mCom.ComOpen();
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button_send_Click(object sender, EventArgs e)
{
mCom.ComWrite(Encoding.UTF8.GetBytes(textBox2.Text));
}
private void Form1_Load(object sender, EventArgs e)
{
string[] names = SerialPort.GetPortNames();
if (names.Length >= 1)
{
for (int i = 0; i < names.Length; i++)
{
comboBox_com.Items.Add(names[i]);
}
comboBox_com.Text = names[0];
}
else
{
comboBox_com.Items.Add("COM0");
comboBox_com.Text = "COM0";
}
comboBox1.SelectedIndex = 13;
comboBox2.SelectedIndex = 2;
comboBox3.SelectedIndex = 0;
comboBox4.SelectedIndex = 0;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (Res.logs.Count > 0)
{
textBox1.Text += Res.logs[0] + "\r\n";
Res.logs.RemoveAt(0);
}
}
}
/// <summary>
/// 在这里实现串口的数据接收和发送
/// </summary>
public class MyCom
{
/// <summary>
/// 打开串口
/// </summary>
public void ComOpen()
{
if (Res.comm.IsOpen == false)
{
// 打开串口
Res.comm.PortName = Res.com_name; // 串口
Res.comm.BaudRate = Res.Box_Bound; // 波特率
Res.comm.DataBits = Res.Box_DataBit; // 数据位
// 停止位
if (Res.Box_StopBit == "1") Res.comm.StopBits = System.IO.Ports.StopBits.One;
if (Res.Box_StopBit == "1.5") Res.comm.StopBits = System.IO.Ports.StopBits.OnePointFive;
if (Res.Box_StopBit == "2") Res.comm.StopBits = System.IO.Ports.StopBits.Two;
// 校验位
if (Res.Box_Verify == "None") Res.comm.Parity = System.IO.Ports.Parity.None;
if (Res.Box_Verify == "Odd") Res.comm.Parity = System.IO.Ports.Parity.Odd;
if (Res.Box_Verify == "Even") Res.comm.Parity = System.IO.Ports.Parity.Even;
if (Res.Box_Verify == "Mark") Res.comm.Parity = System.IO.Ports.Parity.Mark;
if (Res.Box_Verify == "Space") Res.comm.Parity = System.IO.Ports.Parity.Space;
Res.comm.NewLine = "\r\n";
Res.comm.RtsEnable = true;
Res.comm.Handshake = System.IO.Ports.Handshake.None;
linkCom();
}
else
{
// 关闭串口
Res.logs.Add("关闭串口.");
if (Res.comm.IsOpen)
Res.comm.Close();
}
}
/// <summary>
/// 开线程
/// </summary>
private void linkCom()
{
Res.comm.Open();
Res.comm.Encoding = Encoding.GetEncoding("GB2312");
new Thread(ComReadData) { IsBackground = true }.Start();
}
/// <summary>
/// 数据接收
/// </summary>
private void ComReadData()
{
Res.logs.Add("打开串口完成.");
while (Res.comm.IsOpen)
{
Thread.Sleep(50); // 以50ms一个周期,进行串口数据接收,不能太快,不然会出现拆包的现象
try
{
// 查询串口中目前保存了多少数据
int n = Res.comm.BytesToRead;
// 读取数据
byte[] buf = new byte[n];
Res.comm.Read(buf, 0, n);
// 打印数据
if (buf.Length > 0)
{
string str = Encoding.Default.GetString(buf).Replace("-", " ");
Res.logs.Add(str);
}
}
catch
{
if (Res.comm.IsOpen)
Res.comm.Close();
}
}
}
/// <summary>
/// 发送数据
/// </summary>
public void ComWrite(byte[] bytes)
{
try
{
if (Res.comm.IsOpen && bytes != null)
{
Res.comm.Write(bytes, 0, bytes.Length);
}
}
catch { }
}
}
}
Res.cs 代码如下
using System.Collections.Generic;
using System.IO.Ports;
namespace usb
{
public static class Res
{
/// <summary>
/// 这里保存串口的接收数据
/// </summary>
public static List<string> logs = new List<string>();
/// <summary>
/// 串口接口
/// </summary>
public static SerialPort comm { get; set; } = new SerialPort();
/// <summary>
/// 串口名字
/// </summary>
public static string com_name { get; set; }
/// <summary>
/// 波特率
/// </summary>
public static int Box_Bound { get; set; }
/// <summary>
/// 数据位
/// </summary>
public static int Box_DataBit { get; set; }
/// <summary>
/// 校验位
/// </summary>
public static string Box_Verify { get; set; }
/// <summary>
/// 停止位
/// </summary>
public static string Box_StopBit { get; set; }
}
}