用API函数编写的串口通信,端口打开了,WriteFile总是反回调用失败类型为0;以下是程序,我是新手,谢谢帮
HANDLEhComm;hComm=CreateFile("COM1",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,FILE...
HANDLE hComm;
hComm=CreateFile("COM1",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,0);
if(hComm==INVALID_HANDLE_VALUE)
{
MessageBox("chucho");
return;
}
DCB dcb;
COMMTIMEOUTS CommTimeouts;
CString string;
dcb.DCBlength=sizeof(DCB);
GetCommState(hComm,&dcb);
dcb.BaudRate=9600;
dcb.ByteSize=8;
dcb.fBinary=TRUE;
dcb.fOutxCtsFlow=FALSE;
dcb.fOutxDsrFlow=FALSE;
dcb.fDtrControl=DTR_CONTROL_ENABLE;
dcb.fRtsControl=RTS_CONTROL_ENABLE;
dcb.fOutX=FALSE;
dcb.fInX=FALSE;
dcb.Parity=NOPARITY;
dcb.StopBits=ONESTOPBIT;
GetCommTimeouts(hComm,&CommTimeouts);
CommTimeouts.WriteTotalTimeoutMultiplier=10;
CommTimeouts.WriteTotalTimeoutConstant=100;
SetCommTimeouts(hComm,&CommTimeouts);
if(!SetCommState(hComm,&dcb))
{
MessageBox("出错");
}
else
MessageBox("正确");
SetupComm(hComm,1024,1024);
char buf[4]="123";
DWORD length;
COMSTAT comstat;
DWORD dwErrorFlags;
DWORD Error;
if(!ClearCommError(hComm,&dwErrorFlags,&comstat))
{
MessageBox("chuowu");
}
if(!WriteFile(hComm,buf,4,&length,0))
{
MessageBox("出错");
Error=GetLastError();
string.Format(_T("%x"),Error);
string.Format(_T("%x"),Error);
// string="nihao";
MessageBox(string);
}
if(!length)
{
MessageBox("没有数据发送");
}
MessageBox("结束");
CloseHandle(hComm); 展开
hComm=CreateFile("COM1",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,0);
if(hComm==INVALID_HANDLE_VALUE)
{
MessageBox("chucho");
return;
}
DCB dcb;
COMMTIMEOUTS CommTimeouts;
CString string;
dcb.DCBlength=sizeof(DCB);
GetCommState(hComm,&dcb);
dcb.BaudRate=9600;
dcb.ByteSize=8;
dcb.fBinary=TRUE;
dcb.fOutxCtsFlow=FALSE;
dcb.fOutxDsrFlow=FALSE;
dcb.fDtrControl=DTR_CONTROL_ENABLE;
dcb.fRtsControl=RTS_CONTROL_ENABLE;
dcb.fOutX=FALSE;
dcb.fInX=FALSE;
dcb.Parity=NOPARITY;
dcb.StopBits=ONESTOPBIT;
GetCommTimeouts(hComm,&CommTimeouts);
CommTimeouts.WriteTotalTimeoutMultiplier=10;
CommTimeouts.WriteTotalTimeoutConstant=100;
SetCommTimeouts(hComm,&CommTimeouts);
if(!SetCommState(hComm,&dcb))
{
MessageBox("出错");
}
else
MessageBox("正确");
SetupComm(hComm,1024,1024);
char buf[4]="123";
DWORD length;
COMSTAT comstat;
DWORD dwErrorFlags;
DWORD Error;
if(!ClearCommError(hComm,&dwErrorFlags,&comstat))
{
MessageBox("chuowu");
}
if(!WriteFile(hComm,buf,4,&length,0))
{
MessageBox("出错");
Error=GetLastError();
string.Format(_T("%x"),Error);
string.Format(_T("%x"),Error);
// string="nihao";
MessageBox(string);
}
if(!length)
{
MessageBox("没有数据发送");
}
MessageBox("结束");
CloseHandle(hComm); 展开
2012-06-12
展开全部
慢慢 调试 吧
推荐看书
Visual C++_Turbo C串口通信编程实践
推荐看书
Visual C++_Turbo C串口通信编程实践
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
我也遇到同样问题,用GetLastError()返回的是6
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
我遇到同样的问题,我用GetLastError()也是返回0,但是写入字节为0.请问你现在解决了吗?如果解决了可以告诉我怎么解决的?
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询