上位機(jī)和下位機(jī)通信的問題,使用的協(xié)議rs485協(xié)議.
題目是用VC++讓上位機(jī)和下位機(jī)進(jìn)行通信.
接在電腦上的rs232口,使用了232和485的轉(zhuǎn)換器,發(fā)送相應(yīng)的數(shù)據(jù)格式,然后上位機(jī)接受相應(yīng)的格式。
原代碼如下:
// TODO: Add your control notification handler code here
char buff[200];
CString str;
GetDlgItem(IDC_EDI_BUF) -> GetWindowText(str);
sprintf(buff,"%s",(LPCSTR)str);
//MessageBox(buff);
//然后打開串口,開始通信
HANDLE hCom; //createFile函數(shù)返回的句柄
//打開的是端口一
hCom = CreateFile("COM1",GENERIC_READ|GENERIC_WRITE,
0, NULL,OPEN_EXISTING, 0, NULL);
if(hCom == NULL)
{
MessageBox("打開端口一時(shí)出現(xiàn)了錯(cuò)誤");
}
//設(shè)置讀寫緩沖區(qū)的緩沖大小
//改變端口的設(shè)備控制塊
/*DCB dcb;
GetCommState(hCom,&dcb);
dcb.BaudRate = CBR_9600;
dcb.ByteSize=8;//數(shù)據(jù)位8位
dcb.Parity = NOPARITY; //有校驗(yàn)
dcb.StopBits=ONESTOPBIT; //一個(gè)停止位
if(false==SetCommState(hCom,&dcb))
{
MessageBox("配置端口時(shí)出現(xiàn)了錯(cuò)誤");
}*/
DCB dcb;
GetCommState(hCom,&dcb);
dcb.BaudRate = CBR_9600;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
dcb.fBinary = TRUE;
dcb.fParity = TRUE;
dcb.fOutxDsrFlow = false;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcb.fOutxCtsFlow = false;
//#ifdef LPR_DOHERELARGE
// dcb.fRtsControl = RTS_CONTROL_ENABLE;
//#else
dcb.fRtsControl = RTS_CONTROL_DISABLE;
//#endif
/* dcb.fInX = false;
dcb.fOutX = false;
dcb.XonChar = ASCII_XON;
dcb.XoffChar = ASCII_XOFF;
dcb.XonLim = 100;
dcb.XoffLim = 100;*/
if(false==SetCommState(hCom,&dcb))
{
MessageBox("配置端口時(shí)出現(xiàn)了錯(cuò)誤");
}
//設(shè)置讀寫操作,將緩沖里面的數(shù)據(jù)寫入到串口里面
BOOL isWrite = false;
DWORD length = 100;
COMSTAT ComStat;
DWORD dwErrorFlags;
ClearCommError(hCom,&dwErrorFlags,&ComStat);
isWrite = WriteFile(hCom,buff,length,&length,NULL);
if(isWrite == false)
{
MessageBox("寫入數(shù)據(jù)時(shí)出現(xiàn)了錯(cuò)誤");
}
//寫完數(shù)據(jù)然后從緩沖里面讀取數(shù)據(jù)
//過一段時(shí)間才讀取緩沖里面的數(shù)據(jù)
::Sleep(100);
//讀取緩沖里面的數(shù)據(jù)
BOOL isRead = false;
char readbuf[100];
DWORD bReadStatus;
memset(readbuf,0,sizeof(readbuf));
isRead = ::ReadFile(hCom,readbuf,100,&bReadStatus,NULL);
//MessageBox(readbuf);
GetDlgItem(IDC_RECV_BUFF) -> SetWindowText(readbuf);
CloseHandle(hCom);
這樣就完成了一次通信。還有從下位機(jī)發(fā)送來的報(bào)文解析部分沒有給出。那部分是純的軟件部分。和機(jī)器無關(guān)。
來源:SKT5次