c# wifi串口通信_在C#中实现串口通信的方法
通常,在C#中实现串口通信,我们有四种方法:
第一:通过MSCOMM控件这是最简单的,最方便的方法。可功能上很难做到控制自如,同时这个控件并不是系统本身所带,所以还得注册,不在本文讨论范围。可以访问http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=320 ,一个国外网友的写的教程,作者很热心,我曾有发邮件给他,很快就回复了。
第二:微软在.NET新推出了一个串口控件,基于.NET的P/Invoke调用方法实现,详细的大家可以访问微软网站http://msdn.microsoft.com/msdnmag/issues/02/10/NETSerialComm/default.aspx,方便得到更多资料。
第三:就是用第三方控件啦,可一般都要付费的,不太合实际,不作考虑
第四:自己用API写串口通信,这样难度高点,但对于我们来说,可以方便实现自己想要的各种功能
在本文,我们采用第四种方法来实现串口通信,不过不是自己写,用一个国外网友现成的已经封装好的类库,不过功能简单点,相对我们来说已经够用了。
在整个终端短信的操作过程中,与串口的通信,只用到了四个功能,打开、写、读、关闭串口。下面是类库对这四个功能的定义:
打开串口:
函数原型:public void Open()
说明:打开事先设置好的端口
示例:
using JustinIO;
static JustinIO.CommPort ss_port = new JustinIO.CommPort();
ss_port.PortNum = COM1; //端口号
ss_port.BaudRate = 19200; //串口通信波特率
ss_port.ByteSize = 8; //数据位
ss_port.Parity = 0; //奇偶校验
ss_port.StopBits = 1;//停止位
ss_port.ReadTimeout = 1000; //读超时
try
{
if (ss_port.Opened)
{
ss_port.Close();
ss_port.Open(); //打开串口
}
else
{
ss_port.Open();//打开串口
}
return true;
}
catch(Exception e)
{
MessageBox.Show("错误:" + e.Message);
return false;
}
写串口:
函数原型:public void Write(byte[] WriteBytes)
WriteBytes 就是你的写入的字节,注意,字符串要转换成字节数组才能进行通信
示例:
ss_port.Write(Encoding.ASCII.GetBytes("AT+CGMI\r")); //获取手机品牌
读串口:
函数原型:public byte[] Read(int NumBytes)
NumBytes 读入缓存数,注意读取来的是字节数组,要实际应用中要进行字符转换
示例:
string response = Encoding.ASCII.GetString(ss_port.Read(128)); //读取128个字节缓存
关闭串口:
函数原型:ss_port.Close()
示例:
ss_port.Close();
由于篇幅,以及串口通信涉及内容广泛,我在这里只讲这些。
在上面我们已经把终端短信所需的各种原始技术有所了解,是可以小试牛刀的时候了。
using System;
using System.Runtime.InteropServices;
namespace BusApp
{
///
///
///
public class mycom
{
public mycom()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public int PortNum; //1,2,3,4
public int BaudRate; //1200,2400,4800,9600
public byte ByteSize; //8 bits
public byte Parity; // 0-4=no,odd,even,mark,space
public byte StopBits; // 0,1,2 = 1, 1.5, 2
public int ReadTimeout; //10
//comm port win32 file handle
private int hComm = -1;
public bool Opened = false;
//win32 api constants
private const uint GENERIC_READ = 0x80000000;
private const uint GENERIC_WRITE = 0x40000000;
private const int OPEN_EXISTING = 3;
private const int INVALID_HANDLE_VALUE = -1;
[StructLayout(LayoutKind.Sequential)]
private struct DCB
{
//taken from c struct in platform sdk
public int DCBlength; // sizeof(DCB)
public int BaudRate; // current baud rate
public int fBinary; // binary mode, no EOF check
public int fParity; // enable parity checking
public int fOutxCtsFlow; // CTS output flow control
public int fOutxDsrFlow; // DSR output flow control
public int fDtrControl; // DTR flow control type
public int fDsrSensitivity; // DSR sensitivity
public int fTXContinueOnXoff; // XOFF continues Tx
public int fOutX; // XON/XOFF out flow control
public int fInX; // XON/XOFF in flow control
public int fErrorChar; // enable error replacement
public int fNull; // enable null stripping
public int fRtsControl; // RTS flow control
public int fAbortOnError; // abort on error
public int fDummy2; // reserved
public ushort wReserved; // not currently used
public ushort XonLim; // transmit XON threshold
public ushort XoffLim; // transmit XOFF threshold
public byte ByteSize; // number of bits/byte, 4-8
public byte Parity; // 0-4=no,odd,even,mark,space
public byte StopBits; // 0,1,2 = 1, 1.5, 2
public char XonChar; // Tx and Rx XON character
public char XoffChar; // Tx and Rx XOFF character
public char ErrorChar; // error replacement character
public char EofChar; // end of input character
public char EvtChar; // received event character
public ushort wReserved1; // reserved; do not use
}
[StructLayout(LayoutKind.Sequential)]
private struct COMMTIMEOUTS
{
public int ReadIntervalTimeout;
public int ReadTotalTimeoutMultiplier;
public int ReadTotalTimeoutConstant;
public int WriteTotalTimeoutMultiplier;
public int WriteTotalTimeoutConstant;
}
[StructLayout(LayoutKind.Sequential)]
private struct OVERLAPPED
{
public int Internal;
public int InternalHigh;
public int Offset;
public int OffsetHigh;
public int hEvent;
}
[DllImport("kernel32.dll")]
private static extern int CreateFile(
string lpFileName, // file name
uint dwDesiredAccess, // access mode
int dwShareMode, // share mode
int lpSecurityAttributes, // SD
int dwCreationDisposition, // how to create
int dwFlagsAndAttributes, // file attributes
int hTemplateFile // handle to template file
);
[DllImport("kernel32.dll")]
private static extern bool GetCommState(
int hFile, // handle to communications device
ref DCB lpDCB // device-control block
);
[DllImport("kernel32.dll")]
private static extern bool BuildCommDCB(
string lpDef, // device-control string
ref DCB lpDCB // device-control block
);
[DllImport("kernel32.dll")]
private static extern bool SetCommState(
int hFile, // handle to communications device
ref DCB lpDCB // device-control block
);
[DllImport("kernel32.dll")]
private static extern bool GetCommTimeouts(
int hFile, // handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // time-out values
);
[DllImport("kernel32.dll")]
private static extern bool SetCommTimeouts(
int hFile, // handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // time-out values
);
[DllImport("kernel32.dll")]
private static extern bool ReadFile(
int hFile, // handle to file
byte[] lpBuffer, // data buffer
int nNumberOfBytesToRead, // number of bytes to read
ref int lpNumberOfBytesRead, // number of bytes read
ref OVERLAPPED lpOverlapped // overlapped buffer
);
[DllImport("kernel32.dll")]
private static extern bool WriteFile(
int hFile, // handle to file
byte[] lpBuffer, // data buffer
int nNumberOfBytesToWrite, // number of bytes to write
ref int lpNumberOfBytesWritten, // number of bytes written
ref OVERLAPPED lpOverlapped // overlapped buffer
);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(
int hObject // handle to object
);
public void Open()
{
DCB dcbCommPort = new DCB();
COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();
// OPEN THE COMM PORT.
hComm = CreateFile("COM" + PortNum ,GENERIC_READ | GENERIC_WRITE,0, 0,OPEN_EXISTING,0,0);
// IF THE PORT CANNOT BE OPENED, BAIL OUT.
if(hComm == INVALID_HANDLE_VALUE)
{
throw(new ApplicationException("Comm Port Can Not Be Opened"));
}
// SET THE COMM TIMEOUTS.
GetCommTimeouts(hComm,ref ctoCommPort);
ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout;
ctoCommPort.ReadTotalTimeoutMultiplier = 0;
ctoCommPort.WriteTotalTimeoutMultiplier = 0;
ctoCommPort.WriteTotalTimeoutConstant = 0;
SetCommTimeouts(hComm,ref ctoCommPort);
// SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
// THERE ARE OTHER WAYS OF DOING SETTING THESE BUT THIS IS THE EASIEST.
// IF YOU WANT TO LATER ADD CODE FOR OTHER BAUD RATES, REMEMBER
// THAT THE ARGUMENT FOR BuildCommDCB MUST BE A POINTER TO A STRING.
// ALSO NOTE THAT BuildCommDCB() DEFAULTS TO NO HANDSHAKING.
dcbCommPort.DCBlength = Marshal.SizeOf(dcbCommPort);
GetCommState(hComm, ref dcbCommPort);
dcbCommPort.BaudRate=BaudRate;
dcbCommPort.Parity=Parity;
dcbCommPort.ByteSize=ByteSize;
dcbCommPort.StopBits=StopBits;
SetCommState(hComm, ref dcbCommPort);
Opened = true;
}
public void Close()
{
if (hComm!=INVALID_HANDLE_VALUE)
{
CloseHandle(hComm);
Opened=false;
}
}
public byte[] Read(int NumBytes)
{
byte[] BufBytes;
byte[] OutBytes;
BufBytes = new byte[NumBytes];
if (hComm!=INVALID_HANDLE_VALUE)
{
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesRead=0;
ReadFile(hComm,BufBytes,NumBytes,ref BytesRead,ref ovlCommPort);
OutBytes = new byte[BytesRead];
Array.Copy(BufBytes,OutBytes,BytesRead);
}
else
{
throw(new ApplicationException("Comm Port Not Open"));
}
return OutBytes;
}
public int Write(byte[] WriteBytes)
{
int BytesWritten = 0;
if (hComm!=INVALID_HANDLE_VALUE)
{
OVERLAPPED ovlCommPort = new OVERLAPPED();
WriteFile(hComm,WriteBytes,WriteBytes.Length,ref BytesWritten,ref ovlCommPort);
}
else
{
throw(new ApplicationException("Comm Port Not Open"));
}
return BytesWritten;
}
}
}
c# wifi串口通信_在C#中实现串口通信的方法相关推荐
- java socket分包粘包 代码_分享java中处理socket通信过程中粘包情况的实例代码
本篇文章主要介绍了java中处理socket通信过程中粘包的情况,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 这两天学习了java中处理socket通信过程中粘包的情况,而且很重要,所以,今天添 ...
- FPGA 串口中断_一个严谨的STM32串口DMA发送amp;接收(1.5Mbps波特率)机制
昨天分享的<嵌入式大杂烩读者福利:第一期>大家有去抽奖吗,没抽的可参与抽奖,碰碰运气.我最喜欢抽奖了,还记得前几个月疫情严重时期连抽中了3包口罩,真刺激,哈哈.之后多多安排抽奖,敬请期待. ...
- linux关闭串口控制台输入,关闭Linux中的串口打印
项目中用到串口通信,但是这个串口也用于控制台.为了保证串口通信时不能有控制台发出的消息,需要关闭打印. 在测试过程中发现,有三种类型的打印,一是uboot的打印,在Starting kernel .. ...
- openmv串口数据 串口助手_齐安安小课堂 | 串口数据抓取以及串口数据模拟
各位同学们好,好久不见! 齐安安小课堂又双叒叕开课啦~ 本期来讲讲在工控现场使用的设备中 有哪些普遍存在又容易被忽视的安全隐患 只有重视每一个小细节 才能对工业安全做出更好的防护哦~ 引言 在工控现场 ...
- java通信项目_Java项目中的多线程通信如何利用Socket实现
Java项目中的多线程通信如何利用Socket实现 发布时间:2020-11-24 16:44:40 来源:亿速云 阅读:96 作者:Leah 这期内容当中小编将会给大家带来有关Java项目中的多线程 ...
- python怎么横着输出_对python3中, print横向输出的方法详解
对python3中, print横向输出的方法详解 Python 2 : print打印的时候,如果结尾有逗号,打出来时候不会换行.但是在python3里面就不行了. Python3: 3.0的pri ...
- pyqt5 qscrollarea到达_在PYQT5中QscrollArea(滚动条)的使用方法
如下所示: import sys from PyQt5.QtWidgets import * class MainWindow(QMainWindow): def __init__(self,): s ...
- created写法_在vue中created、mounted等方法使用小结
created:html加载完成之前,执行.执行顺序:父组件-子组件 mounted:html加载完成后执行.执行顺序:子组件-父组件 methods:事件方法执行 watch:watch是去监听一个 ...
- 在mybatis用mysql的代码块_关于Mybatis 中使用Mysql存储过程的方法
1.存储过程的简介 我们常用的操作数据库语言SQL语句在执行的时候需要要先编译,然后执行,而存储过程(Stored Procedure)是一组为了完成特定功能的SQL语句集,经编译后存储在数据库中,用 ...
最新文章
- JavaEE 企业级分布式高级架构师课程_汇总贴
- Thread类源码剖析
- 【最简便解法】1069 微博转发抽奖 (20分)
- Linux 目录详细说明
- HDU 1247 Hat’s Words 字典树(Trie树)
- sql视图能使用触发器吗_冰箱买回家能立即使用吗 冰箱买回家要放多久能使用【详解】...
- Vue编写动态组件实践(render函数的使用心得)
- python输出重定向记录
- NIPS 又!放!票!了!
- 《Spring In Action(第4版)》阅读总结(四)渲染Web视图
- Angualr routerLink 两种传参方法及参数的使用
- Windows Server 2012 修复ms17-010漏洞提示 此更新不适用于你的计算机
- 在服务器上打不开新点投标文件,新点投标文件制作操作手册.doc
- 设备状态监测系统提升企业设备管理水平
- dubbo源码分析23 -- provider 接收与发送原理
- VMware Horizon 8安装部署(八)访问测试,成功部署。
- (分布式网络)基于残差网络的多光谱全色图像分布式融合框架
- 面试官:Redis中哈希分布不均匀该怎么办
- C++ 1 之 冲刺期末不挂科的入门
- 内存,外存,运存,显存,闪存,硬盘,SSD等概念
热门文章
- mongodb 复制集部署(主从升级版)
- wdcp mysql configure error_install Error: mysql configure err
- 极路由s1有wds_极路由1、1s等机型刷OpenWrt--成为真正的极客
- AI+智能服务机器人应用基础【实践报告】
- three.js网页demo展示
- Android开发辅助工具类 Utils
- ubuntu下安装Realtek usb无线网卡驱动(8821cu)
- 破解帐户后,黑客重现如何榨干用户的最终价值
- 【综合复习_网络部分】
- 深度神经网络的训练过程,深度神经网络训练方法