串口的定义,请自行了解.
C#操作串口通讯在.Net强大类库的支持下,只需要三个步骤:
1 创建
2 打开
3 发送/接受
1 创建:
1 串口通讯需用用到的命名空间如下:
- using System.IO.Ports;
- using System.IO;
复制代码
2 因为全局使用,所以声明为全局变量
- private SerialPort spSend = new SerialPort();
复制代码
3 指定串口名称
- spSend.PortName = "COM1";
- //继续根据需要指定端口的波特率,校验位等信息
- //在例子中我们只指定名称,其他的一概不管.
复制代码
2 打开:
3 发送/接收
- //发送
- byte[] data = Encoding.ASCII.GetBytes("要发送的信息");
- spSend.Write(data, 0, data.Length);
复制代码
- //接收
- byte[] data = new byte[spSend.BytesToRead];
- spSend.Read(data, 0, data.Length);
- String str = new ASCIIEncoding().GetString(data);//收取到的信息
复制代码
好了,核心代码就是这么简单,下面看完整实例,
界面:

控件名称:
下拉框ComList 打开按钮btnOpen 发送框 txtSend 发送按钮btnSend 接收框txtInfo 另外还有一个定时器Timer1
完整源码:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.IO.Ports;//需要的命名空间
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
-
- namespace ChengChenXu.com.COMDemo
- {
- public partial class Form1 : Form
- {
- private SerialPort spSend = new SerialPort(); //全局变量
- public Form1()
- {
- InitializeComponent();
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
- //获取本机串口列表
- string[] comList = SerialPort.GetPortNames();
- if (comList.Length == 0) MessageBox.Show("本机没有任何串口");
- //绑定串口列表到下拉列表,设置第一项为默认值
- foreach (var com in comList)
- {
- ComList.Items.Add(com);
- }
- ComList.SelectedIndex = 0;
-
- //启动定时器,用来接受信息,没有使用多线程,更易于理解
- timer1.Start();
- }
- private void btnOpen_Click(object sender, EventArgs e)
- {
- if (ComList.Items.Count == 0)
- {
- MessageBox.Show("没有发现串口");
- return;
- }
-
- //判断是打开操作还是关闭操作
- if (btnOpen.Text == "打开串口")
- {
- if (!spSend.IsOpen)
- {
- //设置端口名称
- //这里我们仅仅设置端口的名称,其他的全部用默认.
- spSend.PortName = ComList.SelectedItem.ToString();
-
- try
- {
- //打开串口
- spSend.Open();
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- //更新控件状态
- this.btnOpen.Text = "关闭串口";
- this.ComList.Enabled = false;
- }
- }
- else if(btnOpen.Text=="关闭串口")
- {
- //关闭串口
- spSend.Close();
-
- btnOpen.Text = "打开串口";
- ComList.Enabled = true;
- }
- }
-
- private void btnSend_Click(object sender, EventArgs e)
- {
- //发送数据
- //准备数据 这里我们只实现发送ASCII码 其他的可以先转化为byte[]再发送
- byte[] data = Encoding.ASCII.GetBytes(txtSend.Text);
-
- if (spSend.IsOpen)
- {
- try
- {
- //发送动作 参数三个分别为数据 起始偏移位置 长度
- spSend.Write(data, 0, data.Length);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- }
- else
- {
- MessageBox.Show("端口还未打开");
- }
-
- }
-
- private void Receive()
- {
- //接收信息 先判断是否为打开状态
- if (spSend.IsOpen)
- {
- //准备接收
- byte[] data = new byte[spSend.BytesToRead];
- //接受动作
- spSend.Read(data, 0, data.Length);
- //把接收到的信息转成字符串显示到控件里
- this.txtInfo.Text += new ASCIIEncoding().GetString(data);
- }
- }
- private void timer1_Tick(object sender, EventArgs e)
- {
- //用定时器来定期执行接收动作 间隔100毫秒
- Receive();
- }
- }
- }
复制代码
如何测试
串口通讯既然是通讯那么肯定是需要两方参与的,如何在单机进行测试呢?下面给出几个方法:
1 方法一 把电脑串口的2 3针链接起来,那么接收方和发送方可以为同一个端口.因为2针负责发送,3针负责接收,连接起来即可形成回路
2 使用两台电脑,用串口线相连
3 使用虚拟串口软件,最简单易用,这里我们采用这个方法进行测试.
首先软件下载:VirtualSerialPortDriver 下载地址: VirtualSerialPortDriver.rar
这个是一个收费软件,半个月的试用期,需要的话可以搜索下是否有破解版
安装好之后打开软件,右侧选择好两个准备互联的串口然后点击Add pair即可. 我选择的是COM9和COM10 可以看到左边Virtual ports下面已经有了COM9和COM10了 他们已经可以实现通讯了

把DEMO编译好之后,直接运行两个实例: 一个选择COM9 一个选择COM10 然后都打开串口

现在已经可以互相发送信息了
由COM9发出的Send for COM9已经发送到COM10
COM9也已经接收到了COM10发出的信息Send for COM10

本例只用了最简单的例子来演示串口通讯过程,简化一切功能,只为更好理解.
源码以及DEMO: ChengChenXu.com.COMDemo.rar
本文为博主原创,转载请保留出处: http://www.chengchenxu.com/Article/27/netchuankou |