c#如何实现串口通信读取数据

作者&投稿:慎秋 (若有异议请与网页底部的电邮联系)
C#用serialPort实现串口通信读取byte数据菜鸟求助。~

class Program
{
struct BinData
{
public byte Length; //长度 8bit
public byte[] Header; // 1,2 字节没用
public byte[] Flag;// 3,4 字节截出来
public byte Padding; // 5没用
public byte[] Data; // 7~17 有用
}

static void Main(string[] args)
{
SerialPort sp = new SerialPort("COM3");

sp.Open();
sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived); //注册DataReceived事件,当收到数据时调用 sp_DataReceived
while (true) { }
}

static void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort port = (SerialPort)sender;
byte[] buf = new byte[port.ReadBufferSize];
int len = 0;

//将数据读入内存流
MemoryStream ms = new MemoryStream();
len = port.Read(buf, 0, buf.Length);
ms.Write(buf, 0, len);

buf = ms.ToArray();
FormatData(buf); //处理数据
}
static BinData FormatData(byte[] buf)
{
BinData d = new BinData();
d.Length = buf[0];//第一字节 长度
d.Header = new byte[2] { buf[1], buf[2] }; //1,2字节没用
d.Flag = new byte[2] { buf[3], buf[4] }; // 3,4 字节截出来
d.Padding = buf[5]; //5没用
byte[] data = new byte[d.Length - 7];
Buffer.BlockCopy(buf, 7, data, 0, d.Length - 7); //截取7~长度-7 数据
d.Data = data;
return d;
}
}

class Program
{
struct BinData
{
public byte Length; //长度 8bit
public byte[] Header; // 1,2 字节没用
public byte[] Flag;// 3,4 字节截出来
public byte Padding; // 5没用
public byte[] Data; // 7~17 有用
}

static void Main(string[] args)
{
SerialPort sp = new SerialPort("COM3");

sp.Open();
sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived); //注册DataReceived事件,当收到数据时调用 sp_DataReceived
while (true) { }
}

static void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort port = (SerialPort)sender;
byte[] buf = new byte[port.ReadBufferSize];
int len = 0;

//将数据读入内存流
MemoryStream ms = new MemoryStream();
len = port.Read(buf, 0, buf.Length);
ms.Write(buf, 0, len);

buf = ms.ToArray();
FormatData(buf); //处理数据
}
static BinData FormatData(byte[] buf)
{
BinData d = new BinData();
d.Length = buf[0];//第一字节 长度
d.Header = new byte[2] { buf[1], buf[2] }; //1,2字节没用
d.Flag = new byte[2] { buf[3], buf[4] }; // 3,4 字节截出来
d.Padding = buf[5]; //5没用
byte[] data = new byte[d.Length - 7];
Buffer.BlockCopy(buf, 7, data, 0, d.Length - 7); //截取7~长度-7 数据
d.Data = data;
return d;
}
}

使用System.IO.Port.SerialPort类实现串口通信

System.IO.Port.SerialPort类介绍

System.IO.Port.SerialPort是.NET Framework提供的操作串行端口的类,里面提供了一些方法、属性和和事件供开发者调用操作串口。

调用流程

1. 直接调用SerialPort的静态方法GetPortNames()获取当前计算机的串行端口名称数组

2.根据串口名称,初始化SerialPort对象,设置参数,调用Open()方法打开串口

3.调用Write()方法发送数据

4.注册接收数据的监听,获取数据(或者另起线程循环读取接收数据,本文使用注册监听方式接收数据)    

具体代码实现

using System;  
using System.IO.Ports;  
using System.Text;

namespace PortControlDemo  
{
public class PortControlHelper
{
#region 字段/属性/委托
/// <summary>
/// 串行端口对象
/// </summary>
private SerialPort sp;

/// <summary>
/// 串口接收数据委托
/// </summary>
public delegate void ComReceiveDataHandler(string data);

public ComReceiveDataHandler OnComReceiveDataHandler = null;

/// <summary>
/// 端口名称数组
/// </summary>
public string[] PortNameArr { get; set; }

/// <summary>
/// 串口通信开启状态
/// </summary>
public bool PortState { get; set; } = false;

/// <summary>
/// 编码类型
/// </summary>
public Encoding EncodingType { get; set; } = Encoding.ASCII;
#endregion

#region 方法
public PortControlHelper()
{
PortNameArr = SerialPort.GetPortNames();
sp = new SerialPort();
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
}

/// <summary>
/// 打开端口
/// </summary>
/// <param name="portName">端口名称</param>
/// <param name="boudRate">波特率</param>
/// <param name="dataBit">数据位</param>
/// <param name="stopBit">停止位</param>
/// <param name="timeout">超时时间</param>
public void OpenPort(string portName , int boudRate = 115200, int dataBit = 8, int stopBit = 1, int timeout = 5000)
{
try
{
sp.PortName = portName;
sp.BaudRate = boudRate;
sp.DataBits = dataBit;
sp.StopBits = (StopBits)stopBit;
sp.ReadTimeout = timeout;
sp.Open();
PortState = true;
}
catch (Exception e)
{
throw e;
}
}

/// <summary>
/// 关闭端口
/// </summary>
public void ClosePort()
{
try
{
sp.Close();
PortState = false;
}
catch (Exception e)
{
throw e;
}
}

/// <summary>
/// 发送数据
/// </summary>
/// <param name="sendData"></param>
public void SendData(string sendData)
{
try
{
sp.Encoding = EncodingType;
sp.Write(sendData);
}
catch (Exception e)
{
throw e;
}
}

/// <summary>
/// 接收数据回调用
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] buffer = new byte[sp.BytesToRead];
sp.Read(buffer, 0, buffer.Length);
string str = EncodingType.GetString(buffer);
if (OnComReceiveDataHandler != null)
{
OnComReceiveDataHandler(str);
}
}
#endregion
}  
}

View Code

三、编写Winform串口通信工具界面

界面预览



可以给你做,简单的事情,做好程序打包发给你.如需要直接发私信


石拐区15258774076: 如何使用C# 进行串口的读写,请详细点 -
兆卿艾麦: 一、C#串口操作之读取串口数据:try { axMSComm2.CommPort = 1i; axMSComm2.InputMode = MSCommLib.InputModeConstants.comInputModeBinary; //用于设置或返回传输数据的类型, //此例程是通过Input属性以二进制方式检取回数据 ...

石拐区15258774076: 怎么在c#应用程序中读取串口传送过来的数据 -
兆卿艾麦: //创建一个串口通讯 SerialPort CurrentPort = null; CurrentPort = new SerialPort(); CurrentPort.ReadBufferSize = 128; CurrentPort.PortName = comName; //端口号CurrentPort.BaudRate = bandRate; //比特率CurrentPort.Parity =parity;//奇偶校...

石拐区15258774076: 在C#中怎样实现串口通讯接受数据 -
兆卿艾麦: C#实现串口通讯你肯定得用到SerialPort,打开串口连接后,绑定DataReceived事件就能接收数据

石拐区15258774076: 怎样用C#读取串口数据 -
兆卿艾麦: 可以使用SerialPort这个控件或者类,可以从电脑的COM口中读取串口发过来的数据.具体可参见MSDN:SerialPort类,希望可以帮到你.

石拐区15258774076: 在c#的web中怎样实现与串口通讯 -
兆卿艾麦: 使用使用serialport这个类,可以在DataReceived事件中作处理.也可以直接使用Read、和Write函数对串口进行操作.

石拐区15258774076: c# 关于从串口读取数据
兆卿艾麦: 可以使用System.IO.Ports命名空间 先创建一个串口对象,然后进行读写操作. 具体见: http://www.codeproject.com/KB/cs/serialcommunication.aspx

石拐区15258774076: 如何用c#读取串口数据 -
兆卿艾麦: Main方法是必须且只有一个.static void Main() {//程序入口点...}

石拐区15258774076: c# 读取串口数据
兆卿艾麦: C# API方式串口读写 该文章转载自德仔工作室: http://www.dezai.cn/Article_Show.asp?ArticleID=23626 C#中串口通信编程 该文章转载自德仔工作室: http://www.dezai.cn/Article_Show.asp?ArticleID=24179 NET平台下通用的串口操作类 该文章转载自德仔工作室: http://www.dezai.cn/Article_Show.asp?ArticleID=24088

石拐区15258774076: 如何在C#下实现串口通信?求详解~ -
兆卿艾麦: System.IO.Ports命名空间下有一个专门用来访问串口的类SerialPort.SerialPort port = new SerialPort();// 设置串口参数,必须与对端的参数相同 port.PortName = "COM1"; // 串口名称 port.BaudRate = 2400; // 波特率 port.DataBits = 7; ...

石拐区15258774076: 请教高手:想使用C#命令对电脑的串口实现读写数据,不知从哪里下手?请指教 -
兆卿艾麦: //得到机器上所有的端口,32313133353236313431303231363533e58685e5aeb931333264643164并且显示在ComBox里面private void Form1_Load(object sender, EventArgs e) {Computer pc = new Computer(); foreach (string port in pc.Ports...

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 星空见康网