My program simply does nothing in loop. I set an interrupt for serial port (USART). When data comes, yes, it works and toggles the LED. But it just does it once. Once it got into the interrupt it doesn't come back to where it left off.
My code is here.
#include <avr/interrupt.h> #include <avr/io.h>
volatile int state_Led = LOW;
void setup()
{
pinMode(8, OUTPUT);
UBRR0H = 0; // Load upper 8-bits of the baud rate value into the high byte of the UBRR register
UBRR0L = 8; // Load lower 8-bits of the baud rate value into the low byte of the UBRR register
UCSR0B |= (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0); // Turn on the transmission, reception, and Receive interrupt
interrupts();
}
void loop()
{
digitalWrite(8, state_Led);
}
ISR(USART_RX_vect)
{
state_Led = !state_Led;
}
Can anyone please help me to understand what's wrong with my code and what's going on with it?
Because you don't handle the interrupt. You cannot overwrite the serial interrupt and think that the Arduino core code still does the serial handling for you. You did not read the hardware register of the UART to clear the interrupt cause.
Can you use the normal Arduino functions ?
At least you can start with those.
Why do you need the interrupt when something is received ?
The Arduino Serial library uses interrupts and a buffer. Is that a problem ?
Do you know the serialEvent ?
If you want to rewrite the Arduino Serial library all over, you could at least use working code. You will find uart code at http://www.avrfreaks.net/ in the 'Projects' section. You have to log in to see it.
@Caltoa,
You do realise that serialEvent is not an "event" in the sense of a interrupt?
@OP, I'm not sure I know all the details of how to do what you want, but I am like you, in possession of the source code that most certainly does know how to correctly handle serial interrupts.
Thank you AWOL,
I'm looking at the code, and I see now that the serialEvent is executed at the end of every loop(), that is in the background so to speak. I didn't know that.
It's all just a question of scale; a real event/interrupt gets checked every instruction cycle (which may be as fast as 62.5ns, but may sometimes be a little slower), serialEvent gets checked every "loop()" cycle, which may be orders of magnitude times slower (and may not ever happen, if something in "loop()" blocks.
Looking at it another way, "orders of magnitude slower" may be perfectly adequate, if, for instance, humans are involved in the interaction.
Maybe, if you tell us what you want to achieve. I cannot guess from the minimal sketch you posted. Do you really need an interrupt from the serial hardware? Are you sure you cannot structure you sketch to live with the serialEvent() feature the standard Arduino environment offers?