Skip to content

Instantly share code, notes, and snippets.

@nataliefreed
Created October 3, 2013 22:11
Show Gist options
  • Save nataliefreed/6817921 to your computer and use it in GitHub Desktop.
Save nataliefreed/6817921 to your computer and use it in GitHub Desktop.
Example of using millis() function to time multiple events happening at different rates.
/*
Natalie Freed, 10-3-2013
Example of using millis() function to time multiple events happening at different rates.
For LWHS Building and Programming Intelligent Machines Fall 2013.
To use, open Serial Monitor to view output.
*/
long timer1 = 0; //a long is a "long integer," can hold a larger range
// than integers but takes up more space. Required for millis() function
long timer2 = 0;
long timer3 = 0;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
void setup()
{
//start serial port
Serial.begin(9600);
}
void loop()
{
Serial.print("Counter 1 is increasing very quickly: ");
Serial.println(counter1);
Serial.print("Counter 2 is increasing at a medium rate: ");
Serial.println(counter2);
Serial.print("Counter 3 is increasing slowly: ");
Serial.println(counter3);
Serial.println(); //print a blank line to make it easier to read
//the millis() function returns time (in milliseconds) elapsed since the program started
if(millis() - timer1 > 200) //time elapsed = current time minus last time it was printed
{
counter1++; //increase counter1 by 1;
timer1 = millis(); //set timer representing last time printed to current time
}
if(millis() - timer2 > 1000) //time elapsed = current time minus last time it was printed
{
counter2++; //increase counter2 by 1;
timer2 = millis();
}
if(millis() - timer3 > 3000) //time elapsed = current time minus last time it was printed
{
counter3++; //increase counter2 by 1;
timer3 = millis(); //set timer representing last time printed to current time
}
delay(200); //make sure we're not printing too fast and overloading the serial port
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment