WriteFile()和ReadFile()异步不写或读

时间:2013-02-15 14:57:05

标签: c++ winapi serial-port

我正在尝试使用writefilereadfile函数通过串行端口连接发送和接收字符串。我必须异步执行此操作,因为要读取的字节数始终不同,readfile只会挂起或阻塞,直到获得正确的字节数。既然我正在尝试异步执行此操作,我的writefile函数将不会发送任何数据,并且我的readfile函数似乎被跳过,因为下一行开始执行它而没有任何字符被读取。不确定我的Overlapped结构或我的超时是否有问题。但是我现在卡住了。

超时

void Serial::OpenPortRead()
{
HANDLE sSerial =  CreateFile(L"COM3",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,0);
//Timeout Settings
COMMTIMEOUTS    CommTimeouts;   
GetCommTimeouts(sSerial, &CommTimeouts);
CommTimeouts.ReadIntervalTimeout            = 5000; 
    CommTimeouts.ReadTotalTimeoutMultiplier     = 2; 
    CommTimeouts.ReadTotalTimeoutConstant       = 10; 
    CommTimeouts.WriteTotalTimeoutMultiplier    = 50; 
    CommTimeouts.WriteTotalTimeoutConstant      = 500; 

//Port Settings
DCB dcbSerialParams = {0};
dcbSerialParams.DCBlength=sizeof(dcbSerialParams);
dcbSerialParams.BaudRate=CBR_19200;
dcbSerialParams.ByteSize=8;
dcbSerialParams.StopBits=ONESTOPBIT;
dcbSerialParams.Parity=NOPARITY;

SetCommState(sSerial,&dcbSerialParams);//Apply Settings to Handle




}

写文件功能

void Serial::WritePort(CString buffer)
{


DWORD bytes;//pointer to hold number of bytes written
USES_CONVERSION;
CW2A buf((LPCWSTR)buffer);//Convert unicode to ascii



OpenPortRead();
OVERLAPPED overlapped_structure;
memset(&overlapped_structure, 0, sizeof(overlapped_structure));
overlapped_structure.Offset = 0;
overlapped_structure.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

WriteFile(sSerial, buf,strlen(buf),&bytes,&overlapped_structure);//Send string


}

读取文件功能

int Serial::ReadPort(CString buf){

OpenPortRead();// Open Serial Communication for reading

const int buffer_size = 10;
 char buffer[10];//buffer to hold recieved string

memset (buffer, 0, buffer_size * sizeof (char));
int n, num,iTemp,i=0;
OVERLAPPED overlapped_structure;
memset(&overlapped_structure, 0, sizeof(overlapped_structure));
overlapped_structure.Offset = 0;
overlapped_structure.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

DWORD bytesRead;//pointer to number bytes read


ReadFile(sSerial,&buffer,buffer_size,&bytesRead,&overlapped_structure);// begin read



//Used this function because return would be filled with extra raw data characters
buffer[n] = StringLength(buffer, &n);//find length of string returned
num = n;

1 个答案:

答案 0 :(得分:2)

MSDN包含有关如何将重叠I / O与串行端口通信一起使用的详细信息:

Serial Communications