标签:style class blog code http color
虚拟串口驱动工具,创建俩个虚拟串口,如图:
创建两个Console模拟串口的发送接收数据
C#串口数据接收发送,类空间:
using System.IO.Ports;
C# 串行端口 接收数据,代码如下:
//遍历串行端口名称数组 foreach (string port in System.IO.Ports.SerialPort.GetPortNames()) { Console.WriteLine(port); } byte[] b = new byte[32]; SerialPort sp = new SerialPort("COM4"); while (true) { //打开新的串行端口连接 sp.Open(); //丢弃来自串行驱动程序的接受缓冲区的数据 sp.DiscardInBuffer(); //丢弃来自串行驱动程序的传输缓冲区的数据 sp.DiscardOutBuffer(); //从串口输入缓冲区读取一些字节并将那些字节写入字节数组中指定的偏移量处 sp.Read(b, 0, b.Length); StringBuilder sb = new StringBuilder(); for (int i = 0; i < b.Length;i++ ) { sb.Append(Convert.ToString(b[i]) + " "); } Console.WriteLine(sb.ToString()); Console.WriteLine(b.Length.ToString()); //关闭端口连接 sp.Close(); //当前线程挂起500毫秒 System.Threading.Thread.Sleep(500); }
C# 串行端口 发送数据,代码如下:
SerialPort sp = new SerialPort("COM2"); byte[] m = new byte[5]; int i = 0; while (true) { //打开新的串行端口连接 sp.Open(); //丢弃来自串行驱动程序的接受缓冲区的数据 sp.DiscardInBuffer(); //丢弃来自串行驱动程序的传输缓冲区的数据 sp.DiscardOutBuffer(); m[0] = Convert.ToByte("1"); m[1] = Convert.ToByte("2"); m[2] = Convert.ToByte("3"); m[3] = Convert.ToByte("4"); m[4] = Convert.ToByte("5"); //使用缓冲区的数据将指定数量的字节写入串行端口 sp.Write(m, 0, m.Length); //关闭端口连接 sp.Close(); Console.WriteLine(i.ToString()); i = i + 1; //当前线程挂起500毫秒 System.Threading.Thread.Sleep(500); }
标签:style class blog code http color
原文地址:http://www.cnblogs.com/bmbh/p/3795774.html