SlashDevin / NeoSWSerial

Efficient alternative to SoftwareSerial with attachInterrupt for RX chars, simultaneous RX & TX
169 stars 42 forks source link

Not able to read characters in attachInterrupt #12

Closed arjun289 closed 7 years ago

arjun289 commented 7 years ago

Is there a way to perform read inside the attachInterrupt function?

SlashDevin commented 7 years ago

No, because the character is passed in as the first argument. Just use that char:

    static void handleRxChar( uint8_t c )
    {
      // do something with 'c' now
      if (c == '\n')
        newlines++;
    }

You should never stay inside an interrupt routine, because it blocks everything else. You can't receive/send/print anything or stay in a while loop, because other interrupts won't be serviced (e.g., for Serial, and millis()). Be quick about it!

That's the whole purpose of attachInterrupt... being quick. But you have to "play nice" and exit the interrupt routine very quickly.

The typical use for attachInterrupt is to feed one character at a time to a Finite-State Machine. If you tell me more about your application, I could point you to some similar projects (and FSM code).

Most beginners want to save a bunch of characters and then process them all at once. If that's what you want to do, then don't use attachInterrupt.