11 years, 7 months ago.

Skip getchar() if no input? using interrupts?

Hi i'm completely stuck now i've tryed some ways of doing this but have yet to get a solution.

In short i would like to read a value from a sensor display the value and keep doing this until a user presses 'e' to exit the loop and go back to a menu.

So i'm trying to display an anaglo input using printf() but at the same time i want to be able to exit this loop using a character input, in this case e. Which i'm trying to do using c = getchat();. However as soon as the program reaches c = getchar(); it stops and waits for a users input. I want the program to look for character but if no character is entered then carry on with the loop.

I was thinking of using an interrupt like timeout or ticker but not sure how to use them. Below is my code in question.

Repository: getchar_timeout

If i'm not stating what my question is clearly i'm looking for a way to skip past c = getchar; if there is NO user input. i.e. a timeout so that if say 100mS passes and no character has been entered then carry on with the while loop.

1 Answer

11 years, 7 months ago.

I would use a real Serial object, and then use the readable function. So define:

Serial pc(USBTX,USBRX);

Then in your code you can do:

if (pc.readable()) {
  c = pc.getc();  //Same as getchar();
  //Your if statements
}

There are also other nice options with generating an interrupt when a new char arrives, but this is probably the easiest.

Edit: Looks like I was too late ;)