non blocking tasks

Status
Not open for further replies.

imagiko

New member
Hello,

I want to run some gpio functions (raise a bunch of lines for time t) when I receive commands over serial, but when I perform these gpio tasks, I want to still be able to read serial data if available. Right now I have a delay function to raise the gpio line for the desired time and in that time any serial data is just stored in the buffer(or possibly lost) and only acted upon once im out of the delay function. How would I be able to achieve this in the teensy arduino/c framework.
 
In general:
Instead of using delay(), in your loop() you could routinely check for elapsed milliseconds (using special Teensy var type "elapsedMillis" https://www.pjrc.com/teensy/td_timing_elaspedMillis.html or the stock millis()) since you raised the pins; if elapsed time > t, lower the pins.
When new data arrives from the serial port, SerialEvent() is triggered (a bit like an interrupt handler).

Teensy specific:
Teensy software is quite smart; the delay() function, which usually is to be avoided because wastes CPU cycles in NOPs, here calls the special internal function yield(), which in turn checks for new data from serial ports and triggers SerialEvent() in case.
So using delay() is not as bad as with other Arduino-like boards. That said, best practice is to avoid delay() and check elapsed time.

By the way: on Teensy, it's a good idea to call digitalWriteFast() instead of digitalWrite() to toggle GPIO pins.
 
You can use TeensyDelay for that kind of tasks. Basically you could do the following:

  1. Set the pins or whatever you need to do
  2. Trigger one of the 8 delay channel with the required "reset" time
  3. In the callback of the delay channel reset your pins or do whatever you need to do.

Here a very simple example demonstrating that with the built in LED: https://github.com/luni64/TeensyDelay#basic-example
 
Status
Not open for further replies.
Back
Top