Arduino Serial communication with interrupt10 Sep 2014
The other day, I helped Joe with his project. The project requires the Arduino to listen to the Bluetooth communication (sent via an Android App) while also running its own program. The Bluetooth module uses the serial comm. To make it work, I’ll use this basic code for the interrupt which when triggered, it takes the Bluetooth communication’s input.
// To use this example, you have to connect Rx pin (digital pin 0) to interrupt 0 pin (digital pin 2).
// Using interrupt 0 on digital pin 2.
attachInterrupt(0, serialInterrupt, CHANGE);
// Used to signal that main loop is alive.
// Used to signal that Serial input was read.
// Do something using even delays. There is an interrupt for that (Serial I/O)!
// Blink led to signal loop is alive.
// Volatile, since it is modified in an ISR.
volatile boolean inService = false;
// Trick: since Serial I/O in interrupt driven, we must reenable interrupts while in this Interrupt Service Routine.
// But doing so will cause the routine to be called nestedly, causing problems.
// So we mark we are already in service.
// Already in service? Do nothing.
if (inService) return;
// You was not in service. Now you are.
inService = true;
// Reenable interrupts, to allow Serial to work. We do this only if inService is false.
// Allow serial to read at least one byte.
// Blink led to signal Serial data arrived.
byte data = Serial.read();
// Echo data back to developer ;-)
// Job done.
inService = false;