// CDetectDlg 主 类 名,
//打开串口
HANDLE CDetectDlg::KSrialOpen()}
void CDetectDlg::FCS(CString &str) // 这个函数是用来把数据校验的
{
CString o, oo, ff, fcs, ol;
int b, l, i;
char o2;
o = str;
b = 0;
l = o.GetLength();
for (i = 0; i
o2 = o.GetAt(i);
b = b^o2;
}
ff.Format("%X", b);
if (ff.GetLength() == 1) ff = '0' + ff;
fcs = ff + "*";
oo = o + fcs;
str = oo + "\r";
}
char* CDetectDlg::pack_data() // 发送一个特定的数据 先测试一下 是否能够发送完成 并且返回数据
{
m_send_str = "@00RD00020002";//@00SC02 @00KSCIO 001000
FCS(m_send_str);
TRACE("---pack_data():%s ---\n", m_send_str);
return m_send_str.GetBuffer(0);
}
//读串口信息
int CDetectDlg::ReadData()
{
char readBuffer[1024];
DWORD wCount = 1024;//读取的字节数
BOOL bReadStat;
bReadStat = ReadFile(hCom, readBuffer, wCount, &wCount, NULL);
if (!bReadStat)
{
TRACE("---ReadFile error :%d ---\n", GetLastError());//得到返回的错误值
AfxMessageBox("读串口失败!");
CloseHandle(hCom);
return -1;
}
if (readBuffer[5] == '0' && readBuffer[6] == '0')
{
OnOutputMessage("成功得到PLC返回数据");
}
PurgeComm(hCom, PURGE_TXCLEAR | PURGE_RXCLEAR | PURGE_TXABORT | PURGE_RXABORT);
return 0;
}
//写串口信息
int CDetectDlg::WriteData(HANDLE handle, char *buffer)//send_data
{
unsigned long dwBytesWrite;
DWORD dwErrorFlags;
BOOL bWriteStat;
if (0 == ClearCommError(handle, &dwErrorFlags, &ComStat) )
{
AfxMessageBox("该函数ClearCommError调用失败!");
}
dwBytesWrite = strlen(buffer);
TRACE("---strlen(buffer) :%ld ---\n", dwBytesWrite);//得到返值
bWriteStat = WriteFile(handle, buffer, dwBytesWrite, &dwBytesWrite, NULL);
if (!bWriteStat)
{
TRACE("---WriteFile error :%d---\n", GetLastError());//得到返回的值
AfxMessageBox("写串口信息失败!");
return -1;
}
return 0;
}
int CDetectDlg::all_call()
{
WriteData(hCom, pack_data());
ReadData();
return 0;
}
为了确保C++ 程序能够与PLC串口通讯上,在模式上是这样的,发一个数据,(是往串口写数据),确保PLC接到数据,还要读一下串口(即串口返回的 数据,确保PLC端有应答)