Is it possible to use Serial.available() or Serial.read() inside an ISR?
I have an ISR running with a timer interrupt. When a certain condition is met, I want the program to halt until a key is pressed.
I can halt the program with a while(digital.read()==0) loop using a hardware button, but I want to wait for a serial input (a key pressed on the keyboard).
My attempt with while(Serial.available()==0) doesn't work inside an ISR; however, works fine in the loop() or setup(). Why?
My initial guess is that the interrupt priority for Serial functions is low but I am not sure. Can someone tell me what it is?
You won't be able to receive any data during an ISR and the data already in the Serial input buffer isn't going to disappear so there is no need for an ISR to get it.
I think you have the wrong concept for achieving whatever you are trying to do. If you describe the project we can probably give more useful advice.
For example if you are content to wait for something to happen at human speeds you probably don't need an interrupt.
Maybe Have a look at the examples in Serial Input Basics - simple reliable ways to receive data.
Thanks for the answers. So I shouldn't try to read serial data in an ISR.
What I am currently doing is that I setup a flag in the ISR and then execute the code based on that flag, in the main loop. This works fine but introduces an additional comparison (if) instruction in the main loop, which is only true rarely. So if I could move the halt condition to the ISR, I could eliminate this if condition making the loop execute much faster. That's what I had in mind.
If the interrupt is caused by Data Ready on the UART (serial port input), then of course you can use a dedicated ISR to read the character and store it somewhere safe.
If the controller doesn't have to do anything else (is idle), it will enjoy every if-statement that breaks the drabness of endless calls to and returns from loop()
If you claim that the omission of a single if-statement will make loop() execute much faster, this implies that loop() is otherwise empty. If not, you'll notice almost no difference from adding or removing such a single statement.
Why do you think that faster execution of loop() will make anything work better? When loop() executes many thousand (up to 200,000) times every second, what will change if it is called one time more or less frequently?
It's wise to have an eye on performance, no doubt, but such considerations can be delayed until you design a more complex program, where bad coding practices or algorithms may overload the controller. But even then a cure will not consist in the removal of a single statement, instead the true bottlenecks must be identified and eliminated by an appropriate redesign of the program structure.