#include <arduino-timer.h>
#include <Wire.h>
#include "Menu.h"
/**
Timers
*/
Timer<2, millis> appTimer;
unsigned long lastTime = 0;
const int ENCODER_TIMER = 50;
const int MENU_TIMEOUT = 10000;
const int SYSTEM_STATUS_TIMER = 1000;
/**
Encoder
*/
#define ENCODER_S1_PIN 32
#define ENCODER_S2_PIN 33
#define ENCODER_BTN_PIN 25
void setup() {
Serial.begin(115200);
while (!Serial);
Serial.println(".");
menu.setSystemStatus("starting ...");
initMenu();
initEncoder();
initTimers();
menu.setSystemStatus("");
tst();
}
void loop() {
try {
encoderWatcher();
appTimer.tick<void>();
} catch (const std::exception& e) {
Serial.println("UNEXPECTED ERROR: " + String(e.what()));
}
}
void tst() {
int ch = 1;
delayWithoutBlocking(1, [](int channel) {
Serial.println("V: 255, CH: " + String(channel));
}, ch);
delayWithoutBlocking(150, [](int channel) {
Serial.println("V: 0, CH: " + String(channel));
}, ch);
delayWithoutBlocking(300, [](int channel) {
Serial.println("V: 255x, CH: " + String(channel));
}, ch);
delayWithoutBlocking(450, [](int channel) {
Serial.println("V: 0x, CH: " + String(channel));
}, ch);
}
void delayWithoutBlocking(unsigned long delayTime, void (callback)(int), int intValue) {
if (millis() - lastTime >= delayTime) {
Serial.println("hit");
lastTime = millis();
(callback)(intValue);
if (delayTime == 450) {
Serial.println("x");
}
}
}
void initEncoder() {
pinMode(ENCODER_S1_PIN, INPUT);
pinMode(ENCODER_S2_PIN, INPUT);
pinMode(ENCODER_BTN_PIN, INPUT_PULLUP);
}
void initTimers() {
appTimer.every(ENCODER_TIMER, encoderActionTimer);
appTimer.every(SYSTEM_STATUS_TIMER, checkSystemStatusTimer);
}
void initMenu() {
menu.setupLcdWithMenu(0x27, mainMenu);
menu.showDashboard();
}
void encoderWatcher() {
int s1Value = digitalRead(ENCODER_S1_PIN);
if (s1Value != encoderLastS1Value) {
encoderLastS1Value = s1Value;
int s2Value = digitalRead(ENCODER_S2_PIN);
if (s1Value == LOW && s2Value == HIGH) {
encoderDirection = 1;
}
if (s1Value == LOW && s2Value == LOW) {
encoderDirection = -1;
}
}
}
bool checkSystemStatusTimer(void *) {
return true;
}
bool encoderActionTimer(void *) {
boolean menuChanged = false;
boolean btnValue = digitalRead(ENCODER_BTN_PIN);
if (encoderDirection != 0) {
if (menu.isShow()) {
if (encoderDirection == 1) {
menu.down();
} else {
menu.up();
}
}
encoderDirection = 0;
menuChanged = true;
showDashboard = false;
}
if (encoderConfirm == false && btnValue == LOW) {
menuChanged = true;
showDashboard = false;
if (menu.isShow()) {
encoderConfirm = true;
menu.enter();
}
} else if (encoderConfirm == true && btnValue == HIGH) {
encoderConfirm = false;
menuChanged = true;
}
if (menuChanged == true) {
if (!menu.isShow() && showDashboard == false) {
menu.show();
}
encoderLastInput = millis();
}
if ((millis() - encoderLastInput) > MENU_TIMEOUT) {
if (menu.isShow()) {
menu.backToMainMenu();
menu.showDashboard();
}
menu.lcd->setBacklight(LOW);
}
return true;
}