开发者

program hangs when using windows 32bit serial communications

开发者 https://www.devze.com 2023-02-06 05:40 出处:网络
written below is a crude code i wrote for accessing a serial port. attached to that port is a microcontroller that sends me data and having a baud rate of 57600. i ran the code once and got results bu

written below is a crude code i wrote for accessing a serial port. attached to that port is a microcontroller that sends me data and having a baud rate of 57600. i ran the code once and got results but after closing the window, my comp开发者_如何学Cuter hanged. i pressed ctrl+alt+del and saw that under processes my program was still running. i cant close it too.

int n = 20;
char szBuff[20 + 1] = {0};

HANDLE hSerial;
DCB dcbSerialParams = {0};
COMMTIMEOUTS timeouts={0};
DWORD dwBytesRead = 20;

dcbSerialParams.DCBlength=sizeof(DCB);

hSerial = CreateFile("COM5",
                 GENERIC_READ | GENERIC_WRITE,
                 0,
                 0,
                 OPEN_EXISTING,
                 FILE_ATTRIBUTE_NORMAL,
                 0);


if(hSerial==INVALID_HANDLE_VALUE)
{
  if(GetLastError()==ERROR_FILE_NOT_FOUND)
  {
    puts ("cannot open port!");
  }

  puts ("invalid handle value!");                                 
}

if (!GetCommState(hSerial, &dcbSerialParams)) 
{
  puts ("error getting state");
}

dcbSerialParams.BaudRate=CBR_57600;
dcbSerialParams.ByteSize=8;
dcbSerialParams.StopBits=ONESTOPBIT;
dcbSerialParams.Parity=NOPARITY;

if(!SetCommState(hSerial, &dcbSerialParams))
{
  puts ("error setting port state");
}


while (1)
{

  if(!ReadFile(hSerial, szBuff, n, &dwBytesRead, NULL)){
     puts ("serial read error fail!");
  } 

  else
  {
     printf ("%s\n" , szBuff);
  }

}


That sounds like a buggy serial port driver. See Why do some process stay in Task Manager after they've been killed?. When you kill your program, it doesn't go away until all of its pending I/O operations have been canceled.


You MUST to define some type of stop to the app if it will loop in a while(1).

Option 1: The microcontroller must send a terminate command or character that you use to break the while.

Option 2: Some type of timeout instead while(1).

Option 3: Catch some signal and then break the while().

And there are a lot of other options.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号