#include <Thread.h>
#include <ThreadController.h>
#include <LiquidCrystal_I2C.h>
#define I2C_ADDR 0x27
#define LCD_COLUMNS 20
#define LCD_LINES 4
#define PIN_TRIG 3
#define PIN_ECHO 2
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
ThreadController control1 = ThreadController();
ThreadController control2 = ThreadController();
Thread myClock = Thread();
Thread myAdc = Thread();
Thread myDistance = Thread();
int cm = 0;
void printSec() {
lcd.setCursor(3, 0);
lcd.print(millis()/1000);
}
void readAdc() {
lcd.setCursor(3, 1);
lcd.print("A0 :");
int val = analogRead(A0);
lcd.print(val);
}
void getCm() {
digitalWrite(PIN_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
// Read the result:
int duration = pulseIn(PIN_ECHO, HIGH);
//Serial.print("Distance in CM: ");
cm = int(duration / 58);
lcd.setCursor(3, 2);
int cnt = map(cm, 0, 400, 0, 10);
for (int i = 0; i < 10; i++){
lcd.print((i<cnt) ?"#":" ");
}
}
void setup() {
Serial.begin(115200);
pinMode(PIN_TRIG, OUTPUT);
pinMode(PIN_ECHO, INPUT);
// Init
lcd.init();
lcd.backlight();
myClock.onRun(printSec);
myClock.setInterval(1000);
myAdc.onRun(readAdc);
myAdc.setInterval(500);
myDistance.onRun(getCm);
myDistance.setInterval(100);
control1.add(&myClock);
control2.add(&myAdc);
control2.add(&myDistance);
}
void loop() {
control1.run();
control2.run();
}