#include <U8g2lib.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define ENCODER_A_PIN 18 // Use pin numbers directly
#define ENCODER_B_PIN 19
volatile int32_t encoder_count = 0;
volatile int32_t count = 0;
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
void oledTask(void * pvParam) {
u8g2.begin();
char encoder_display[20];
char encoder_display2[20];
for (;;) {
u8g2.clearBuffer(); // clear the internal memory
u8g2.setFont(u8g2_font_ncenB08_tr); // choose a suitable font
sprintf(encoder_display2, "Count2: %d", count);
u8g2.drawStr(15, 10, encoder_display2); // write something to the internal memory
sprintf(encoder_display, "Count: %d", encoder_count); // prepare the string
u8g2.drawStr(15, 30, encoder_display); // display the encoder count
u8g2.sendBuffer(); // transfer internal memory to the display
vTaskDelay(pdMS_TO_TICKS(100));
}
}
void lcdTask(void * pvParam) {
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x3F for a 16 chars and 2 line display
lcd.setCursor(2,0); //Set cursor to character 2 on line 0
lcd.print("Hello world!");
// lcd.setCursor(1,1); //Set cursor to character 2 on line 0
// lcd.print(count); // prepare the string
vTaskDelay(pdMS_TO_TICKS(100));
}
void IRAM_ATTR encoder_isr_handler() {
static int32_t last_level_a = -1;
int level_a = digitalRead(ENCODER_A_PIN);
int level_b = digitalRead(ENCODER_B_PIN);
if (last_level_a != level_a) {
last_level_a = level_a;
if(level_a == 1) { // only count on rising edge
encoder_count += (level_a != level_b ? 1 : -1);
}
}
}
void encoder_setup() {
pinMode(ENCODER_A_PIN, INPUT_PULLUP);
pinMode(ENCODER_B_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(ENCODER_A_PIN), encoder_isr_handler, CHANGE);
// attachInterrupt(digitalPinToInterrupt(ENCODER_B_PIN), encoder_isr_handler, CHANGE);
}
void lcd_setup() {
LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x3F for a 16 chars and 2 line display
lcd.init();
lcd.clear();
lcd.backlight(); // Make sure backlight is on
}
void encoder_task(void *arg) {
for (;;) {
count += 1;
vTaskDelay(pdMS_TO_TICKS(50));
}
}
void Time_task(void *arg) {
for (;;) {
vTaskDelay(pdMS_TO_TICKS(2000));
static bool invflag;
invflag = !invflag;
u8g2.sendF("c", invflag? 0x0a7 : 0x0a6);
}
}
void setup() {
xTaskCreate(oledTask, "OLED Task", 1024 * 6, NULL, 1, NULL);
encoder_setup();
lcd_setup();
// xTaskCreate(lcdTask, "LCD Task", 1024 * 6, NULL, 1, NULL);
xTaskCreate(Time_task, "Time_task", 2048, NULL, 10, NULL);
xTaskCreate(encoder_task, "encoder_task", 2048, NULL, 10, NULL);
}
void loop() {}