#include <LiquidCrystal_I2C.h>
#include <Encoder.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
Encoder myEnc(2, 3);
#define button 4
long oldPosition = -999;
float angleValue;
float stockValue;
float encoderValue;
bool stockSet = false;
bool angleSet = false;
bool bigAngle;
byte customBackslash[8] = {
0b00000,
0b10000,
0b01000,
0b00100,
0b00010,
0b00001,
0b00000,
0b00000
};
void setup() {
lcd.begin(16, 2);
pinMode(button, INPUT_PULLUP);
Serial.begin(115200);
}
void loop() {
if (stockSet == false){
setStock();
}
if (stockSet == true && angleSet == false){
setAngle();
}
if (stockSet == true && angleSet == true){
calculate(stockValue, angleValue);
}
}
void(* resetFunc) (void) = 0;
void setStock(){
lcd.setCursor(0,0);
lcd.print("stock = ");
long newPosition = myEnc.read();
if (newPosition != oldPosition) {
oldPosition = newPosition;
lcd.setCursor(8, 0);
encoderValue = newPosition/4;
stockValue = encoderValue/2 + 20;
lcd.print(stockValue,1);
lcd.print(" mm ");
}
if(digitalRead(button) == LOW){
lcd.setCursor(0,0);
lcd.clear();
delay(500);
lcd.setCursor(0,0);
lcd.print("stock = ");
lcd.setCursor(8, 0);
lcd.print(stockValue,1);
lcd.print(" mm ");
stockSet = true;
lcd.setCursor(0,1);
lcd.print("angle = 90");
lcd.print("\xDF");
lcd.print(" |");
return stockValue;
}
}
void setAngle(){
long newPosition = myEnc.read();
if (newPosition != oldPosition) {
oldPosition = newPosition;
encoderValue = newPosition/4;
angleValue = encoderValue/2 - stockValue + 110;
printAngle(angleValue);
}
if (digitalRead(button)==LOW){
lcd.clear();
delay(500);
lcd.setCursor(0,1);
lcd.print("angle = ");
lcd.setCursor(8, 1);
lcd.print(angleValue,1);
angleSet = true;
return angleValue;
}
}
void printAngle(float angleValue){
lcd.createChar(7, customBackslash);
if (angleValue < 90){
lcd.setCursor(8,1);
lcd.print(angleValue,1);
lcd.print("\xDF");
lcd.setCursor(14,1);
lcd.write(byte(7)); //print our custom char backslash
}
else if (angleValue == 90){
lcd.setCursor(8,1);
lcd.print(angleValue,1);
lcd.print("\xDF");
lcd.print(" ");
lcd.setCursor(14,1);
lcd.print("|");
}
else {
lcd.setCursor(8,1);
float angleTemp = angleValue*-1+180;
lcd.print(angleTemp,1);
lcd.print("\xDF");
lcd.print(" ");
lcd.setCursor(14,1);
lcd.print("/");
}
return;
}
void calculate(float stockValue, float angleValue){
if(angleValue==0){
angleValue = 90;
}
lcd.clear();
lcd.setCursor(0,0);
float offset = (stockValue-14) / tan(angleValue*PI/180) ;
if (offset > -0.1 && offset< 0.1){
lcd.print("offset = 0.0 mm ");
}
else{
lcd.clear();
lcd.print("offset = ");
lcd.print(offset,1);
lcd.print(" mm");
}
while(digitalRead(button)==HIGH){
}
resetFunc();
}