I’m trying to replicate that earbuds functionality that consists in a multifunctional button. If you press this button x amount of times, in a period of time, the earbud will do something depending on how many times you press the button. I don’t know if I’m being understandable (I’m not a native english speaker so it would be nice if you rate my english).
These are my main code and libraries.
#include <mcu_init.h>
#include <millis.h>
#include <button.h>
int main() {
GPIO_init();
cli();
INT0_init();
TMR0_init();
sei();
while (1) {
handleButton();
}
return 0;
}
#include <millis.h>
static volatile uint32_t miliseconds = 0;
ISR (TIMER0_COMPA_vect) {
miliseconds++;
PORTA |= (1 << 1);
}
uint32_t millis() {
uint32_t time;
uint8_t oldSREG = SREG;
cli();
time = miliseconds;
SREG = oldSREG;
return time;
}
#include <button.h>
volatile uint8_t count = 0;
volatile uint32_t lastPressTime = 0;
ISR (INT0_vect) {
if (millis() - lastPressTime >= 200) {
count++;
lastPressTime = millis();
}
}
void handleButton() {
if (millis() - lastPressTime >= 1500) {
lastPressTime = millis();
switch (count) {
case 2:
PORTA ^= (1 << 1);
count = 0;
break;
case 3:
PORTA ^= (1 << 3);
count = 0;
break;
default:
count = 0;
}
}
return;
}
These are the header files
#ifndef MILLIS_H_
#define MILLIS_H_
#include <avr/interrupt.h>
uint32_t millis();
#endif
#ifndef BUTTON_H_
#define BUTTON_H_
#include <millis.h>
void handleButton();
#endif
Btw, if I call the millis() function before calling the handleButton() function inside the while (1) from my main.c. It starts working. But if I dont do this, neither the timer 0 interrupt works.
I tried everything I could and the only things that worked were:
Declarating miliseconds as an extern volatile uint32_t in millis.h and incrementing this variable by the TIMER0 ISR. I used this variable as my millis().
Calling the millis() function before calling the handleButton() function inside the while (1) from my main.c. In this case, I don’t understand why this is happening and if it’s really necessary to do this call in the main loop.
Carlos Leonel Rivas Pimentel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.