C++ build 串口通信
void writeSerialPort(String data,DWORD time){
char *SendData;
DCB dcb;
char *ComNo;
String temp="COM1";
ComNo = temp.c_str();
HANDLE hComm=CreateFile(ComNo,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,0);
if(hComm == INVALID_HANDLE_VALUE){
MessageBox(0,"打开通信端口错误!","Comm Error",MB_OK);
return;
}
GetCommState(hComm,&dcb);
dcb.BaudRate = 1200;
dcb.ByteSize = 8;
//dcb.fParity = 1;
dcb.Parity = 2;
dcb.StopBits = 0;
if(!SetCommState(hComm,&dcb)){
MessageBox(0,"通信端口设置错误!","Set Error",MB_OK);
CloseHandle(hComm);
return;
}
unsigned long lrc,BS;
SendData = data.c_str();
BS = data.Length();
WriteFile(hComm,SendData,BS,&lrc,NULL);
Sleep(time);
DWORD nBytesRead,dwEvent,dwError;
COMSTAT cs;
ClearCommError(hComm,&dwError,&cs);
if(cs.cbInQue>sizeof(inbuff)){
PurgeComm(hComm,PURGE_RXCLEAR);
return;
}
ReadFile(hComm,inbuff,cs.cbInQue,&nBytesRead,NULL);
inbuff[cs.cbInQue]='\0';
CloseHandle(hComm);
}
我想和一个设备通信,但是设备就是接受不了,但是用JAVA可以,串口设置应该没有错!
[解决办法]
very good i like
[解决办法]
调试跟踪,着重看下dcb和hComm的值
[解决办法]
用个串口调试软件,看看你发了些什么东西,既然用其他得可以就是你写得代码有问题
[解决办法]
接个自环头自己发自己收跟踪看看
[解决办法]
char *chrTemp = new char[ FDeviceName.Length() + 8 ];
strcpy( chrTemp , ("\\\\.\"+FDeviceName).c_str());
//end
if ((FHandle = CreateFile(chrTemp,
GENERIC_READ
[解决办法]
GENERIC_WRITE, 0, NULL,OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL
[解决办法]
FILE_FLAG_OVERLAPPED, NULL))==(HANDLE)-1)
FConnected = false ;
else
{
FConnected = true ;
if (GetFileType(FHandle) != FILE_TYPE_CHAR)
{
DestroyHandle();
} else SetCommMask(FHandle, 511);
}
这是我在用的代码,应该是strcpy( chrTemp , ("\\\\.\"+FDeviceName).c_str());
[解决办法]
如果有需要的话可以Mail我,给你我写的类
[解决办法]
是不是COM port坏了?
[解决办法]
貌似有点问题