Intermittent memory exception error with COM communication
This code is for Windows 7. I am trying to grab the response to an AT command and print just the part of the string I need. Visual Studio Express is randomly telling me I have memory exceptions with this code. It doesn't happen every time.
#include <Windows.h>
#include <iostream>
#include <string>
int main()
{
HANDLE hSerial = CreateFile("CO开发者_Go百科M3",GENERIC_READ | GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
if(hSerial==INVALID_HANDLE_VALUE)
std::cout << "Insert error message";
DCB dcbSerialParams = {0};
dcbSerialParams.DCBlength=sizeof(dcbSerialParams);
if (!GetCommState(hSerial, &dcbSerialParams))
std::cout << "Insert error message";
dcbSerialParams.BaudRate=CBR_9600;
dcbSerialParams.ByteSize=8;
dcbSerialParams.StopBits=ONESTOPBIT;
dcbSerialParams.Parity=NOPARITY;
if (!SetCommState(hSerial,&dcbSerialParams))
std::cout << "Insert error message";
COMMTIMEOUTS timeouts={0};
timeouts.ReadIntervalTimeout=50;
timeouts.ReadTotalTimeoutConstant=50;
timeouts.ReadTotalTimeoutMultiplier=10;
timeouts.WriteTotalTimeoutConstant=50;
timeouts.WriteTotalTimeoutMultiplier=10;
if(!SetCommTimeouts(hSerial, &timeouts))
std::cout << "Insert error message";
while(1)
{
char szBuff[50+1] = {0};
char wzBuff[14] = {"AT+CSQ\r"};
DWORD dZBytesRead = 0;
DWORD dwBytesRead = 0;
if(!WriteFile(hSerial, wzBuff, 7, &dZBytesRead, NULL))
std::cout << "Write error";
if(!ReadFile(hSerial, szBuff, 50, &dwBytesRead, NULL))
std::cout << "Read Error";
std:: cout << szBuff;
std::string test = std::string(szBuff).substr(8,10);
std::cout << test;
Sleep(500);
}
return 0;
}
The built-in iterator debugging is going to complain about your substr() call. You are making some wrong assumptions:
- ReadFile() will only return what's available in the serial port receive buffer. Serial ports are slow, you typically only get one or two characters. You cannot ignore dwBytesRead.
- A serial port doesn't return C strings, it returns bytes. You won't get the zero terminator. Use dwBytesRead again to append the zero yourself.
Keep calling ReadFile() until you've received the full response. Typically terminated by a line feed character. Then process the response.
精彩评论