Arduino Programming – Interval
http://www.vimeo.com/8179793
How to write a program that fires actions with different intervals without using the delay() function. Configuration of the serial port and printing values is also explained.
Level : beginner with Arduino. ( Basic knowledge of programming principles like if/else and variables ).
Download the Arduino ( .pde ) files : arduino_tutorial_interval.zip
Interval_basic.pde :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 /*
Print serial text with an interval.
Basic example.
created 01-12-2009 by kasperkamperman.com
*/
unsigned long previousMillis = 0;
unsigned long currentMillis = 0;
int interval = 1000;
void setup() {
// opens serial port, sets data rate to 57600 bits per second
Serial.begin(57600);
}
void loop()
{ // save number of milliseconds since the program started
currentMillis = millis();
// check to see if the interval time is passed.
if (currentMillis - previousMillis >= interval == true ) {
Serial.print("this program runs now for : ");
Serial.print(currentMillis);
Serial.println(" milliseconds");
// save the time when we displayed the string for the last time
previousMillis = currentMillis;
}
}
Interval_for_loop.pde :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39 /*
Print serial text with different intervals.
Check the array with a for-loop.
created 01-12-2009 by kasperkamperman.com
*/
const int amountOfIntervals = 3;
unsigned long previousMillis[amountOfIntervals] = {0, 0, 0};
unsigned long currentMillis = 0;
int intervals[amountOfIntervals] = {1000, 2500, 5000};
void setup() {
// opens serial port, sets data rate to 57600 bits per second
Serial.begin(57600);
}
void loop()
{ // save number of milliseconds since the program started
currentMillis = millis();
// check the 3 intervals one by one with a for-loop.
for(int i=0; i<amountOfIntervals; i++) {
// check to see if the interval time is passed.
if (currentMillis - previousMillis[i] >= intervals[i]) {
if(i==0) Serial.println("- every 1 second");
if(i==1) Serial.println(" - every 2.5 second");
if(i==2) Serial.println(" - every 5 seconds");
// save the time when we displayed the string for the last time
previousMillis[i] = currentMillis;
}
}
}
Art&Technology related bookmarks