11 years, 5 months ago.

Find solution for program hang using putc

I'm communicating the a energy meter MODBUS with the mbed micro-controller. I use getc to extract a serials of response character from the energy meter but there is one problem with this method. If the energy meter stop sending characters halfway through, the micro controller will keep waiting forever for any character to be receive.

Is there anyway to write a program whereby i can set a limited time for the program to wait for any character before abandoning the process?

for (int count = 0; count < 7 ; count++) {    // For example, device will reply 7 character in MODBUS slave response format
    response[count] = device.getc();
    wait_ms(1);
}

1 Answer

11 years, 5 months ago.

You meant getc in the title?

There are several options I can think of, but readable() is probably the best one, something like:

Timer timer;
int response = -1;

timer.reset();   //Not really needed if it is like this
timer.start();

while( timer.read() < TIME_OUT ) {            //Keep checking as long as we aren't at TIME_OUT yet
  if (device.readable())                                 //If a new char is available get it
    response = device.getc();
}

//Check is response = -1 or what you expected:
if (response == -1)
  printf("Time Out!\n");