#define _TASK_SLEEP_ON_IDLE_RUN // Enable 1 ms SLEEP_IDLE powerdowns between runs if no callback methods were invoked during the pass
#include <TaskScheduler.h>
#include <EnableInterrupt.h>
// ==== Scheduler ==============================
Scheduler ts;
void task1Callback();
void task2Callback();
// ==== Task definitions ========================
Task t1 (1000 * TASK_MILLISECOND, TASK_FOREVER, &task1Callback, &ts, true);
Task t2 (500 * TASK_MILLISECOND, TASK_FOREVER, &task2Callback, &ts, true);
const int buttonPin = 3; // the number of the pushbutton pin
const int ledPin1 = 6; // the number of the LED pin
const int ledPin2 = 4; // the number of the LED pin
const int ledPin3 = 5; // the number of the LED pin
const int ledPin4 = 9; // the number of the LED pin
const int ledPin5 = 10; // the number of the LED pin
const int encoderPinA = 2;
const int encoderPinB = 7;
const int encoderButtonPin = 8;
// variables will change:
volatile int buttonState1 = 0; // variable for reading the pushbutton status
volatile bool ledState2 = false; // variable for reading the pushbutton status
volatile bool ledState3 = false; // variable for reading the pushbutton status
volatile int encoderPos = 10;
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
pinMode(ledPin4, OUTPUT);
pinMode(ledPin5, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
pinMode(encoderPinA, INPUT);
pinMode(encoderPinB, INPUT);
// Attach an interrupt to the ISR vector
attachInterrupt(digitalPinToInterrupt(buttonPin), pin_ISR, CHANGE);
attachInterrupt(digitalPinToInterrupt(encoderPinA), encoder_ISR, RISING);
}
void loop() {
ts.execute();
}
void pin_ISR() {
buttonState1 = digitalRead(buttonPin);
digitalWrite(ledPin1, buttonState1);
}
void encoder_ISR() {
static unsigned long lastInterruptTime = 0;
unsigned long interruptTime = millis();
if (interruptTime - lastInterruptTime > 5) { // faster than 5ms is a bounce
if (digitalRead(encoderPinB) == LOW) {
// right turn
encoderPos--;
digitalWrite(ledPin4, HIGH);
delay(100);
digitalWrite(ledPin4, LOW);
}
else {
// left turn
encoderPos++;
digitalWrite(ledPin5, HIGH);
delay(100);
digitalWrite(ledPin5, LOW);
}
}
encoderPos = max(0, min(20, encoderPos));
// update mode
}
void task1Callback() {
// task code
ledState2 = !ledState2;
digitalWrite(ledPin2, ledState2);
}
void task2Callback() {
// task code
ledState3 = !ledState3;
digitalWrite(ledPin3, ledState3);
}