C#中使用SerialPort类实现简单串口编程

本文介绍如何使用C#实现串口通信,包括创建SerialPort对象、设置串口参数及读写操作。同时探讨了串口通信的基本原理,并提供了一个实际的应用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于项目需要通过串口通信,所以学习一下在此做一下笔记。

.NET 2.0提供了串口通信的功能,其命名空间是System.IO.Ports。这个新的框架不但可以访问计算机上的串口,还可以和串口设备进行通信。

创建C#串口通信程序之创建SerialPort 对象

通过创建SerialPort 对象,我们可以在程序中控制串口通信的全过程。

我们将要用到的SerialPort 类的方法:

ReadLine():从输入缓冲区读一新行的值,如果没有,会返回NULL

WriteLine(string):写入输出缓冲

Open():打开一个新的串口连接

Close():关闭

//create a serialport object,with COM1,baudrate 57600,parity bit:none,data bit:8 //stopbits:one SerialPort sport = new SerialPort("COM1",57600,Parity.None,8,StopBits.One); private void seriallistenfun() { try { if (sport.IsOpen) { sport.Close(); sport.Open(); //open com } else { sport.Open();//open com } String data; string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); //得到当前路径 path = path+@"/newfile.txt"; FileStream TextFile = File.Open(path, FileMode.Create, FileAccess.Write,FileShare.Read);//创建文件   byte [] Info ;   while (true) { if (sport.BytesToRead != 0) { data = sport.ReadExisting().ToString();//读取串口数据 this.BeginInvoke(dfun, new object[] { data }); data += "/r/n"; Info = new UTF8Encoding(true).GetBytes(data);//转换成字节流 TextFile.Write(Info,0,Info.Length);//写入文件 Thread.Sleep(10); } else { //this.BeginInvoke(dfun, new object[] { "Serialrev:NULL" }); Thread.Sleep(50); } } } catch(SystemException e) { this.BeginInvoke(dfun, new object[] { e.ToString() }); }

建C#串口通信程序之串口的硬件知识

在数据传输的时候,每个字节的数据通过单个的电缆线传输。包包括开始位,数据,结束为。一旦

开始位传出,后面就会传数据,可能是5,6,7或8位,就看你的设定了。发送和接收必须设定同样

的波特率和数据位数。

创建C#串口通信程序之无猫模式

没有Modem模式的电缆只是简单地交叉传送和接收线。同样DTR & DSR, 和 RTS & CTS也需要交叉。

这里,我们三条线。互连2和3(一段的2pin连接3pin),连接两端的5pin。

这里需要注意:在wince上获取当前路径方法较为独特,跟winxp win7上不同,PC上的方法不能用到这上面来,另外注意读取串口数据时不能使用readline,可以使用readexisting目前还不知为什么.

public partial class Form1 : Form { public Form1() { InitializeComponent(); } SerialPort port1 = new SerialPort(); string InputData = String.Empty; delegate void SetTextCallback(string text); private void Port_Select() {//获取机器中的串口地址 string[] ports = SerialPort.GetPortNames(); foreach (string port in ports) { comboBox1.Items.Add(port); } } private void Form1_Load_1(object sender, EventArgs e) { Port_Select(); this.comboBox1.SelectedIndex = 0; this.comboBox2.SelectedIndex = 0; } private void button1_Click(object sender, EventArgs e) { if (button1.Text == "关闭串口") //当要关闭串口的时候 { port1.DiscardOutBuffer(); port1.DiscardInBuffer(); port1.Close(); button1.Text = "打开串口"; label3.Text = "串口当前状况:未打开"; comboBox1.Enabled = true; comboBox2.Enabled = true; } else if (button1.Text == "打开串口") //当要打开串口的时候 { try { port1.PortName = comboBox1.SelectedItem.ToString(); port1.BaudRate = Convert.ToInt32(comboBox2.SelectedItem); port1.DataBits = 8; port1.RtsEnable = true; port1.Open(); port1.DiscardOutBuffer(); port1.DiscardInBuffer(); button1.Text = "关闭串口"; comboBox1.Enabled = false; comboBox2.Enabled = false; label3.Text = "串口:" + comboBox1.SelectedItem.ToString() + " 波特率:" + comboBox2.SelectedItem.ToString() + " 数据位:8 "; } catch { button1.Text = "打开串口"; label3.Text = "串口:" + comboBox1.SelectedItem.ToString() + "打开失败"; MessageBox.Show("该串口无法打开"); } } } 资源中部分代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值