Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save sixhat/ee4facabb70cccee91ca9d0c9afbbce6 to your computer and use it in GitHub Desktop.

Select an option

Save sixhat/ee4facabb70cccee91ca9d0c9afbbce6 to your computer and use it in GitHub Desktop.
Example of using a Timer to run different tasks with different frequencies...
struct Timer {
bool active;
unsigned long previous;
unsigned long interval;
} luz, pisca;
/* Initializes timer with a given time interval */
void activateTimer(struct Timer* timer, unsigned long interval) {
timer->active = 1;
timer->previous = millis();
timer->interval = interval;
}
/* Checks if timer has fired and executes function if true */
void runTimer(struct Timer* timer, void (*function)()) {
if (timer->active && millis() - timer->previous >= timer->interval) {
function();
timer->previous = millis();
}
}
int running = 0;
void intHandler() {
static unsigned long last_interrupt_time = 0;
unsigned long interrupt_time = millis();
// If interrupts come faster than 200ms, assume it's a bounce and ignore
if (interrupt_time - last_interrupt_time > 200) {
running = !running;
}
last_interrupt_time = interrupt_time;
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(D6, OUTPUT);
pinMode(D5, INPUT);
attachInterrupt(digitalPinToInterrupt(D5), intHandler, FALLING);
activateTimer(&luz, 50);
activateTimer(&pisca, 200);
}
void piscar() {
static int ligado = 0;
if (running) {
ligado = 1 - ligado;
} else {
ligado = 0;
}
digitalWrite(D6, ligado);
}
void ler_luz() {
if (running) {
Serial.println(analogRead(A0));
}
}
void loop() {
runTimer(&luz, ler_luz);
runTimer(&pisca, piscar);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment