HANDLE hCom=0;
DCB dcb;
OVERLAPPED OverRead, OverWrite;
COMSTAT comstat;
OVERLAPPED os;
DWORD dwEvtMask=0;
//---------------------------------------------------------------------------
//初始化串口
int __stdcall InitCom(int port,int baud)
{
AnsiString comname;
comname="COM"+IntToStr(port);
CloseHandle(hCom);
COMMTIMEOUTS CommTimeOuts;
if(hCom==INVALID_HANDLE_VALUE)
{
switch (GetLastError())
{
case ERROR_FILE_NOT_FOUND: MessageBox(NULL,"串口不存在!","提示信息",NULL );
break;
case ERROR_ACCESS_DENIED: MessageBox(NULL,"串口已被占用!","提示信息",NULL);
break;
}
return 0;
}
if(hCom!=0)
{
return 0;
}
hCom=CreateFile(comname.c_str(), //文件名
GENERIC_READ|GENERIC_WRITE,//访问模式允许读写
0, //此项必须是0
NULL,//无安全参数
OPEN_EXISTING,//创建方式
FILE_FLAG_OVERLAPPED,//异步工作方式
NULL);
if(hCom==INVALID_HANDLE_VALUE)
{
ShowMessage("打开串口失败!");
return 0;
}
if(!GetCommState(hCom,&dcb)) //获得串口设置并用它填充dcb结构体
{
ShowMessage("获得串口设置失败!");
return 0;
}
if(!SetupComm(hCom,1024,512)) //设置输入输出缓冲区大小
{
ShowMessage("设置输入输出缓冲区大小失败!");
return 0;
}
//设置dcb结构成员变量
dcb.BaudRate=baud;
dcb.fParity=0;
dcb.Parity=NOPARITY;
dcb.StopBits=ONESTOPBIT;
dcb.ByteSize=8;
dcb.fNull=FALSE;
dcb.fInX=true;
dcb.fOutX=true;
dcb.XonLim=1;
dcb.XoffLim=1;
dcb.fRtsControl=RTS_CONTROL_DISABLE;
if(!SetCommState(hCom,&dcb)) //重新配置串口
{
ShowMessage("配置串口失败!");
return 0;
}
//获取串行口超时参数
GetCommTimeouts(hCom,&CommTimeOuts);
CommTimeOuts.ReadIntervalTimeout=0xFFFFFFFF;
CommTimeOuts.WriteTotalTimeoutConstant=5000;
if(!SetCommMask(hCom,EV_RXCHAR))
{
ShowMessage("设置事件掩码失败!");
return 0;
}
SetCommTimeouts(hCom,&CommTimeOuts); // 设置超时
memset(&OverRead,0,sizeof(OVERLAPPED));
memset(&OverWrite,0,sizeof(OVERLAPPED));
OverRead.hEvent=CreateEvent(NULL,true,false,NULL);
OverWrite.hEvent=CreateEvent(NULL,true,false,NULL);
OverWrite.Offset=0;
OverWrite.OffsetHigh=0;
}
//向串口写数据
void __fastcall Sendsms(void* chStr,,unsigned long StrLen)
{
unsigned long Written ;
BOOL WriteState=WriteFile(hCom,
chStr,
StrLen,
&Written
&OverWrite);
if((!WriteState || StrLen!=Written) && (GetLastError()==ERROR_IO_PENDING))
{
//ShowMessage("错误!");
}
}
//-----------------------------------------------------------------------------
为什么总是不能向串口写入(AT命令)数据呢?请指点一下,谢谢!
3 个解决方案
#1
__stdcall ??
#2
全部改成__fastcall 试试
#3
还是不行啊
#1
__stdcall ??
#2
全部改成__fastcall 试试
#3
还是不行啊