Multitasking arduino with CAN bus inputs

So, you already figured out where your issues come from. Now you need to rethink how your code is written. Currently you are only doing one thing at a time. Your Arduino can do many thinks at the same time. To achieve this, you must follow a few rules until you know when you may break them.

  • do not use delay
  • make sure your loop runs as often as possible
  • for complex task do little steps and move on, do not wait for things to happen
  • start separating your code in loop() into functions and tasks

For this to work, you will need to keep track of the state your task is in. You can use global variables or static local variable for this. I like to use switch-case statements for simple state machines.

This will make your code look more complicated but it will allow you to extend your code with new functions without breaking what you have already done.

Here is the basic structure of a switch-case state machine.

void task()
{
static int state = 0; // This is only set to 0 the very first time when the function is called

  switch (state )
  {
    case 0:
      // do something only once
      state++;
      break;
    case 1:
      // do something until if condition is true
      if (...)
      {
        state++;
      }
      break;
    case 2:
      // do something until if condition is true, the start from beginning
      if (...)
      {
        state = 0;
      }
      break;
    default:
      state = 0;
      break;
  }
}

You can have as many of these as you want. Use the millis() technique inside a state/case to control timing before moving on to the next state.

You can use enums to give your states names and make the code easier to read.

Try turning your two LEDs into two tasks. If you have any question post your new code.