c++Builder串口接收数据问题
我用线程写了一个通过串口接收数据的程序,结果出现了问题:
连续发三个数据,如果两个数据之间的间隔为5毫秒以上,就没有问题,
但是如果连续发送,没有时间间隔,接到的好多数据都是乱码,是不是我的配置有些问题,读取缓冲区数据的参数设置不对?
请各位指教:
HANDLE __fastcall TComm::GetComHandle(void)
{
return m_Handle;
}
int __fastcall TComm::Open()
{
String szCom;
COMMTIMEOUTS to;
if(pReadThread)
{
SetCommMask(m_Handle,0);
pReadThread->Terminate();
delete pReadThread;
}
szCom.sprintf("COM%d",m_wComm);
if(m_Handle)
{
CloseHandle(m_Handle);
}
m_Handle = CreateFile(szCom.c_str(),GENERIC_READ|GENERIC_WRITE,
0,NULL,OPEN_EXISTING,
//NULL,
FILE_FLAG_OVERLAPPED, //是否异步执行操作
NULL);
if(m_Handle == INVALID_HANDLE_VALUE)
{
return -1;
}
memset((void *)&to,0,sizeof(COMMTIMEOUTS));
to.ReadTotalTimeoutMultiplier = 5;
to.ReadTotalTimeoutConstant = 1000;
SetCommTimeouts(m_Handle,&to);
if(m_pReadProc)
{
SetCommMask(m_Handle,EV_RXCHAR);
pReadThread = new TReadThread(m_Handle,m_OwnHandle,m_pReadProc,false);
}
return 1;
}
DWORD __fastcall TComm::GetErrorMessage(void)
{
LPVOID lpMsgBuf;
DWORD dwBufLen = 0;
dwBufLen = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
);
ZeroMemory(pErrBuf,BUFSIZE);
memcpy(pErrBuf,lpMsgBuf,dwBufLen);
LocalFree( lpMsgBuf );
return dwBufLen;
}
int __fastcall TComm::Close(void)
{
BOOL bReturn;
if(m_Handle)
{
bReturn = CloseHandle(m_Handle);
if(!bReturn)
{
return -1;
}
}
return 1;
}
int __fastcall TComm::DialogSetupComm(void)
{
COMMCONFIG ComConfig;
BOOL bReturn;
String szCom;
DCB dcb;
memset((void *)&dcb,0,sizeof(DCB));
GetCommState(m_Handle,&dcb);
szCom.sprintf("COM%d",m_wComm);
//显示系统配置窗口
/* bReturn = CommConfigDialog(szCom.c_str(),NULL,&ComConfig);
if(!bReturn) //没有配置
{
return -1;
} */
ComConfig.dcb.BaudRate = DWORD(9600);
ComConfig.dcb.fParity = DWORD(0); //DWORD fParity: 1; Enable parity checking
ComConfig.dcb.StopBits = BYTE(0); // BYTE StopBits; 0,1,2 = 1, 1.5, 2
ComConfig.dcb.ByteSize = BYTE(8); // BYTE ByteSize; Number of bits/byte, 4-8
dcb.BaudRate = ComConfig.dcb.BaudRate;
dcb.fParity = ComConfig.dcb.fParity;
dcb.StopBits = ComConfig.dcb.StopBits;
dcb.ByteSize = ComConfig.dcb.ByteSize;
//配置串口波特率等属性
bReturn = SetCommState(m_Handle,&dcb);
if(!bReturn)
{
return -1;
}
return(Open());
}
[解决办法]
楼主,你确定发送源发出的数据没有问题吗?
用串口助手接受一下,看是不是也是乱码
[解决办法]
接收完清除缓冲区了没有,还有就是发送的部分有没有问题??