谢谢各位了。现在是需要写一个名为Dmeasure的类,类的作用是输入端口和波特率,发送命令之后,再把接收到的数据打印出来。
这是名为Dmeasure.h的头文件
ifndef Dmeasure_H
#define Dmeasure_H
#include <windows.h>
#include <winNt.h>
#include <stdlib.h>
#include <iostream>
#include <conio.h>
class Dmeasure
{
public:
Dmeasure(char* Pname,int rate_arg=9600);
int getdistance();//测量距离的函数声明
private:
int rate;
char* portname;
int m_distance;
OVERLAPPED m_ov;
COMSTAT comstat;
HANDLE hComm;
HANDLE hCanReceiveEvent;
char ConvertHexChar(char ch);//将字符转换为相应的十六进制值
bool ProcessErrorMessage(char* ErrorText);//错误处理
bool openport();//打开一个串口
bool setupdcb(int rate_arg);//设置波特率
bool setuptimeout(DWORD ReadInterval,DWORD ReadTotalMultiplier,DWORD ReadTotalconstant,DWORD WriteTotalMultiplier,DWORD WriteTotalconstant);
bool WriteChar(BYTE *m_szWriteBuffer,DWORD m_nToSend); //向串口写入命令
void Writepart();
};
#endif
以下是Dmeasure.cpp文件
#include "stdafx.h"
#include "Dmeasure.h"
Dmeasure::Dmeasure(char* Pname,int rate_arg) //构造函数,包括打开串口和波特率设置
{
portname = Pname;
rate = rate_arg;
hCanReceiveEvent = CreateEvent(NULL,FALSE,FALSE,NULL);//这句是不是不用线程的话,可以省略?
if(openport())
printf("open comport success\n");
//printf("%p\n",hComm);
if(setupdcb(rate))
printf("setupDCB success\n");
if(setuptimeout(0,0,0,0,0))
printf("setuptimeout success\n");
PurgeComm(hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
}
bool Dmeasure::openport()//打开一个串口
{
DWORD dwNum = MultiByteToWideChar (CP_ACP, 0, portname, -1, NULL, 0);
wchar_t *pwText;
pwText = new wchar_t[dwNum];
if(!pwText)
{
delete []pwText;
}
MultiByteToWideChar (CP_ACP, 0, portname, -1, pwText, dwNum);
hComm = CreateFile(pwText,//串口号
GENERIC_READ | GENERIC_WRITE,//允许读写
0, //通讯设备必须以独立方式打开
0, //无安全属性
OPEN_EXISTING, //通讯设备存在
FILE_ATTRIBUTE_NORMAL, //异步I/O
0); //通讯设备不能用模板打开
if (hComm == INVALID_HANDLE_VALUE)
return FALSE;
else
return true;
}
bool Dmeasure::setupdcb(int rate)
{
DCB dcb;
memset(&dcb,0,sizeof(dcb));//清零dcb
if(!GetCommState(hComm,&dcb))//获取当前DCB配置
{
ProcessErrorMessage("GetCommState()");
return FALSE;
}
/* -------------------------------- */
// set DCB to configure the serial port