读写串口的问题
我用C写的DLL,打开/关闭/读写串口(1个字符),打开/关闭都没问题了,可写串口总是出错,查到错误是The handle is invalid. 在网上也查了相关的资料,对比以后还是找不到出错原因。我是新手,请各位多多指教,谢谢
# include <windows.h>
# include <winbase.h>
extern "C"
{
HANDLE __stdcall OpenDevice
(unsigned char chComPort);
unsigned char __stdcall CloseDevice
(HANDLE hDeviceNum);
int CheckDevice
(HANDLE hDeviceNum);//检测是否使用正确的设备
}
#define ENQ 0x5
#define ACK 0x6
#define NAK 0x15
static HANDLE hDevice;//get used device
int errHType,errHCode,errL,errH;//get error number L-made by hardware H-made by dll
BOOL WINAPI DllEntryPoint(HINSTANCE hDLL,DWORD dwReason,LPVOID Reserved)
{
switch(dwReason)
{
case DLL_PROCESS_ATTACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
HANDLE __stdcall OpenDevice(unsigned char chComPort)
{
char chComName[5];
HANDLE hDeviceNum;
DCB dDcb;
COMMTIMEOUTS TimeOuts;
BOOL fState;
unsigned char pChar;
unsigned char pc[5];
DWORD length;
OVERLAPPED osWrite;
DWORD l1=0;
switch(chComPort)
{
case 1:
strcpy(chComName,"COM1");
break;
case 2:
strcpy(chComName,"COM2");
break;
case 3:
strcpy(chComName,"COM3");
break;
case 4:
strcpy(chComName,"COM4");
};
//open the Com
hDeviceNum=NULL;
hDeviceNum=CreateFile(chComName,
GENERIC_READ|GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,
NULL);
if (hDeviceNum==INVALID_HANDLE_VALUE)
return NULL;
SetupComm(hDeviceNum,256,256);
SetCommMask(hDeviceNum,EV_RXCHAR);
//set the OverTime of the Com
TimeOuts.ReadIntervalTimeout =MAXDWORD;
TimeOuts.ReadTotalTimeoutConstant =2000;
TimeOuts.ReadTotalTimeoutMultiplier =MAXDWORD;
TimeOuts.WriteTotalTimeoutMultiplier =50;
TimeOuts.WriteTotalTimeoutConstant =2000;
SetCommTimeouts(hDeviceNum,&TimeOuts);
//set the State of the Com
GetCommState(hDeviceNum,&dDcb);
dDcb.fNull =FALSE;
dDcb.fBinary =TRUE;
dDcb.BaudRate =19200;
dDcb.fParity =FALSE;
dDcb.Parity =NOPARITY;
dDcb.ByteSize =0x8;
dDcb.StopBits=ONESTOPBIT;
SetCommState(hDeviceNum,&dDcb);
hDevice=hDeviceNum;
pChar=ENQ;
length=1;
fState=FALSE;
ClearCommError(m_hCom,&dwErrorFlags,&ComStat);
PurgeComm(hDeviceNum,PURGE_TXCLEAR);
fState=WriteFile(hDeviceNum,&pChar,length,&l1,&osWrite);
if(!fState)
if(GetLastError()==ERROR_IO_PENDING)
GetOverlappedResult(hDeviceNum,&osWrite,&length,TRUE);// 等待
return hDeviceNum;
}
unsigned char __stdcall CloseDevice(HANDLE hDeviceNum)
{
unsigned char i;
if(CheckDevice(hDeviceNum)!=1)
i=0;
else
{
CloseHandle(hDeviceNum);
i=1;
}
return i;
}
int CheckDevice(HANDLE hDeviceNum)
{
if(hDeviceNum==hDevice)
errH=1;
else
{
errHType=0x01;
errHCode=00;
errH=(-1)*((errHType<<11)|(errHCode<<8));
}
return errH;
}