Hi guys, I am new here.
I would just like to ask a question if possible. I used the TimerOne library to create a timer that starts at 0 minutes and 0 seconds, and then goes up by 1 second like any normal timer. For my project, I need to reduce a variable by 1 every x seconds after a certain point, so for example at 0:10 a variable needs to be reduce by -1 every 5 seconds and cannot go below 0. I am totally unsure how to code this, any guidance would be much appreciated.
#include <TimerOne.h>
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
int Seconds = -2;
int Minutes = 0;
void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
Timer1.initialize(1000000);
Timer1.attachInterrupt(timer);
}
void timer(){
Seconds++;
}
void loop() {
if(Seconds==60) {
lcd.clear();
Minutes++;
Seconds=0;
}
lcd.setCursor(6,1);
lcd.print(Seconds);
lcd.setCursor(5,1);
lcd.print(":");
lcd.setCursor(4,1);
lcd.print(Minutes);
lcd.setCursor(0,1);
lcd.print("Age");
This is what I have so far for the timer. Any help is much appreciated, thank you in advance.
Where ever in your code the 1 second has elapsed, decrement your variable. If the value is -1, set it back to whatever original value you want it to be.
ieee488:
Where ever in your code the 1 second has elapsed, decrement your variable. If the value is -1, set it back to whatever original value you want it to be.
Hi, thank you for the feedback. I don't really know how to implement that, could you possibly give me an example please?
You can use -- to decrement (count down) just as you can use ++ to increment (count up).
Seconds-- ;
Or,
Seconds = Seconds -1 ;
Then use an [u]if-statement[/u] to stop when you get down to zero.
I am totally unsure how to code this, any guidance would be much appreciated.
I suggest you start with a down-counter that simply counts and displays the results. Then you can add the if-statement. Then add the timing. Then add the code to take care of the minutes and seconds, etc. ...Just work on one little thing at a time and "develop" your program. Don't try to write the whole program at once.
The most common way to make a counter that stops at a certain count is to use a [u]for-loop[/u], but the timing makes it a bit more complicated.
static unsigned lastSeconds = 0;
if (Seconds > lastSeconds )
{ // Time has changed
lastSeconds = Seconds;
// Starting at 10 seconds, every 5 seconds, decrement the Variable by 1 until it reaches 0.
if (Seconds >= 10 && (Seconds % 5) == 0 && Variable >= 1)
{
Variable--;
}
}