-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmillis_count_down.ino
85 lines (72 loc) · 2.25 KB
/
millis_count_down.ino
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// ---------------------------------------------
// millis_count_down.ino
// ---------------------------------------------
// License: The Unlicense, Public Domain.
// Author: Koepel
// 2019 january 23
// ---------------------------------------------
//
// millis() demo for a count down timer.
//
// A button is connected to pin 2 and GND.
// The count down starts as soon as the button
// is pressed.
//
const int buttonPin = 2;
const long startCount = 5000; // start countdown with 5 seconds
unsigned long previousMillisCounter;
bool counting = false;
// An extra timer with millis is used to show the count down time.
// For a LCD display, the interval can be 200 ms.
// For the serial monitor, the interval can also be 200 ms.
// For a 7-segment display, the update can be done
// at full speed without the use of millis().
unsigned long previousMillisUpdate;
const unsigned long intervalUpdate = 200;
void setup()
{
pinMode( buttonPin, INPUT_PULLUP);
Serial.begin( 9600);
Serial.println( "Press the button");
}
void loop()
{
unsigned long currentMillis = millis();
if( !counting)
{
// As soon as the button is pressed, the counter is
// made active and the value of millis() is remembered.
if( digitalRead( buttonPin) == LOW)
{
previousMillisCounter = currentMillis;
counting = true;
}
}
else
{
// To prevent a rollover problem, the time that has passed
// since the start is calculated with unsigned long.
// After that the down-counter value is calculated with long,
// because it might have passed the end time and became negative.
unsigned long countUpValue = currentMillis - previousMillisCounter; // must be unsigned long !
long countDownValue = startCount - long( countUpValue); // must be long !
// Check if the end time is reached
if( countDownValue <= 0)
{
countDownValue = 0;
// Also print the value of 0 to the output
Serial.println( countDownValue);
Serial.println( "Press the button");
counting = false;
}
else
{
// Update the output.
if( currentMillis - previousMillisUpdate >= intervalUpdate)
{
previousMillisUpdate = currentMillis;
Serial.println( countDownValue);
}
}
}
}