Win32串口操作的技巧

本文详细介绍了在Win32环境下如何操作串口,包括使用CreateFile()打开串口,SetupComm()设置缓冲区,CloseHandle()关闭串口,GetCommProperties()获取串口信息,SetCommState()和GetCommState()设定与获取通信状态,以及读写数据、设置超时、事件驱动I/O等关键操作。此外,还讨论了如何处理错误和使用硬件控制命令。
摘要由CSDN通过智能技术生成
1.开启一个 Serial Port

  利用一般开启档案的 CreatFile() 即可开启 serial port device

HANDLE CreateFile(
LPCTSTR lpFileName, // pointer to name of the file
DWORD dwDesiredAccess, // access (read-write) mode
DWORD dwShareMode, // share mode
LPSECURITY_ATTRIBUTES lpSecurityAttributes, // pointer to security attributes
DWORD dwCreationDistribution, // how to create
DWORD dwFlagsAndAttributes, // file attributes
HANDLE hTemplateFile // handle to file with attributes to copy
);

  用 CreateFile() API.
  lpFileName 为 "COM1" 或是 "COM2"
  dwDersiredAccess 一般为 GENERIC_READ|GENERIC_WRITE
  dwShareMode "必须"为 0, 即不能共享, 但同一个 process 中的不同 thread 在一开启之后就可以共享.
  lpSecurityAttributes 一般为 NULL
  dwCreateionDistributon 在这里"必须"为 OPEN_EXISTING
  dwFlagsAndAttributes 定义了开启的属性, 若是设成 FILE_FLAG_OVERLAPPED 则可使用异步的 I/O.
  hTemplateFile "必须"为 NULL
  传回档案 handle
  设定 Serial Port 传送及接收缓冲区的大小

  在开启完 serial port 之后, 可以藉由呼叫 SetupComm() 来进行配置传送时的缓冲区及接收时的缓冲区. 如果没有呼叫 SetupComm() 的话, Win95 会配置内定的缓冲区.

BOOL SetupComm(
HANDLE hFile, // handle of communications device
DWORD dwInQueue, // size of input buffer
DWORD dwOutQueue // size of output buffer
);

  2.关闭 Serial Port file

  利用一般的 CloseHandle() 即可.

BOOL CloseHandle(
HANDLE hObject // handle to object to close

  3.取得 Seial Port 的信息

  在 Win32 里头, 将一些通讯时会用到的信息用 COMMPROP 这个结构来表示. (当然不仅仅是 Serial Port) 可以用 GetCommProperties() 来取得:

BOOL GetCommProperties(
HANDLE hFile, // handle of communications device
LPCOMMPROP lpCommProp // address of communications properties structure
);

  COMMPROP 长的像这个样子:

typedef struct _COMMPROP { // cmmp
WORD wPacketLength; // packet size, in bytes
WORD wPacketVersion; // packet version
DWORD dwServiceMask; // services implemented
DWORD dwReserved1; // reserved
DWORD dwMaxTxQueue; // max Tx bufsize, in bytes
DWORD dwMaxRxQueue; // max Rx bufsize, in bytes
DWORD dwMaxBaud; // max baud rate, in bps
DWORD dwProvSubType; // specific provider type
DWORD dwProvCapabilities; // capabilities supported
DWORD dwSettableParams; // changable parameters
DWORD dwSettableBaud; // allowable baud rates
WORD wSettableData; // allowable byte sizes
WORD wSettableStopParity; // stop bits/parity allowed
DWORD dwCurrentTxQueue; // Tx buffer size, in bytes
DWORD dwCurrentRxQueue; // Rx buffer size, in bytes
DWORD dw
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值