Search code examples
arduinoserial-portinterrupt

Handling serial input on Arduino with interrupts on a specific character


I'm working on an educational robotics project that should allow control of the robot over Bluetooth. The robot is an off-the-shelf robot with a serial interface that the Arduino is driving normally autonomously.

I'm trying to allow users to write a series of commands to the Bluetooth serial port (connected to hardware serial pins or software serial pins) while the automation is still running and when they send a new-line, the series of commands is sent to other parts of the robot.

I've used other microcontrollers and written a simple interrupt routine when a pin is pulled high or low, but I am not sure how to handle an interrupt on a character. I think that an interrupt is the best way to do this, but I haven't had much experience with Arduino, so there many be functionality I'm not aware off.

TL;DR: If I want the Arduino to execute code when a certain character arrives on a serial port, should I use an interrupt method?

I also want to add, as this is an educational project, I would like to stay fully on Arduino, several friends and colleagues have recommended alternate chips or MCUs that would have the functionality but I want to stay friendly to new programmers and engineers.


Solution

  • The built-in HardwareSerial does not have support for interrupt-driven handling of characters. Many sketches are OK with the typical polling approach:

    while (Serial.available()) {
      char c = Serial.read();
    
      // Code that watches for certain characters
      .
      .
      .
    }
    

    There's nothing about what you describe that requires interrupts, but you could use an extended version of HardwareSerial that I wrote (modified), called NeoHWSerial. It calls a function that you provide from the interrupt service routine (see documentation).