串口通信
在.net平台下创建c#串口通信程序,.net 2.0提供了串口通信的功能,其命名空间是system.io.ports。这个新的框架不但可以访问计算机上的串口,还可以和串口设备进行通信。
创建c#串口通信程序之命名空间 system.io.ports命名空间中最重用的是serialport 类。 创建c#串口通信程序之创建serialport 对象 通过创建serialport 对象,我们可以在程序中控制串口通信的全过程。
正文
属性
| basestream | 获取 stream 对象的基础 serialport 对象。 |
| baudrate | 获取或设置串行波特率。 |
| breakstate | 获取或设置中断信号状态。 |
| bytestoread | 获取接收缓冲区中数据的字节数。 |
| bytestowrite | 获取发送缓冲区中数据的字节数。 |
| cdholding | 获取端口的载波检测行的状态。 |
| ctsholding | 获取“可以发送”行的状态。 |
| databits | 获取或设置每个字节的标准数据位长度。 |
| discardnull | 获取或设置一个值,该值指示 null 字节在端口和接收缓冲区之间传输时是否被忽略。 |
| dsrholding | 获取数据设置就绪 (dsr) 信号的状态。 |
| dtrenable | 获取或设置一个值,该值在串行通信过程中启用数据终端就绪 (dtr) 信号。 |
| encoding | 获取或设置传输前后文本转换的字节编码。 |
| handshake | 使用 handshake 中的值获取或设置串行端口数据传输的握手协议。 |
| isopen | 获取一个值,该值指示 serialport 对象的打开或关闭状态。 |
| newline | 获取或设置用于解释 readline() 和 writeline(string) 方法调用结束的值。 |
| parity | 获取或设置奇偶校验检查协议。 |
| parityreplace | 获取或设置一个字节,该字节在发生奇偶校验错误时替换数据流中的无效字节。 |
| portname | 获取或设置通信端口,包括但不限于所有可用的 com 端口。 |
| readbuffersize | 获取或设置 serialport 输入缓冲区的大小。 |
| readtimeout | 获取或设置读取操作未完成时发生超时之前的毫秒数。 |
| receivedbytesthreshold | 获取或设置 datareceived 事件发生前内部输入缓冲区中的字节数。 |
| rtsenable | 获取或设置一个值,该值指示在串行通信中是否启用请求发送 (rts) 信号。 |
| stopbits | 获取或设置每个字节的标准停止位数。 |
| writebuffersize | 获取或设置串行端口输出缓冲区的大小。 |
| writetimeout | 获取或设置写入操作未完成时发生超时之前的毫秒数。 |
方法
| close() | 关闭端口连接,将 isopen 属性设置为 false,并释放内部 stream 对象。 |
| discardinbuffer() | 丢弃来自串行驱动程序的接收缓冲区的数据。 |
| discardoutbuffer() | 丢弃来自串行驱动程序的传输缓冲区的数据。 |
| getportnames() | 获取当前计算机的串行端口名的数组。 |
| open() | 打开一个新的串行端口连接。 |
| read(byte[], int32, int32) | 从 serialport 输入缓冲区读取一些字节并将那些字节写入字节数组中指定的偏移量处。 |
| read(char[], int32, int32) | 从 serialport 输入缓冲区中读取一些字符,然后将这些字符写入字符数组中指定的偏移量处。 |
| readbyte() | 从 serialport 输入缓冲区中同步读取一个字节。 |
| readchar() | 从 serialport 输入缓冲区中同步读取一个字符。 |
| readexisting() | 在编码的基础上,读取 serialport 对象的流和输入缓冲区中所有立即可用的字节。 |
| readline() | 一直读取到输入缓冲区中的 newline 值。 |
| readto(string) | 一直读取到输入缓冲区中的指定 value 的字符串。 |
| write(byte[], int32, int32) | 使用缓冲区中的数据将指定数量的字节写入串行端口。 |
| write(char[], int32, int32) | 使用缓冲区中的数据将指定数量的字符写入串行端口。 |
| write(string) | 将指定的字符串写入串行端口。 |
| writeline(string) | 将指定的字符串和 newline 值写入输出缓冲区。 |
nuget 安装system.io.ports

串口写
private void btnwrite_click(object sender, eventargs e)
{
serialport serialport = new serialport();
serialport.portname = "com1";//串口名称
serialport.baudrate = 9600; //获取或设置波特率
serialport.parity = parity.even;//获取或设置校验位
serialport.databits = 8;//获取或设置数据位默认值8
serialport.stopbits = stopbits.one;// 停止位
serialport.open();
serialport.write("a");
serialport.close();
}
串口读
serialport serialport = new serialport();
private void btnread_click(object sender, eventargs e)
{
byte[] a = system.text.encoding.ascii.getbytes(" ");
serialport.portname = "com1";//串口名称
serialport.baudrate = 9600; //获取或设置波特率
serialport.parity = parity.none;//获取或设置校验位
serialport.databits = 8;//获取或设置数据位默认值8
serialport.stopbits = stopbits.one;// 停止位
serialport.datareceived += serialport_datareceived;
serialport.open();
}
private void serialport_datareceived(object sender, serialdatareceivedeventargs e)
{
byte[] b = new byte[8];
int a = serialport.read(b, 0, 8);
this.invoke(() =>
{
string s = bytetohex(b);
txtvalue.text += s+system.environment.newline;
});
}
public string bytetohex(byte[] bytes)
{
string str = string.empty;
foreach (byte byte in bytes)
{
str += string.format("{0:x2}", byte) + " ";
}
return str.trim();
}

一个完整例子

using system.io.ports;
namespace scom
{
public partial class frmmain : form
{
serialport serialport;
public frmmain()
{
initializecomponent();
init();
}
private void loadports()
{
cboport.items.clear();
string[] port = system.io.ports.serialport.getportnames();
foreach (var item in port)
{
cboport.items.add(item);
}
cboport.selectedindex = 0;
}
private void init()
{
loadports();
object[] baudrate = { 4800, 9600, 19200, 38400, 57600, 115200, 230400 };
cbobaudrate.items.addrange(baudrate);
cbobaudrate.selectedindex = 1;
cbodatabits.items.add(7);
cbodatabits.items.add(8);
cbodatabits.selectedindex = 1;
cbostopbits.items.add("one");
cbostopbits.items.add("onepointfive");
cbostopbits.items.add("two");
cbostopbits.selectedindex = 0;
//parity
cboparity.items.add("none");
cboparity.items.add("even");
cboparity.items.add("mark");
cboparity.items.add("odd");
cboparity.items.add("space");
cboparity.selectedindex = 0;
cbohandshaking.items.add("none");
cbohandshaking.items.add("xonxoff");
cbohandshaking.items.add("requesttosend");
cbohandshaking.items.add("requesttosendxonxoff");
cbohandshaking.selectedindex = 0;
btncloseport.enabled = false;
}
private void btnrefresh_click(object sender, eventargs e)
{
loadports();
}
private void btnopenport_click(object sender, eventargs e)
{
if (serialport == null)
{
serialport = new serialport();
}
serialport.portname = cboport.text;//串口名称
serialport.baudrate = int.parse(cbobaudrate.text); //获取或设置波特率
serialport.parity = (parity)enum.parse(typeof(parity), cboparity.text);//获取或设置校验位
serialport.databits = int.parse(cbodatabits.text);//获取或设置数据位默认值8
serialport.stopbits = (stopbits)enum.parse(typeof(stopbits), cbostopbits.text);// 停止位
serialport.handshake = (handshake)enum.parse(typeof(handshake), cbohandshaking.text);// 握手协议
serialport.datareceived += serialport_datareceived;
serialport.open();
stsmain_lblstatus.text = "端口已打开";
btnopenport.enabled = false;
btncloseport.enabled = true;
}
private void serialport_datareceived(object sender, serialdatareceivedeventargs e)
{
this.invoke(new action(() =>
{
byte[] b = new byte[8];
int a = serialport.read(b, 0, 8);
string s = "";
if (rdohex.checked)
{
s = bytetohex(b);
}
else
{
s = system.text.encoding.default.getstring(b);
}
txtreceive.appendtext(system.environment.newline+ s);
}));
}
private void btncloseport_click(object sender, eventargs e)
{
if (serialport != null && serialport.isopen)
{
serialport.datareceived -= serialport_datareceived;
serialport.close();
stsmain_lblstatus.text = "端口已关闭";
btnopenport.enabled = true;
btncloseport.enabled = false;
}
}
private void btnsend_click(object sender, eventargs e)
{
if (serialport == null || !serialport.isopen)
{
return;
}
serialport.write(txtsend.text);
}
private string bytetohex(byte[] bytes)
{
string str = string.empty;
foreach (byte byte in bytes)
{
str += string.format("{0:x2}", byte) + " ";
}
return str.trim();
}
}
}
以上就是c# serialport实现串口通讯的代码详解的详细内容,更多关于c# serialport串口通讯的资料请关注代码网其它相关文章!
发表评论