have a recurring event every x seconds

Hi,

I'm building an Arduino Mega based tennis ball machine, and I want to control the ball rate frequency using a programming logic like this:

  • every 3 seconds -- if the ball is ready and if the motors are running then ---- shoot the ball

the Arduino program is already doing other things, like listening for incoming serial data from the tbm remote control, setting pins high or low, sending serial data out, etc.: what would be the best way to include a recurring event like the one shown above inside my code ?

thanks and best regards,

andrea

what would be the best way to include a recurring event like the one shown above inside my code ?

In the same way as the 'blink without delay' example works. Implement a finite state machine. Google is your friend.

Grumpy_Mike:

what would be the best way to include a recurring event like the one shown above inside my code ?

In the same way as the 'blink without delay' example works. Implement a finite state machine. Google is your friend.

Thanks, you too. :)

this should get you started..

unsigned long balls = 0;
unsigned long lastBall = 0;

void setup()
{
  Serial.begin(115200);
}

void loop()
{
  if ( millis() - lastBall > 3000)
  {
    if (ballReady() && motorsRunning())
    {
       lastBall = millis();   
       shootBall();
       balls++;
       Serial.print("time : ");
       Serial.print(lastBall );
       Serial.print("\t\t balls : ");
       Serial.print(balls);
       Serial.print("\t\t average: ");
       Serial.print(lastBall/balls);
    }
  }

  // other code can be here
} 

bool ballReady()
{
  return true; // need improvement
}

bool motorsRunning()
{
  return true;  // need improvement
}

void shootBall()
{
  Serial.print("shoot !"); // need improvement
}

awesome, thanks to you too. I was worried I needed to have to deal with interrups and maybe rearrange my actual code, which has grown quite long now and cumbersome to mess with.

Maybe you want to approach it like this http://arduino.cc/playground/Code/EventFuse or like that http://arduino.cc/playground/Main/MsTimer2 or that http://arduino.cc/playground/Main/FlexiTimer2