I am trying to finish a school assignment, where I am to program a "time quessing game" where I have to use button and calculate the time between buttton pushes using interrupts and store the time to an array.
The program is supposed ot print the following
1
2
3
4
5
Goal time was 20sec. Your time was 8sec.
the avrage time between pushes was 2.00sec.
So far I have tried the following:
int buttonPush = 0;
long start;
long halt;
byte timer;
long duration;
void setup(){
Serial.begin(9600);
pinMode(2, INPUT);
digitalWrite(2, HIGH);
attachInterrupt(2, painallus, FALLING);
}
void loop(){
}
void painallus(){
Serial.println(buttonPush);
start = millis();
timer = 1;
if(buttonPush <= 4){
buttonPush++;
if (buttonPush == 5){
halt=millis();
duration = halt - start;
Serial.println("lopeta");
Serial.println(duration);
}
}
}
You are breaking essentially all of the rules for using interrupts, and interrupts are never necessary for reading a button, so it would be better to just start over.
In the Arduino IDE, Files>Examples>Digital>Button would be a useful starting point. The State Change example would be another.
Do not use millis() inside interrupt routine
It is perfectly fine to read millis() in an interrupt but NEVER attempt serial I/O in an interrupt.
I am trying to calculate the time in seconds. If I need to use interrupts for the button, can I call another function from inside the interrupt function?
The best use of an interrupt is to simply notify the main program that an event happened. Set a "flag variable" to 1 and let the main program do all the calculations.
Other rules: variables shared with interrupt routines
must be declared volatile.
must be protected from modification by the interrupt, while being accessed by main
To time button pushes there is no need and no good reason to use an interrupt.