




已阅读5页,还剩2页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
C#串口通信打开串口: 函数原型: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+CGMIr); /获取手机品牌 读串口: 函数原型: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 JustinIO class CommPort public int PortNum; public int BaudRate; public byte ByteSize; public byte Parity; / 0-4=no,odd,even,mark,space public byte StopBits; / 0,1,2 = 1, 1.5, 2 public int ReadTimeout; /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) public struct DCB /taken from c struct in platform sdk public int DCBlength; / sizeof(DCB) public int BaudRate; / current baud rate /* these are the c struct bit fields, bit twiddle flag to set 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 uint flags; 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 ); DllImport(kernel32.dll) private static extern uint GetLastError(); 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. GetCommState(hComm, ref dcbCommPort); dcbCommPort.BaudRate=BaudRate; dcbCommPort.flags=0; /dcb.fBinary=1; dcbCommPort.flags|=1; if (Parity0) /dcb.fParity=1 dcbCommPort.flags|=2; dcbCommPort.Parity=Parity; dcbCommPort.ByteSize=ByteSize; dcbCommPort.StopBits=StopBits; if (!SetCommState(hComm, ref dcbCommPort) /uint ErrorNum=GetLastError(); throw(new ApplicationException(Comm Port Can Not Be Opened); /unremark to see if setting took correctly /DCB dcbCommPort2 = new DCB(); /GetCommState(hComm, ref dcbCommPort2); Opened = true; public void Close() if (hComm!=INVALI
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- Z=82附近原子核形状共存研究
- 面向数据与设备异构的联邦学习优化方法研究与应用
- 精神疾病健康指导
- 精油开背培训
- 超声科科室简介
- 关注心理健康 创造和谐班级
- 预防食源性疾病课件
- 顺丰快递教学课件
- 幼儿园教师教育教学能力提升培训
- 音乐说课教育课件
- 放化疗相关口腔黏膜炎预防及护理课件
- 北京市海淀区2025届高一下生物期末检测模拟试题含解析
- JT∕T 795-2023 事故汽车修复技术规范
- 2024四川广元市检察机关招聘聘用制书记员22人笔试备考题库及答案解析
- 内科患者VTE风险评估表
- 一年级上册美术教案-第1课 让大家认识我:诚实最好 ▏人美版
- 科学认识天气智慧树知到期末考试答案2024年
- (高清版)DZT 0064.15-2021 地下水质分析方法 第15部分:总硬度的测定 乙二胺四乙酸二钠滴定法
- 心理体检收费目录
- 雅鲁藏布江米林-加查段沿线暴雨泥石流危险度评价的中期报告
- 抗生素的正确使用与合理配比
评论
0/150
提交评论