How to run a periodic action until a key is pressed

54 views Asked by At

I'm writing a test script for an embedded controller and some of the tests require a user action before you can progress.

I print an instruction on the screen such as

printf("Turn switch A to ON position then press any key");

I then want the script to wait until the user presses a key to progress to the test

ExpectedSwitchState = ON;
CheckSwitch(01);

I could do this fairly easily with (albeit requiring enter to be pressed)

printf("\nPress Enter to continue");
getChar();

The problem I have is that I have to ensure my tool sends a tester present message every 4 seconds, if no other commands are being transmitted. And I want it to resume as soon as a key is pressed, not wait another 4 seconds.

I'm more used to embedded C than anything using computer inputs so am not sure if there are common commands to achieve what I want.

Any advice would be appreciated.

At present I have only found ways to pause the program. Not a way to continue doing something until a key is pressed.

I could create a while loop which increments a counter every 1ms and then transmits tester present whenever the counter gets to 4,000. And exit the while loop if a key is pressed. Seems a little convoluted. And I don't know the commands to detect a key is pressed.

1

There are 1 answers

1
Shaf On

I believe I have found a solution

void UserPause(void)
{
  printf("Press any key to continue\n");  // Print message to user
  while (!_kbhit())  // Loop while the keyboard is not hit
  {

    if (b_TesterPresentEnabled == 1)  
    // Only do tester present if functionality is enabled
    {
        TestTXMsg[0] = 0x3e;  // Set up the message bytes
        TestTXMsg[1] = 0x00;
        TxMsgLen = 2;  // Define the message length
        MsgTest();  // Function to send the message to the ECU
        Sleep(4000);
    }
  }
}