From 7e3f40f15ef5f1660c3f9fd7edecd33f041694b3 Mon Sep 17 00:00:00 2001 From: Bluedragon Date: Mon, 25 Apr 2022 02:33:02 +0700 Subject: [PATCH] init --- .gitignore | 5 + .vscode/extensions.json | 10 + backup/VSS_Rally_V2.h | 1972 +++++++++ backup/backup index before cleanup.h | 413 ++ backup/backup_main.cpp | 677 +++ ...backup_main_before cleaning lcd and at24cx | 2844 +++++++++++++ ...ackup_main_before tryingVSSRALLYv2only.cpp | 2844 +++++++++++++ backup/startrally1.html | 302 ++ data/constanta.html | 177 + data/inputPwd.txt | 1 + data/ssidString.txt | 1 + data/text.txt | 1 + data/tripA | 0 data/tripB | 0 data/tripC | 0 data/tripD | 0 data/tripE | 0 data/tripF | 0 data/tripG | 0 data/tripH | 0 data/tripI | 0 data/tripJ | 0 data/tripK | 0 data/tripL | 0 data/tripM | 0 data/tripN | 0 data/tripO | 0 data/tripP | 0 include/README | 39 + lib/README | 46 + platformio.ini | 34 + src/constanta.h | 194 + src/index.h | 406 ++ src/main.cpp | 3652 +++++++++++++++++ src/template_html.h | 281 ++ test/README | 11 + 36 files changed, 13910 insertions(+) create mode 100644 .gitignore create mode 100644 .vscode/extensions.json create mode 100644 backup/VSS_Rally_V2.h create mode 100644 backup/backup index before cleanup.h create mode 100644 backup/backup_main.cpp create mode 100644 backup/backup_main_before cleaning lcd and at24cx create mode 100644 backup/backup_main_before tryingVSSRALLYv2only.cpp create mode 100644 backup/startrally1.html create mode 100644 data/constanta.html create mode 100644 data/inputPwd.txt create mode 100644 data/ssidString.txt create mode 100644 data/text.txt create mode 100644 data/tripA create mode 100644 data/tripB create mode 100644 data/tripC create mode 100644 data/tripD create mode 100644 data/tripE create mode 100644 data/tripF create mode 100644 data/tripG create mode 100644 data/tripH create mode 100644 data/tripI create mode 100644 data/tripJ create mode 100644 data/tripK create mode 100644 data/tripL create mode 100644 data/tripM create mode 100644 data/tripN create mode 100644 data/tripO create mode 100644 data/tripP create mode 100644 include/README create mode 100644 lib/README create mode 100644 platformio.ini create mode 100644 src/constanta.h create mode 100644 src/index.h create mode 100644 src/main.cpp create mode 100644 src/template_html.h create mode 100644 test/README diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..080e70d --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,10 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ], + "unwantedRecommendations": [ + "ms-vscode.cpptools-extension-pack" + ] +} diff --git a/backup/VSS_Rally_V2.h b/backup/VSS_Rally_V2.h new file mode 100644 index 0000000..ee63ba2 --- /dev/null +++ b/backup/VSS_Rally_V2.h @@ -0,0 +1,1972 @@ +#include +#include +#include +#include + +//#define BUFF_MAX 128 + +//****************************************Define I2C LCD Display ********************************* +#define I2C_ADDR 0x27 // Define I2C Address for the PCF8574T +//---(Following are the PCF8574 pin assignments to LCD connections )---- +// This are different than earlier/different I2C LCD displays + +#define Rs_pin 0 +#define Rw_pin 1 +#define En_pin 2 +#define BACKLIGHT_PIN 3 +#define D4_pin 4 +#define D5_pin 5 +#define D6_pin 6 +#define D7_pin 7 +#define UP_pin 4 +#define DOWN_pin 5 +#define LEFT_pin 6 +#define RIGHT_pin 7 +#define OK_pin 8 + +#define ATMEGA328 //comment out this line if it is not ATMEGA328 +//#define DEBUG //comment out this line to disable for Production(No Serial print) + +#define RRcountSIZE 20 +#define count1Address 0 +#define count1count2diffAddress 40 //only one address which is 40*32 +//int count1Address = 0; +//int count1count2diffAddress = 40; +long count1count2diff = 0; + +#define TRIPSIZE 12 //so thestartaddress is 50*32 until (50+12)*32 +#define TRIPADDRESS 50 + +const byte interruptPin = 2; +const byte ledPin = 13; + +#ifndef ATMEGA328 + volatile byte ledstate = LOW; +#endif + +#define LED_OFF 0 +#define LED_ON 1 + +/*-----( Declare objects )-----*/ +LiquidCrystal_I2C lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin); +AT24CX mem; +boolean cursorON=true; +boolean blinkON=true; +//************************************ END LCD DISPLAY ******************************************* + +uint8_t time[8]; +//char recv[BUFF_MAX]; +unsigned int recv_size = 0; +unsigned long prevsettime, intervalsettime = 250; +unsigned long prevtempint, tempinterval=60000; +unsigned long prevtemprally, tempintervalrally=200; +unsigned long prevcalibrationtime, calibrationtimeinterval = 100; +unsigned long updatecounttime=0; +float temperature; +byte x,y; +unsigned long startmillis, startVSSCount; +unsigned long startsavemillis; + +//#include //https://github.com/JChristensen/Button //from change to +#include + +#define DN_PIN 5 //Connect two tactile button switches (or something similar) +#define UP_PIN 4 //from Arduino pin 2 to ground and from pin 3 to ground. +#define LF_PIN 6 +#define RF_PIN 7 +#define OK_PIN 8 +#define ESC_PIN 10 +#define PULLUP true //To keep things simple, we use the Arduino's internal pullup resistor. +#define INVERT true //Since the pullup resistor will keep the pin high unless the + //switch is closed, this is negative logic, i.e. a high state + //means the button is NOT pressed. (Assuming a normally open switch.) +#define DEBOUNCE_MS 40 //A debounce time of 20 milliseconds usually works well for tactile button switches. + +#define REPEAT_FIRST 1000 //ms required before repeating on long press +#define REPEAT_INCR 75 //repeat interval for long press +#define MIN_COUNT 0 +#define MAX_ROW 3 +#define MAX_COL 19 +#define MS_IN_HOUR 3600000 //Number of ms in an hour +#define MS_IN_MIN 60000 //Number of ms in a minute +Button btnUP(UP_PIN, PULLUP, INVERT, DEBOUNCE_MS); //Declare the buttons +Button btnDN(DN_PIN, PULLUP, INVERT, DEBOUNCE_MS); +Button btnLF(LF_PIN, PULLUP, INVERT, DEBOUNCE_MS); +Button btnRF(RF_PIN, PULLUP, INVERT, DEBOUNCE_MS); //Declare the buttons +Button btnOK(OK_PIN, PULLUP, INVERT, DEBOUNCE_MS); //Declare the buttons +Button btnESC(ESC_PIN, PULLUP, INVERT, DEBOUNCE_MS); //Declare the buttons +enum {WAIT, UP, DOWN, LEFT, RIGHT, OK, RALLYEDIT, ESC}; //The possible states for the STATE machine +enum {MAIN, CALIBRATION, SETTIME, INPUTSUBTRAYEK, RALLY, CONSTANTA}; //The possible states for the MENU +enum {FORWARD, FREEZE, BACKWARD}; +char *dircount[] = {"Fw", "Zz", "Bw"}; + +uint8_t MENU, PREVMENU; +uint8_t STATE, dircount1, dircount2; //The current state machine state +byte hour24, min60, sec60; +unsigned long rpt = REPEAT_FIRST; //A variable time that is used to drive the repeats for long presses +uint8_t prevsec; +float constanta=3.275; +float distance1, distance2; +float prevdistance1, prevdistance2; +long prevcount1, prevcount2; +boolean showTIME = true; + +float tempval; +struct ts t; +byte calibrationDistance=1; +byte tempcalibdist=1; +boolean calibrationON=false; + +float oneMeter=0; +unsigned long startCalibration=0; +unsigned long Calibration=110400; //for CR-V 2012 +unsigned long Calibrationcount; +unsigned long Calibrationtime; +int digit1, digit2, digit3, digit4, digit5, digit6; +byte calibdigit1, calibdigit2, calibdigit3; +int dist1digit1, dist1digit2; +int dist2digit1, dist2digit2; +byte starttractsec, starttractmin, starttracthour; +boolean rallyON=false; + +volatile unsigned long VSSCount =0; + +long count1 = 0; //must be signed as technically distance can go negative +long count2 = 0; +long backcount1 = 0; +long backcount2 = 0; + +//The two time variables are used to store reset times in ms +unsigned long time1 = 1; +unsigned long time2 = 1; +int CURSOR_POS = 1; + +unsigned long count1Seq = 0; +boolean editDist1 = false; + +//to save trayek data +struct RallyData { + char sub; + float speed; + byte startHour; + byte startMin; + byte startSec; +// float distance; +// unsigned int subTime; +}; + //RallyData Trip={"b",23.342, 11,0,0,12.13}; + RallyData Trip[TRIPSIZE]; +//RallyData currentTrip; +byte curTrip=0; +byte prevTrip=0; + +void setup() +{ +// Serial.begin(115200); +#ifdef DEBUG + Serial.begin(115200); + Serial.println("Starting Rally"); +#endif + Wire.begin(); + pinMode(UP_pin, INPUT_PULLUP); + pinMode(DOWN_pin, INPUT_PULLUP); + pinMode(LEFT_pin, INPUT_PULLUP); + pinMode(RIGHT_pin, INPUT_PULLUP); + pinMode(OK_pin, INPUT_PULLUP); + DS3231_init(DS3231_INTCN); + //memset(recv, 0, BUFF_MAX); +#ifdef DEBUG + Serial.println("GET time"); +#endif +/* +Trip[0].sub = "A"; +Trip[0].speed = 24.275; +Trip[0].startHour = 25; +//Trip[0].distance = 12.898; +Trip[9].sub = "A"; +Trip[9].speed = 90.2751; +Trip[9].startHour = 22; +Trip[9].startMin = 59; +Trip[9].startSec = 58; +*/ +//Trip[9].distance = 12.898; +//Serial.println(Trip[0].sub);Serial.println(Trip[0].speed);Serial.println(Trip[0].startHour);Serial.println(Trip[0].startMin);Serial.println(Trip[0].startSec); +//Serial.println(Trip[0].distance); +//Serial.println(Trip[0].subTime); + +for (int i = 0; i23) starttracthour = 23; + if (starttractmin>59) starttractmin = 59; + if (starttractsec>59) starttractsec = 59; + //constanta=mem.readFloat(800); + constanta = Trip[curTrip].speed; + if ((constanta > 150) || (constanta < 0)) constanta = 60; + long m = mem.readLong(896); //read calibration value; + if (m >= 0) { + Calibration = m; + } +#ifdef DEBUG + Serial.println(m); + Serial.println(Calibration); + Serial.println(constanta); +#endif + constantatodigit(); + +// Serial.print(digit1);Serial.print(digit2); Serial.print(digit3); Serial.print(digit4);Serial.print(digit5);Serial.println(digit6); +// Serial.println(constanta,5); + //Serial.print(digitalRead(UP_pin));Serial.print(digitalRead(DOWN_pin));Serial.print(digitalRead(LEFT_pin));Serial.print(digitalRead(RIGHT_pin));Serial.println(digitalRead(OK_pin)); + + prevcount1 = count1; + prevcount2 = count2; + + prevcalibrationtime+=calibrationtimeinterval; + prevtempint+=tempinterval; + prevtemprally+=tempintervalrally; + prevsettime += intervalsettime; + startmillis+=1000; + + pinMode(ledPin, OUTPUT); + pinMode(interruptPin, INPUT); //Pull down using resistor to ground + attachInterrupt(digitalPinToInterrupt(interruptPin), blink, FALLING); + + mainMenu(); +} +void constantatodigit() +{ + digit1=(int)(constanta/10); + digit2=(int)constanta%10; + digit3=(int)((constanta - (int)constanta)*10); + digit4=(int)((constanta*10 - (int)(constanta*10))*10); + digit5=(int)((constanta*100 - (int)(constanta*100))*10); + digit6=(int)((constanta*1000 - (int)(constanta*1000))*10); + //digit6=(int)((constanta*10000 - (int)(constanta*10000))*10); +} +void memretrieveTrip(int pointer, int startaddress) +{ + //Serial.print (pointer); Serial.println(startaddress); + int pointeradd; + Trip[pointer].speed = mem.readFloat(startaddress); + pointeradd = (startaddress + 6); + Trip[pointer].startHour = mem.read(pointeradd); + pointeradd = (startaddress + 5); + Trip[pointer].startMin = mem.read(pointeradd); + pointeradd = (startaddress + 4); + Trip[pointer].startSec = mem.read(pointeradd); + if (Trip[pointer].startHour >= 24) Trip[pointer].startHour = 23; + if (Trip[pointer].startMin >= 60) Trip[pointer].startMin = 59; + if (Trip[pointer].startSec >= 60) Trip[pointer].startSec = 59; +} + +unsigned long memretrieveLong(int startaddress, byte rrpointersize, unsigned long &seq ) +{ + //Serial.print(seq);Serial.print(";R ");Serial.print(rrpointer[0]);Serial.print("; SizeofArr=");Serial.println(rrpointersize); + unsigned long largestcountpointer=0; + int lastpointer = 0; + unsigned long seqnumber = 0; + int pointeradd = 0; + for (int i = 0; i");Serial.println(mem.readLong(pointer+(i*32))); + } +} +*/ + +void blink() { +#ifndef ATMEGA328 + ledstate = !ledstate; +#else + PORTB ^= B00100000; +#endif + VSSCount++; +} + +#ifdef DEBUG +long prevtimemicros=micros(); //************************************************************************** +#endif +unsigned long rallyEditTime=micros(); +byte rallyEditRpt = 0; +boolean rallyEdit =false; +boolean savedCount = true; +unsigned long intervalsavemillis = 3000; + +void loop_VSS() +{ +#ifdef DEBUG + prevtimemicros = micros(); +#endif +#ifndef ATMEGA328 + digitalWrite(ledPin, ledstate); +#endif + char tempF[6]; + unsigned long now1 = millis(); + + btnUP.read(); //read the buttons + btnDN.read(); + btnLF.read(); //read the buttons + btnRF.read(); + btnOK.read(); + btnESC.read(); + if (millis()-rallyEditTime >1500) rallyEditRpt = 0; + switch (STATE) { + case WAIT: //wait for a button event + if (btnUP.wasPressed()) + STATE = UP; + else if (btnDN.wasPressed()) + STATE = DOWN; + else if (btnLF.wasPressed()) + STATE = LEFT; + else if (btnRF.wasPressed()) + STATE = RIGHT; + else if (btnUP.wasReleased()) //reset the long press interval + rpt = REPEAT_FIRST; + else if (btnDN.wasReleased()) + rpt = REPEAT_FIRST; + else if (btnLF.wasReleased()) //reset the long press interval + rpt = REPEAT_FIRST; + else if (btnRF.wasReleased()) + rpt = REPEAT_FIRST; + else if (btnUP.pressedFor(rpt)) { //check for long press + rpt += REPEAT_INCR; //increment the long press interval + STATE = UP; + } + else if (btnDN.pressedFor(rpt)) { + rpt += REPEAT_INCR; + STATE = DOWN; + } + else if (btnLF.pressedFor(rpt)) { //check for long press + rpt += REPEAT_INCR; //increment the long press interval + STATE = LEFT; + } + else if (btnRF.pressedFor(1000)) { + rpt += REPEAT_INCR; + STATE = RIGHT; + } + else if (btnOK.wasPressed() && (MENU != RALLY)) { + STATE = OK; + } + else if (btnOK.wasPressed() && (CURSOR_POS > 4)) { + STATE = OK; + } + else if (btnOK.wasPressed() && (CURSOR_POS <= 2)) { + //STATE = OK; + if (!rallyEditRpt) { + rallyEditTime = millis(); + rallyEditRpt++; + //Serial.println("!rallyEditRpt"); + //Serial.println(rallyEditRpt); + } + else if (millis()-rallyEditTime > 1500) { + rallyEditRpt = 0; + //Serial.println("rallyEditRpt = 0"); + //Serial.println(rallyEditRpt); + } + else if (rallyEditRpt == 2) { + //Serial.println("rallyEditRpt = ");Serial.println(rallyEditRpt); + STATE = RALLYEDIT; + rallyEditRpt = 0; + } + else { + rallyEditRpt++; + //Serial.println("rallyEditRpt++"); + //Serial.println(rallyEditRpt); + } + } + else if (btnOK.pressedFor(rpt) && (CURSOR_POS <= 4)) { + STATE = OK; + } + else if (btnESC.wasPressed()){ + STATE = ESC; + //Serial.println("ESC pressed"); + } + break; + + case DOWN: //increment the counter + switch (MENU) { + case MAIN: + y = min(y++, MAX_ROW); //but not more than the specified maximum + break; + + case RALLY: + if (blinkON) { + if (y == 1) { + if (x == 0 || x == 1) { + dist1digit1 = max(dist1digit1--, 0); + lcd.setCursor(0,y); + if (dist1digit1 <10) lcd.print("0"); + lcd.print(dist1digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist1digit2 = max(dist1digit2-=1, 0); + lcd.setCursor(3,y); + if (dist1digit2 <10) { + lcd.print("00"); + }else if (dist1digit2 <100) lcd.print("0"); + lcd.print(dist1digit2); + } + } + else if (y ==3) { + if (x == 0 || x == 1) { + dist2digit1 = max(dist2digit1--, 0); + lcd.setCursor(0,y); + if (dist2digit1 <10) lcd.print("0"); + lcd.print(dist2digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist2digit2 = max(dist2digit2-=1, 0); + lcd.setCursor(3,y); + if (dist2digit2 <10) { + lcd.print("00"); + }else if (dist2digit2 <100) lcd.print("0"); + lcd.print(dist2digit2); + } + + } + + } + else { + CURSOR_POS=min(CURSOR_POS++,10); + set_cursor_pos(CURSOR_POS); + } + + break; + + case CALIBRATION: + if (!blinkON) y = min(y++, MAX_ROW ); //but not more than the specified maximum + else if (blinkON && y==1) { + //calibrationDistance=max(calibrationDistance--, 1); + tempcalibdist=max(tempcalibdist--, 1); + lcd.print(tempcalibdist); + } + else if (blinkON && y==3 && (x==18||x==19)) { + calibdigit3 = max(calibdigit3--,0); + lcd.setCursor(18,3); + if (calibdigit3<10) lcd.print("0"); + lcd.print(calibdigit3); + } + else if (blinkON && y==3 && (x==16||x==17)) { + calibdigit2 = max(calibdigit2--,0); + lcd.setCursor(16,3); + if (calibdigit2<10) lcd.print("0"); + lcd.print(calibdigit2); + } + else if (blinkON && y==3 && (x==14||x==15)) { + calibdigit1 = max(calibdigit1--,0); + lcd.setCursor(14,3); + if (calibdigit1<10) lcd.print("0"); + lcd.print(calibdigit1); + } + break; + + case CONSTANTA: + if (!blinkON) { + y = min(y++, 3); //but not less than the specified minimum + if (y==1) x=15; + } + else if (y==1) { + prevTrip = min(prevTrip++,TRIPSIZE-1); + //curTrip = min(curTrip++,TRIPSIZE-1); + lcd.setCursor(14,y); + lcd.print(Trip[prevTrip].sub); + } + else if (x==13 && y==2) { + digit1 = max(digit1--, MIN_COUNT); + lcd.print(digit1); + } + else if (x==14 && y==2) { + digit2 = max(digit2--, MIN_COUNT); + lcd.print(digit2); + } + else if (x==16 && y==2) { + digit3 = max(digit3--, MIN_COUNT); + lcd.print(digit3); + } + else if (x==17 && y==2) { + digit4 = max(digit4--, MIN_COUNT); + lcd.print(digit4); + } + else if (x==18 && y==2) { + digit5 = max(digit5--, MIN_COUNT); + lcd.print(digit5); + } + else if (x==19 && y==2) { + digit6 = max(digit6--, MIN_COUNT); + lcd.print(digit6); + } + else if ((x==12 || x==13) && y==3) { //******SET CONSTANTA TIME ******* + hour24=max(hour24--, MIN_COUNT); + lcd.setCursor(12,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==15 || x==16) && y==3) { + min60=max(min60--, MIN_COUNT); + lcd.setCursor(15,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==18 || x==19) && y==3) { + sec60=max(sec60--, MIN_COUNT); + lcd.setCursor(18,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + + case SETTIME: + if (!blinkON) { + y = min(y++, MAX_ROW); //but not more than the specified maximum + lcd.setCursor(x,y); + } + else if ((x==0 || x==1) && y==3) { + hour24=max(hour24--, MIN_COUNT); + lcd.setCursor(0,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==3 || x==4) && y==3) { + min60=max(min60--, MIN_COUNT); + lcd.setCursor(3,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==6 || x==7) && y==3) { + sec60=max(sec60--, MIN_COUNT); + lcd.setCursor(6,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case UP: //decrement the counter + switch(MENU) { + case MAIN: + y = max(y--, MIN_COUNT); //but not less than the specified minimum + break; + + case CALIBRATION: + if (!blinkON) { + y = max(y--, MIN_COUNT); //but not less than the specified minimum + x = 18; + } + else if (blinkON && y==1) { + //calibrationDistance=min(calibrationDistance++, 9); + tempcalibdist=min(tempcalibdist++, 9); + lcd.print(tempcalibdist); + } + else if (blinkON && y==3 && (x==18||x==19)) { + calibdigit3 = min(calibdigit3++,99); + lcd.setCursor(18,3); + if (calibdigit3<10) lcd.print("0"); + lcd.print(calibdigit3); + } + else if (blinkON && y==3 && (x==16||x==17)) { + calibdigit2 = min(calibdigit2++,99); + lcd.setCursor(16,3); + if (calibdigit2<10) lcd.print("0"); + lcd.print(calibdigit2); + } + else if (blinkON && y==3 && (x==14||x==15)) { + calibdigit1 = min(calibdigit1++,50); + lcd.setCursor(14,3); + if (calibdigit1<10) lcd.print("0"); + lcd.print(calibdigit1); + } + break; + + case RALLY: + if (blinkON) { + if (y == 1) { + if (x == 0 || x == 1) { + dist1digit1 = min(dist1digit1++, 999); + lcd.setCursor(0,y); + if (dist1digit1 <10) lcd.print("0"); + lcd.print(dist1digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist1digit2 = min(dist1digit2+=1, 999); + lcd.setCursor(3,y); + if (dist1digit2 <10) { + lcd.print("00"); + }else if (dist1digit2 <100) lcd.print("0"); + lcd.print(dist1digit2); + } + } + else if (y == 3) { + if (x == 0 || x == 1) { + dist2digit1 = min(dist2digit1++, 99); + lcd.setCursor(0,y); + if (dist2digit1 <10) lcd.print("0"); + lcd.print(dist2digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist2digit2 = min(dist2digit2+=1, 999); + lcd.setCursor(3,y); + if (dist2digit2 <10) { + lcd.print("00"); + }else if (dist2digit2 <100) lcd.print("0"); + lcd.print(dist2digit2); + } + } + + } + else { + CURSOR_POS=max(CURSOR_POS--,1); + set_cursor_pos(CURSOR_POS); + } + break; + + case CONSTANTA: + if (!blinkON) { + y = max(y--, MIN_COUNT); //but not less than the specified minimum + if (y==0) x=16; + else if (y==1) x=15; + } + else if (y==1) { + prevTrip = max(prevTrip--, MIN_COUNT); + //curTrip = max(curTrip--, MIN_COUNT); + lcd.setCursor(14,y); + lcd.print(Trip[prevTrip].sub); + } + else if (x==13 && y==2) { + digit1=min(digit1++, 9); + lcd.print(digit1); + } + else if (x==14 && y==2) { + digit2=min(digit2++, 9); + lcd.print(digit2); + } + else if (x==16 && y==2) { + digit3=min(digit3++, 9); + lcd.print(digit3); + } + else if (x==17 && y==2) { + digit4=min(digit4++, 9); + lcd.print(digit4); + } + else if (x==18 && y==2) { + digit5=min(digit5++, 9); + lcd.print(digit5); + } + else if (x==19 && y==2) { + digit6=min(digit6++, 9); + lcd.print(digit6); + } + else if ((x==12 || x==13) && y==3) { //******SET CONSTANTA TIME ******* + hour24=min(hour24++, 23); + lcd.setCursor(12,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==15 || x==16) && y==3) { + min60=min(min60++, 59); + lcd.setCursor(15,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==18 || x==19) && y==3) { + sec60=min(sec60++, 59); + lcd.setCursor(18,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + + case SETTIME: + if (!blinkON) { + y = max(y--, MIN_COUNT); //but not less than the specified minimum + //Serial.print(x); Serial.print(","); Serial.println(y); + //lcd.setCursor(x,y); + } + else if ((x==0 || x==1) && y==3) { + hour24=min(hour24++, 23); + lcd.setCursor(0,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==3 || x==4) && y==3) { + min60=min(min60++, 59); + lcd.setCursor(3,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==6 || x==7) && y==3) { + sec60=min(sec60++, 59); + lcd.setCursor(6,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case RIGHT: //increment the counter + switch (MENU) { + case SETTIME: + x = min(x++, MAX_COL); //MAX_COUNT); //but not more than the specified maximum + //STATE = WAIT; + //Serial.print(x); Serial.print(","); Serial.println(y); + //lcd.setCursor(x,y); + break; + + case RALLY: + if (blinkON) { + + x = min(x++, 5); + //Serial.println(x); + } + else if (CURSOR_POS % 2 ==0) CURSOR_POS=min(CURSOR_POS+2,10); + else CURSOR_POS=min(CURSOR_POS+2,9); + if (!blinkON) set_cursor_pos(CURSOR_POS); + break; + + case CONSTANTA: + if (y==2 || y==3) { + x = min(x++, MAX_COL); //MAX_COUNT); + } + break; + + case CALIBRATION: + if (y==3) { + x = min(x++,MAX_COL); + } + else x = 18; + break; + + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case LEFT: //decrement the counter + switch (MENU) { + case SETTIME: + x = max(x--, MIN_COUNT); //but not less than the specified minimum + //STATE = WAIT; + //Serial.print(x); Serial.print(","); Serial.println(y); + //lcd.setCursor(x,y); + break; + + case RALLY: + if (blinkON) { + x = max(x--, MIN_COUNT); + } + else if (CURSOR_POS % 2 == 0) CURSOR_POS=max(CURSOR_POS-2,2); + else CURSOR_POS=max(CURSOR_POS-2,1); + if (!blinkON) set_cursor_pos(CURSOR_POS); + break; + + case CONSTANTA: + if (y==2 || y==3){ + x = max(x--, 12); + } + break; + + case CALIBRATION: + if (y==3) { + x = max(x--, 14); + } + else x = 18; + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case OK: + switch (MENU) { + case MAIN: + if (y==1) { + MENU = SETTIME; + //prevsettime += millis(); + //prevtempint+=millis(); + } + else if (y==0) { + MENU = RALLY; + //prevtemprally=millis(); + } + else if (y==2) MENU = CONSTANTA; + else if (y==3) { + MENU = CALIBRATION; + //prevcalibrationtime+=millis(); + } + break; + + case CONSTANTA: + if (y==0) MENU = MAIN; + //else if (!blinkON && y==1) { + + // } + else if (!blinkON && y==2) { + constantatodigit(); + lcd.blink(); + blinkON=!blinkON; + } + else if (!blinkON && y==3) { + sec60 = starttractsec; + min60 = starttractmin; + hour24 = starttracthour; + lcd.blink(); + blinkON=!blinkON; + } + else if (!blinkON && y==1) { + prevTrip = curTrip; + lcd.blink(); + blinkON = !blinkON; + } + else if (blinkON && y==1) { + curTrip = prevTrip; + constanta = Trip[curTrip].speed; + starttractsec = Trip[curTrip].startSec; + starttractmin = Trip[curTrip].startMin; + starttracthour = Trip[curTrip].startHour; + lcd.noBlink(); + blinkON=!blinkON; + constantaMenu(); + } + else if (blinkON && y==2) { + lcd.noBlink(); + blinkON=!blinkON; + constanta = (digit1*10)+digit2+(float)digit3/10+(float)digit4/100+(float)digit5/1000+(float)digit6/10000; //+(float)digit6/100000; + //mem.writeFloat(800, constanta); + int pointeradd = ((TRIPADDRESS+curTrip)*32); + mem.writeFloat(pointeradd, constanta); + Trip[curTrip].speed = constanta; +#ifdef DEBUG + Serial.println(pointeradd); Serial.print(";");Serial.println(constanta,5); +#endif + } + else if (blinkON && y==3) { + starttractsec=sec60; + starttractmin=min60; + starttracthour=hour24; + unsigned long valuesettime = starttracthour; + valuesettime = valuesettime * 256 + starttractmin; // effectively shift the first byte 8 bit positions + valuesettime = valuesettime * 256 + starttractsec; + //mem.writeLong(768,valuesettime); + int pointeradd = ((TRIPADDRESS+curTrip)*32+4); + mem.writeLong(pointeradd, valuesettime); + Trip[curTrip].startHour = starttracthour; + Trip[curTrip].startMin = starttractmin; + Trip[curTrip].startSec = starttractsec; + lcd.noBlink(); + blinkON=!blinkON; +#ifdef DEBUG + Serial.println(pointeradd); Serial.println(valuesettime); +#endif + } + else {// if (y==3) { + lcd.blink(); + blinkON=!blinkON; + } + break; + + case RALLY: +#ifdef DEBUG + Serial.println("OKRALLY"); +#endif + switch(CURSOR_POS) + { + case 1: + count1 = 0; + backcount1 = 0; + time1 = VSSCount; + //Serial.println("case 1"); + break; + case 2: + count2 = 0; + backcount2 = 0; + time2 = VSSCount; + //Serial.println("case 2"); + break; + case 3: + count2 = count1; //no yet UNDO next update can UNDO + backcount2 = 0; + //time2 = VSSCount; + //Serial.println("case 3"); + break; + case 4: + count1 = count2; //no yet UNDO next update can UNDO + backcount1 = 0; + //time1 = VSSCount; + //Serial.println("case 4"); + break; + case 5: + //dirfwdcount1 = !dirfwdcount1; + switch (dircount1) + { + case FORWARD: + dircount1 = FREEZE; + break; + case FREEZE: + dircount1 = BACKWARD; + break; + case BACKWARD: + dircount1 = FORWARD; + break; + default: + dircount1 = FORWARD; + break; + } + secondrallyMenu(); + //Serial.println("case 5"); + break; + case 6: + //dirfwdcount2 = !dirfwdcount2; + switch (dircount2) + { + case FORWARD: + dircount2 = FREEZE; + break; + case FREEZE: + dircount2 = BACKWARD; + break; + case BACKWARD: + dircount2 = FORWARD; + break; + default: + dircount2 = FORWARD; + break; + } + secondrallyMenu(); + //Serial.println("case 6"); + break; + case 7: + showTIME = !showTIME; + rallyMenu(); + break; + case 8: + showTIME = !showTIME; + rallyMenu(); + break; + case 9: + //Serial.println("case 9"); + MENU = MAIN; + lcd.noBlink(); + break; + case 10: + //Serial.println("case 10"); + MENU = MAIN; + lcd.noBlink(); + break; + + } + break; + + case CALIBRATION: + if (blinkON && y==1) { + lcd.noBlink(); + blinkON=!blinkON; + calibrationDistance = tempcalibdist; + } + else if (!blinkON && y==1) { + lcd.blink(); + blinkON=!blinkON; + tempcalibdist = calibrationDistance; + } + else if (!blinkON && y==2) { + //startCalibration = millis(); + Calibrationcount = 0; + startCalibration = VSSCount; + Calibrationtime = startCalibration; + blinkON=!blinkON; + lcd.blink(); + calibrationON=true; + lcd.setCursor(0,2); + lcd.print("Calibrating 00.000Km"); + } + else if (blinkON && y==2) { + Calibration = (VSSCount-startCalibration)/(float)calibrationDistance; + mem.writeLong(896, Calibration); //Save Calibration to memory + oneMeter=(millis()-startCalibration)/(1000*(float)calibrationDistance);//*calibrationDistance); + oneMeter=((float)VSSCount-startCalibration)/(1000*(float)calibrationDistance);//*calibrationDistance); + oneMeter=(float)(Calibration)/1000*(float)calibrationDistance; + blinkON=!blinkON; + lcd.noBlink(); + calibrationON=false; + lcd.setCursor(0,2); + lcd.print("Start "); + lcd.setCursor(0,3); + lcd.print("1m="); + //Serial.print(startCalibration);Serial.print(";");Serial.print((millis()-startCalibration)/1000);Serial.print(";"); +#ifdef DEBUG + Serial.println(oneMeter,5); +#endif + lcd.print(oneMeter,3); + lcd.print(";"); + } + else if (!blinkON && y==3) { //not yet implemented + lcd.blink(); + blinkON=!blinkON; + calibdigit1 = (byte)(Calibration/10000); + calibdigit2 = (byte)((Calibration % 10000)/100); + calibdigit3 = Calibration % 100; + //Serial.println(calibdigit1);Serial.println(calibdigit2);Serial.println(calibdigit3); + } + else if (blinkON && y==3) { + lcd.noBlink(); + blinkON=!blinkON; + //Serial.println(calibdigit1);Serial.println(calibdigit2);Serial.println(calibdigit3); + Calibration = ((long)calibdigit1*10000) + ((long)calibdigit2*100) + (calibdigit3); + //Serial.println(Calibration); + mem.writeLong(896, Calibration); + } + else if (y==0) MENU = MAIN; + break; + + case SETTIME: + if (blinkON && y==3) { + t.sec=sec60; + t.min=min60; + t.hour=hour24; + DS3231_set(t); + lcd.noBlink(); + blinkON=!blinkON; + //Serial.println("OK"); + } + else if (y==3) { + lcd.blink(); + blinkON=!blinkON; + } + else {//(blinkON) { + MENU = MAIN; + lcd.noBlink(); + } + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case RALLYEDIT: + if ((CURSOR_POS == 1 || CURSOR_POS == 2) && !blinkON) { + rallyEdit = true; + blinkON = true; + lcd.blink(); + //if (distance<100) { + dist1digit1=((int)distance1%1000); + dist1digit2=(int)((distance1 - (int)distance1)*1000); + dist2digit1=((int)distance2%1000); + dist2digit2=(int)((distance2 - (int)distance2)*1000); + //} + /* + Serial.print(dist1digit1);Serial.println(dist1digit2); //Serial.print(dist1digit3); Serial.print(dist1digit4);Serial.println(dist1digit5);//Serial.println(digit6); + Serial.println(distance1,3); + Serial.print(dist2digit1);Serial.println(dist2digit2); //Serial.print(dist1digit3); Serial.print(dist1digit4);Serial.println(dist1digit5);//Serial.println(digit6); + Serial.println(distance2,3); + */ + } + else if (blinkON) { //set the new distance to count + blinkON = false; + rallyEdit = false; + /* + Serial.println(count1); + Serial.println(distance1,5); + Serial.println(""); + */ + if (CURSOR_POS == 1) { + distance1 = dist1digit1 + (float)dist1digit2/1000; + count1 = (unsigned long)(distance1 * Calibration) + 5; + //distance1 = (float)count1/((float)Calibration); + }else if (CURSOR_POS == 2) { + distance2 = dist2digit1 + (float)dist2digit2/1000; + count2 = (unsigned long)(distance2 * Calibration) + 5; + //distance2 = (float)count2/((float)Calibration); + } + /* + Serial.println(count1); + Serial.println(distance1,3); + */ + set_cursor_pos(CURSOR_POS); + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case ESC: + switch (MENU) + { + case RALLY: + lcd.noBlink(); + MENU=MAIN; + if (rallyEdit) { + rallyEdit = false; + lcd.blink(); + MENU = RALLY; + set_cursor_pos(CURSOR_POS); + } + blinkON=false; + + break; + case SETTIME: + lcd.noBlink(); + if (!blinkON) MENU = MAIN; + blinkON=false; + //MENU=MAIN; + break; + case CONSTANTA: + //MENU=MAIN; + if (!blinkON) MENU = MAIN; + else constantaMenu(); + lcd.noBlink(); + blinkON=false; + break; + case CALIBRATION: + lcd.noBlink(); + if (!blinkON) MENU = MAIN; + blinkON=false; + calibrationON=false; + //MENU=MAIN; + break; + + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + } + +//***************************************************************** +//*************************************** M E N U ***************** +// +// +// +//*************************************** M E N U ***************** +//***************************************************************** + + if (PREVMENU!=MENU) + { + switch (MENU) + { + case (MAIN): + mainMenu(); + break; + + case (RALLY): + lcd.clear(); + rallyMenu(); + rallyON=true; + //lcd.blink(); + CURSOR_POS=10; + set_cursor_pos(CURSOR_POS); + break; + + case (SETTIME): + lcd.clear(); + settimeMenu(); + sec60=t.sec; + min60=t.min; + hour24=t.hour; + lcd.setCursor(0,3); + lcdprint2digit(hour24); + lcd.print(":"); + lcdprint2digit(min60); + lcd.print(":"); + lcdprint2digit(sec60); + x=0; + y=2; + lcd.setCursor(x,y); + break; + + case (CALIBRATION): + calibrationMenu(); + break; + + case CONSTANTA: + sec60=starttractsec; + min60=starttractmin; + hour24=starttracthour; + x = 16; + y = 0; + constantaMenu(); + break; + + case (INPUTSUBTRAYEK): + break; + } + } + + if (MENU==RALLY) { + if ((now1 - prevtemprally) >= tempintervalrally) { + //if ((long)(now1 - prevtemprally) >= 0) { + //rallyMenu(); + if (!rallyEdit) redrawrallyMenu(); //Distance is edited? + prevtemprally=now1; + //prevtemprally+=tempintervalrally; + } + } + + if (MENU==SETTIME) { + //if ((long)(now1 - prevtempint) >=0 ){ + if ((now1 - prevtempint) >=tempinterval ){ + temperature = DS3231_get_treg(); //Get temperature + dtostrf(temperature, 5, 1, tempF); + lcd.setCursor(9,1); + lcd.print(tempF); + lcd.print((char)223); + lcd.print("C "); + //prevtempint+=tempinterval; + prevtempint=now1; + lcd.setCursor(x,y); + //lcd.setCursor(15,0); + //lcd.print(now); + } + //if ((long)(now1- prevsettime) >=0 ){ //show SET TIME MENU + if ((now1 - prevsettime) >=intervalsettime ){ //show SET TIME MENU + DS3231_get(&t); //Get time + if (prevsec!=t.sec) { //will update the LCD every sec(as long as the t.sec is different) eventhough intervalseetime is 250ms + settimeMenu(); + prevsettime = now1; + //prevsettime += intervalsettime; + } + } + } + + if (MENU==CALIBRATION) { + if (calibrationON) { + if ((now1 - prevcalibrationtime) >= calibrationtimeinterval ) { + //if ((long)(now1 - prevcalibrationtime) >=0 ) { + redrawcalibrationMenu(); + char Calibrationstr[6]; + unsigned long calibtemp = VSSCount - startCalibration; + sprintf(Calibrationstr, "%06lu", calibtemp); + lcd.setCursor(14,3); + lcd.print(Calibrationstr); + lcd.setCursor(x,y); + prevcalibrationtime=now1; + //prevcalibrationtime+=calibrationtimeinterval; + } + } + } + + //if (((long)(millis()-startmillis)>=0) && MENU!=CALIBRATION) { + if ((now1-startmillis)>=500) { //&& MENU!=CALIBRATION && MENU!=MAIN) { + unsigned long VSSCountDiff = VSSCount - startVSSCount; + startVSSCount=VSSCount; + if ((VSSCountDiff == 0) && savedCount) { + intervalsavemillis = 4000000; + } + else if ((VSSCountDiff == 0) && !savedCount) { + saveCount(); + savedCount = !savedCount; + intervalsavemillis = 2000000; + } + else if (VSSCountDiff < 15) intervalsavemillis = 3000; + else if (VSSCountDiff < 70) intervalsavemillis = 60000; + else intervalsavemillis = 4000000; + if (VSSCountDiff > 0) savedCount = false; + if (MENU!=CALIBRATION && MENU!=MAIN && MENU!=CONSTANTA) { + lcd.setCursor(0,0); + if (VSSCountDiff==0) lcd.print("0"); + else if (VSSCountDiff <= 10) lcd.print("1"); + else if (VSSCountDiff <= 50) lcd.print("2"); + else if (VSSCountDiff <= 150) lcd.print("3"); + else if (VSSCountDiff <= 250) lcd.print("4"); + else if (VSSCountDiff <= 400) lcd.print("5"); + else if (VSSCountDiff <= 600) lcd.print("6"); + else if (VSSCountDiff <= 900) lcd.print("7"); + else if (VSSCountDiff <= 1200) lcd.print("8"); + else if (VSSCountDiff > 1200) lcd.print("9"); + + //lcd.print(VSSCountDiff); + //lcd.print(" "); + lcd.setCursor(x,y); + } + //startmillis+=400; + startmillis=now1; + + } + +/* + if (((millis() % 100)==0) && MENU!=CALIBRATION) { + lcd.setCursor(0,2); + lcd.print(VSSCount); + lcd.print(" "); + lcd.setCursor(x,y); + } +*/ + if ((millis()-updatecounttime)>=250) { + updateCount(); + updatecounttime = millis(); + } + + if ((millis()-startsavemillis) > intervalsavemillis) { + saveCount(); + //startsavemillis += 3000; + startsavemillis = millis; + } +#ifdef DEBUG + Serial.print(micros()-prevtimemicros); Serial.println("**"); +#endif +} +void printUPchar() +{ + byte thumb1[8] = {B00100,B01110,B11111,B00100,B00100,B00100,B00100,B00100}; + lcd.createChar(1, thumb1); + //lcd.write(1); +} +void printDOWNchar() +{ + byte thumb1[8] = {B00100,B00100,B00100,B00100,B00100,B11111,B01110,B00100}; + lcd.createChar(2, thumb1); + //lcd.write(2); +} +void printMOVEchar() +{ + byte Movechar3[8] = {B00000,B00000,B00000,B00000,B00000,B00000,B00000,B11111}; + lcd.createChar(3, Movechar3); + byte Movechar4[8] = {B00000,B00000,B00000,B00000,B00000,B00000,B11111,B11111}; + lcd.createChar(4, Movechar4); + byte Movechar5[8] = {B00000,B00000,B00000,B00000,B00000,B11111,B11111,B11111}; + lcd.createChar(5, Movechar5); +} + + +void lcdprint2digit(byte val) +{ + if (val<10) lcd.print("0"); + lcd.print(val); +} +void setTheTime(char *cmd) +{ + // ssmmhhWDDMMYYYY set time + + t.sec = inp2toi(cmd, 0); + t.min = inp2toi(cmd, 2); + t.hour = inp2toi(cmd, 4); + t.wday = inp2toi(cmd, 6); + t.mday = inp2toi(cmd, 7); + t.mon = inp2toi(cmd, 9); + t.year = inp2toi(cmd, 11) * 100 + inp2toi(cmd, 13); + DS3231_set(t); +#ifdef DEBUG + Serial.println("OK setTheTime()"); +#endif +} + +void printMonth(int month) +{ + switch(month) + { + case 1: lcd.print(" January ");break; + case 2: lcd.print(" February ");break; + case 3: lcd.print(" March ");break; + case 4: lcd.print(" April ");break; + case 5: lcd.print(" May ");break; + case 6: lcd.print(" June ");break; + case 7: lcd.print(" July ");break; + case 8: lcd.print(" August ");break; + case 9: lcd.print(" September ");break; + case 10: lcd.print(" October ");break; + case 11: lcd.print(" November ");break; + case 12: lcd.print(" December ");break; + default: lcd.print(" Error ");break; + } +} + +void mainMenu() +{ + MENU = MAIN; + lcd.clear(); + lcd.print("1. Rally TSD"); + lcd.setCursor(0,1); + lcd.print("2. Set Main Time"); + lcd.setCursor(0,2); + lcd.print("3. Input Constanta"); + lcd.setCursor(0,3); + lcd.print("4. Calibration ODO"); + //lcd.home(); + x=2; + y=0; + lcd.cursor(); + lcd.setCursor(x,y); + PREVMENU = MENU; +} + +void settimeMenu() +{ + lcd.setCursor(0,0); + lcd.print(t.mday); + printMonth(t.mon); + lcd.print(t.year); + + runningtime(0,1); + + lcd.setCursor(x,y); + prevsec = t.sec; + PREVMENU = MENU; +} + +void runningtime(byte x1,byte y1) +{ + lcd.setCursor(x1,y1); //Go to second line of the LCD Screen + if(t.hour<10) + { + lcd.print("0"); + } + lcd.print(t.hour); + lcd.print(":"); + if(t.min<10) + { + lcd.print("0"); + } + lcd.print(t.min); + lcd.print(":"); + if(t.sec<10) + { + lcd.print("0"); + } + lcd.print(t.sec); +} +void calibrationMenu() +{ + MENU = CALIBRATION; + lcd.clear(); + lcd.print("Calibration Back"); + lcd.setCursor(0,1); + lcd.print("Set Distance(Km): "); + lcd.print(calibrationDistance); + lcd.setCursor(0,2); + lcd.print("Start 00.000Km"); + lcd.setCursor(0,3); + lcd.print("1m="); + lcd.print(((float)Calibration/1000),3); + char Calibrationstr[6]; + sprintf(Calibrationstr, "%06lu", Calibration); + lcd.setCursor(14,3); + lcd.print(Calibrationstr); + //lcd.setCursor(0,0); + //lcd.print(Calibration); + //lcd.home(); + x=18; + y=0; + lcd.setCursor(x,y); + lcd.cursor(); + //lcd.blink(); + //blinkON=true; + PREVMENU = MENU; +} + +void constantaMenu() +{ + MENU = CONSTANTA; + lcd.clear(); + lcd.print("Constanta Back"); + lcd.setCursor(0,1); + lcd.print("Sub Trip:"); + lcd.setCursor(14,1); + lcd.print(Trip[curTrip].sub); + lcd.setCursor(0,2); + lcd.print("Set Speed:"); + lcd.setCursor(13,2); + if (constanta<10) lcd.print("0"); + lcd.print(constanta,4); + //lcd.print( + lcd.setCursor(0,3); + lcd.print("Start Time:"); + //DS3231_get(&t); //Get time + lcd.setCursor(12,3); //Go to second line of the LCD Screen + if(starttracthour<10) + { + lcd.print("0"); + } + lcd.print(starttracthour); + lcd.print(":"); + if(starttractmin<10) + { + lcd.print("0"); + } + lcd.print(starttractmin); + lcd.print(":"); + if(starttractsec<10) + { + lcd.print("0"); + } + lcd.print(starttractsec); + lcd.print(""); + //x=14; + //y=0; + lcd.setCursor(x,y); + lcd.cursor(); + //lcd.blink(); + //blinkON=true; + PREVMENU = MENU; + +} +void updateCount() +{ + if (dircount1 == FORWARD) { + count1 = count1 + (VSSCount-time1); + } + else if (dircount1 == BACKWARD) { + count1 = count1 - (VSSCount-time1); + } + + if (dircount2 == FORWARD) { + count2 = count2 + (VSSCount-time2); + } + else if (dircount2 == BACKWARD) { + count2 = count2 - (VSSCount-time2); + } + time1 = VSSCount; + time2 = VSSCount; +} +void saveCount() +{ + if (count1 != prevcount1) { + count1Seq++; + memwritingLong(count1Address, RRcountSIZE, count1Seq, count1);//(int startaddress, byte RRsize, unsigned long seq, unsigned long Data) + prevcount1 = count1; + } + + if ((count1-count2) != count1count2diff) { +#ifdef DEBUG + Serial.print("count1=");Serial.print(count1);Serial.print(";count2=");Serial.print(count2);Serial.print("countdiff=");Serial.println(count1count2diff); +#endif + count1count2diff = count1-count2; + int pointer = count1count2diffAddress*32; + mem.writeLong(pointer,count1count2diff); +#ifdef DEBUG + Serial.println("save count1count2diff"); +#endif + } +} +void rallyMenu() +{ + MENU = RALLY; + + //lcd.clear(); + lcd.setCursor(15,0); + if (showTIME) lcd.print("Time "); + else lcd.print("TDiff"); + + secondrallyMenu(); + PREVMENU = MENU; +#ifdef DEBUG + Serial.println("rallyMenu"); +#endif +} + +void secondrallyMenu() +{ + char heading2[6]; + char heading4[6]; + lcd.setCursor(9,1); + //sprintf(heading2, "%s", (dirfwdcount1?"Fw":"Bw")); + sprintf(heading2, "%s", dircount[dircount1]); + lcd.print(heading2); + + lcd.setCursor(9,3); + //sprintf(heading4, "%s", (dirfwdcount2?"Fw":"Bw")); + sprintf(heading4, "%s", dircount[dircount2]); + lcd.print(heading4); +#ifdef DEBUG + Serial.println("secondrallyMenu"); +#endif +} + +unsigned long startspeed=0; +float startdistance=0; + +void redrawcalibrationMenu() +{ + float distance; + Calibrationcount = Calibrationcount + (VSSCount-Calibrationtime); + distance = (float)Calibrationcount/((float)Calibration); + char cur_distance_str[6]; + byte xtemp=13; + if (distance<100) { + sprintf(cur_distance_str, "%02d.%03dKm", (int)distance, (int)((distance - (int)distance)*1000)); + xtemp = 12; + } + else if (distance<1000) { + sprintf(cur_distance_str, "%02d.%02dKm", (int)distance, (int)((distance - (int)distance)*100)); + } + else { + sprintf(cur_distance_str, "%03d.%01dKm", (int)distance, (int)((distance - (int)distance)*10)); + } + Calibrationtime = VSSCount; + lcd.setCursor(xtemp,2); + lcd.print(cur_distance_str); +} +void redrawrallyMenu() +{ + DS3231_get(&t); //Get time + //runningtime(6,0); + //float distance, distance1, distance2; + + //Serial.print(tempcount1);Serial.print(";"); Serial.print(time1);Serial.print("; ");Serial.print(Calibration); Serial.print(";"); Serial.println(count1); + updateCount(); + + //distance = (float)count1/((float)Calibration); + distance1 = (float)count1/((float)Calibration); // * 1); + distance2 = (float)count2/((float)Calibration); + float speed1=0; + + if ((distance1 - startdistance) > 0) { + speed1 = (distance1-startdistance)/(millis()-startspeed)*3600000; + } + + startdistance = distance1; + startspeed = millis(); //startspeed is only one no startspeed2 + + if ((millis()-startsavemillis)>0) { + + if (distance1 != prevdistance1) { + mem.writeFloat(832,distance1); + prevdistance1 = distance1; + } + if (distance2 != prevdistance2) { + mem.writeFloat(864,distance2); + prevdistance2 = distance2; + } + saveCount(); + startsavemillis=millis()+2500; + } + //Serial.print(tempcount1);Serial.print(";"); Serial.print(time1);Serial.print("; ");Serial.print(Calibration); Serial.print(";"); Serial.println(count1); + + //Serial.print(millis());Serial.print(";");Serial.println(distance1,3); + //Serial.print(starttracthour); Serial.print(":"); Serial.print(starttractmin); Serial.print(":"); Serial.println(starttractsec); + //Serial.println(distance2,3); + lcd.setCursor(4,0); + lcd.print(Trip[curTrip].sub); + lcd.setCursor(0,2); + //lcd.print(T + lcd.print(Trip[curTrip].speed); + lcd.print("Km/H"); + + runningtime(6,0); + lcd.setCursor(11,2); + char cur_speed_str[8]; + sprintf(cur_speed_str, "%3d.%01dKm/h", (int)speed1, (int)((speed1 - (int)speed1)*10)); + lcd.print(cur_speed_str); + char cur_distance1_str[6]; + char cur_distance2_str[6]; + lcd.setCursor(0,1); + if (distance1<100) { + sprintf(cur_distance1_str, "%02d.%03dKm", (int)distance1, (int)((distance1 - (int)distance1)*1000)); + } + else if (distance1<1000) { + sprintf(cur_distance1_str, "%02d.%02dKm", (int)distance1, (int)((distance1 - (int)distance1)*100)); + } + else { + sprintf(cur_distance1_str, "%03d.%01dKm", (int)distance1, (int)((distance1 - (int)distance1)*10)); + } + //lcd.print(distance1,3); + lcd.print(cur_distance1_str); + lcd.setCursor(0,3); + if (distance2<100) { + sprintf(cur_distance2_str, "%02d.%03dKm", (int)distance2, (int)((distance2 - (int)distance2)*1000)); + } + else if (distance2<1000) { + sprintf(cur_distance2_str, "%02d.%02dKm", (int)distance2, (int)((distance2 - (int)distance2)*100)); + } + else { + sprintf(cur_distance2_str, "%03d.%01dKm", (int)distance2, (int)((distance2 - (int)distance2)*10)); + } + //lcd.print(distance2,3); + lcd.print(cur_distance2_str); + + float distancetime1 = distance1 * 60 / constanta; + float distancetime2 = distance2 * 60 / constanta; + +//Calculating all about TIME,TDiff(including passing 23:59:59) + lcd.setCursor(9,1); + int secs1, mins1, hours1; + + secs1 = (distancetime1-(int)distancetime1)*60; + mins1 = (int)distancetime1 % 60; + hours1 = (int)distancetime1 / 60; + unsigned long totcurrentsecs = t.sec + (t.min*60) + ((long)t.hour*3600); + unsigned long totsecs1 = secs1 + (mins1*60) + ((long)hours1*3600); + unsigned long totstarttractsecs = starttractsec + (starttractmin*60) + ((long)starttracthour*3600); + unsigned long tottime1 = totsecs1 + totstarttractsecs; + boolean negatifsign = false; + +//Serial.print((long)starttracthour*3600); Serial.print(";"); Serial.print(starttractmin*60); Serial.println(";"); +//Serial.print(totsecs1); Serial.print(";"); Serial.print(totstarttractsecs); Serial.print(";"); +//Serial.print(tottime1);Serial.print(";");Serial.println(totcurrentsecs); + if (totcurrentsecs=0) { //positif means we are too fast, slow down please. + if (tottime1 >= totcurrentsecs) { //positif means we are too fast, slow down please. + // Serial.println("pos"); + negatifsign = false; + tottime1 = tottime1 - totcurrentsecs; + } + else { //negatif means we need to hurry, its late + // Serial.println("neg"); + negatifsign = true; + tottime1 = totcurrentsecs - tottime1; + } + } + //Serial.print(negatifsign);Serial.print(";"); Serial.println(tottime1); + hours1 = ((int)(tottime1 / 3600))%24; + mins1 = (int)((tottime1 % 3600)/60); + secs1 = (tottime1 % 60); + + char cur_time1_str[10]; + if (showTIME) { + sprintf(cur_time1_str, "%s %02d:%02d:%02d", dircount[dircount1], hours1, mins1, secs1); + } + else { + if (hours1 < 10) sprintf(cur_time1_str, "%s %s%01d:%02d:%02d", dircount[dircount1], (negatifsign?"-":" "), hours1, mins1, secs1); + else sprintf(cur_time1_str, "%s%s%02d:%02d:%02d", dircount[dircount1], (negatifsign?"-":" "), hours1, mins1, secs1); + + } + lcd.print(cur_time1_str); + +// Print Second TIME + lcd.setCursor(9,3); + int secs2, mins2, hours2; + + secs2 = (distancetime2-(int)distancetime2)*60; + mins2 = (int)distancetime2 % 60; + hours2 = (int)distancetime2 / 60; + + unsigned long totsecs2 = secs2 + (mins2*60) + ((long)hours2*3600); + unsigned long tottime2 = totsecs2 + totstarttractsecs; +//Serial.println(tottime2); + + if (!showTIME) { + if (tottime2 >= totcurrentsecs) { //positif means we are too fast, slow down please. + negatifsign = false; + tottime2 = tottime2 - totcurrentsecs; + } + else { //negatif means we need to hurry, its late + negatifsign = true; + tottime2 = totcurrentsecs - tottime2 ; + } + } + + hours2 = ((int)(tottime2 / 3600))%24; + mins2 = (int)((tottime2 % 3600)/60); + secs2 = (tottime2 % 60); + char cur_time2_str[10]; + if (showTIME) { + sprintf(cur_time2_str, "%s %02d:%02d:%02d", dircount[dircount2], hours2, mins2, secs2); + } + else { + if (hours2<10) sprintf(cur_time2_str, "%s %s%01d:%02d:%02d", dircount[dircount2], (negatifsign?"-":" "), hours2, mins2, secs2); + else sprintf(cur_time2_str, "%s%s%02d:%02d:%02d", dircount[dircount2], (negatifsign?"-":" "), hours2, mins2, secs2); + } + //sprintf(cur_time2_str, "%s%02d:%02d:%02d", (dirfwdcount2?"Fw":"Bw"), hours2, mins2, secs2); + //sprintf(cur_time2_str, "%s %02d:%02d:%02d", dircount[dircount2], hours2, mins2, secs2); + lcd.print(cur_time2_str); +/* //may be needed to refresh if Km more than 10000Km + lcd.setCursor(8,3); + lcd.write(1); //UP Arrow + + lcd.setCursor(8,1); + lcd.write(2); //DOWN Arrow +*/ + lcd.setCursor(x,y); +} + +void set_cursor_pos(int new_pos) +{ + /* + Cursor Positon map: + ---------------------- + |Count1 TIME AvgSp| + |1 35 |7 9 | + |Count2 KmH| + |2 46 |8 10| + ---------------------- + */ + + //Need to clear the previous cursor position + //int x, y; + switch(CURSOR_POS) + { + case 1: + x = 0; + y = 1; + break; + case 2: + x = 0; + y = 3; + break; + case 3: + x = 8; //Km is 7,1 + y = 1; + break; + case 4: + x = 8; //Km is 7,3 + y = 3; + break; + case 5: + x = 9; + y = 1; + break; + case 6: + x = 9; + y = 3; + break; + case 7: + x = 13; + y = 1; + break; + case 8: + x = 13; + y = 3; + break; + case 9: + x = 18; + y = 1; + break; + case 10: + x = 18; + y = 3; + break; + } + lcd.print(" "); + lcd.blink(); + lcd.setCursor(8,3); + lcd.write(1); //UP Arrow + + lcd.setCursor(8,1); + lcd.write(2); //DOWN Arrow + + lcd.setCursor(x,y); + +/* + switch(new_pos) + { + case 1: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_RIGHT); + break; + case 2: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_RIGHT); + break; + case 3: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 4: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 5: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 6: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 7: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_LEFT); + break; + case 8: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_LEFT); + break; + } +*/ + + CURSOR_POS = new_pos; +#ifdef DEBUG + Serial.print("SetCursorPosition:"); + Serial.println(CURSOR_POS); +#endif +} diff --git a/backup/backup index before cleanup.h b/backup/backup index before cleanup.h new file mode 100644 index 0000000..f30392a --- /dev/null +++ b/backup/backup index before cleanup.h @@ -0,0 +1,413 @@ +const char MAIN_page[] PROGMEM = R"=====( + + + + + +
+

The ESP32 Update web page without refresh


+

Sensor Value:0


+

Sensor 2 Value:0


+

Sensor 3 Value:0


+

Time: 0


+
Circuits4you.com +
+ + + +)====="; + + +const char HTML_startrally1[] PROGMEM = R"rawliteral( + + Rally TerraTrip v1 + + + + + + + +
+
+
12345
+ +

TRIP A (123.4Km/h)

+

Time: 00:00:00

+

123.4Km/h

+
+
+ +
+

OD 1->

+

123.4567 km

+

DIRECT

+

00:00:00

+
+
+

+ +

+
+

+ + +

+
+

+
+ +

+
+
+
+ +
+

OD 2->123.456 km

+

DIRECT

+

00:00:00

+
+
+
+ +
+
+
+ + +
+
+

+
+ +
+

+
+ +
+ + + + + + + + +)rawliteral"; + +//HTML_CALIBRATION + + + +const char HTML_CALIBRATION[] PROGMEM = R"rawliteral( + + Rally TerraTrip v1 Calibration + + + + + + + +
+
+

12345

+

TRACK A

+

Time: 00:00:00

+

123.4Km/h

+
+
+ +
+

Set Distance (9 Km)->

+

+ + + +

+
+
+

Set Calibration Manually (110000)->

+

+ + + +

+
+
+

+ +

+
+

+ 00.000Km

+
+
+
+

1 meter=123.456

+

123456 Calibration Value

+
+ + +
+ + + +)rawliteral"; \ No newline at end of file diff --git a/backup/backup_main.cpp b/backup/backup_main.cpp new file mode 100644 index 0000000..4b16a0d --- /dev/null +++ b/backup/backup_main.cpp @@ -0,0 +1,677 @@ +/********* + Rui Santos + Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-input-data-html-form/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files. + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. +*********/ + +#include +#ifdef ESP32 + #include + #include + #include +#else + #include + #include + #include + #include +#endif +#include +//#include +#include +#include +#include +#include +//#include + +AsyncWebServer server(80); +AsyncWebSocket ws("/ws"); +AsyncWebSocket wscal("/wscal"); +//WiFiManager wifiManager; + +// REPLACE WITH YOUR NETWORK CREDENTIALS +char ssid[] = "WiFi_SuGi"; +char password[] = "12345678901"; + +//strcpy(ssid,"WiFi_SuGi"); + +//password = "1234567890"; + +const char *soft_ap_ssid = "MyESP32AP"; +const char *soft_ap_password = "testpassword"; + +const char* PARAM_STRING = "inputString"; +const char* PARAM_INT = "inputInt"; +const char* PARAM_FLOAT = "inputFloat"; + +const char* PARAM_SSID = "ssidString"; +const char* PARAM_PWD = "inputPwd"; + +const char* ntpServer = "pool.ntp.org"; +const long gmtOffset_sec = 7*3600; +const int daylightOffset_sec = 0; + + + +void notFound(AsyncWebServerRequest *request) { + request->send(404); +} + +String readFile(fs::FS &fs, const char * path){ + Serial.printf("Reading file: %s\r\n", path); + File file = fs.open(path, "r"); + if(!file || file.isDirectory()){ + Serial.println("- empty file or failed to open file"); + return String(); + } + Serial.print("- read from file:"); + String fileContent; + while(file.available()){ + fileContent+=String((char)file.read()); + } + file.close(); + Serial.println(fileContent); + return fileContent; +} + +void writeFile(fs::FS &fs, const char * path, const char * message){ + Serial.printf("Writing file: %s\r\n", path); + File file = fs.open(path, "w"); + if(!file){ + Serial.println("- failed to open file for writing"); + return; + } + if(file.print(message)){ + Serial.println("- file written"); + } else { + Serial.println("- write failed"); + } + file.close(); +} + +// Replaces placeholder with stored values +String processor(const String& var){ + //Serial.println(var); + Serial.print("Processor "); + Serial.print(var); + if(var == "inputString"){ + return readFile(SPIFFS, "/inputString.txt"); + } + else if(var == "inputInt"){ + return readFile(SPIFFS, "/inputInt.txt"); + } + else if(var == "inputFloat"){ + return readFile(SPIFFS, "/inputFloat.txt"); + } + else if(var == "ssidString"){ + return readFile(SPIFFS, "/ssidString.txt"); + } + else if(var == "localip"){ + return WiFi.localIP().toString(); + } + else if(var == "serveripaddress"){ + if (WiFi.localIP().toString()!="0.0.0.0"){ + Serial.println(WiFi.localIP()); + return WiFi.localIP().toString(); + } else { + Serial.println(WiFi.softAPIP()); + return WiFi.softAPIP().toString(); + } + } + // else if(var == "inputPwd"){ + // return readFile(SPIFFS, "/inputPwd.txt"); + // } + return String(); +} + + + + +void OnWiFiEvent(WiFiEvent_t event) +{ + switch (event) { + + case SYSTEM_EVENT_STA_CONNECTED: + Serial.println("ESP32 Connected to WiFi Network"); + break; + case SYSTEM_EVENT_AP_START: + Serial.println("ESP32 soft AP started"); + break; + case SYSTEM_EVENT_AP_STACONNECTED: + Serial.println("Station connected to ESP32 soft AP"); + break; + case SYSTEM_EVENT_AP_STADISCONNECTED: + Serial.println("Station disconnected from ESP32 soft AP"); + break; + default: break; + } +} +String getPin(){ + struct tm timeinfo; + String hasil; + if(!getLocalTime(&timeinfo)){ + Serial.println("Failed to obtain time"); + return hasil; + } + // StaticJsonBuffer<200> jsonBuffer; + // JsonObject& root = JsonBuffer.createObject(); + DynamicJsonDocument testdoc(512); + //String datetime = &timeinfo; + char datetime[21]; + char time[9]; + strftime(datetime, 21, "%d %b %Y %H:%M:%S", &timeinfo); + strftime(time, 9, "%H:%M:%S", &timeinfo); + //Serial.println(&timeinfo); + //Serial.println(datetime); + testdoc["pin36"]=242; + testdoc["pin39"]=datetime; + testdoc["time"]=time; + // testdoc["datetime"]=datetime; + testdoc["pin5"]=millis(); + testdoc["curtime"]=time; + testdoc["speed"]=String(float(random(1,20000))/100,1); + testdoc["counter"]=random(0,50000); + String bb[]={"A","B","C","D","E","F","G","H","I","J","K","L"}; + testdoc["curtrack"]=bb[random(12)]; + String dir[]={"FW","STOP","BACK"}; + testdoc["dir1"]=dir[random(3)]; + testdoc["dir2"]=dir[random(3)]; + testdoc["time1"]=time; + testdoc["time2"]=time; + float odo1=float(millis())/10000; + float odo2=float(millis())/20000; + //Serial.println(odo1,3); + testdoc["odo1"]=String(odo1,3); + testdoc["odo2"]=String(odo2,3); // if disabled, the web will get undefined value + //serializeJson(testdoc,Serial); + serializeJson(testdoc,hasil); + //testdoc.printTo(hasil); + // testdoc.clear(); + return hasil; +} +String getCalib(){ + struct tm timeinfo; + String hasil; + if(!getLocalTime(&timeinfo)){ + Serial.println("Failed to obtain time"); + return hasil; + } + DynamicJsonDocument testdoc(200); + //String datetime = &timeinfo; + char datetime[21]; + char time[9]; + strftime(datetime, 21, "%d %b %Y %H:%M:%S", &timeinfo); + strftime(time, 9, "%H:%M:%S", &timeinfo); + //Serial.println(&timeinfo); + //Serial.println(datetime); + // testdoc["datetime"]=datetime; + testdoc["curtime"]=time; + testdoc["speed"]=String(float(random(1,20000))/100,1); + testdoc["counter"]=random(0,50000); + String bb[]={"A","B","C","D","E","F","G","H","I","J","K","L"}; + testdoc["curtrack"]=bb[random(12)]; + float calkm=float(millis())/100000; + float calmeter=float(millis())/100; + testdoc["caldist"]=random(9); + testdoc["calman"]=random(100000, 150000); + testdoc["calkm"]=String(calkm,3); + testdoc["calmeter"]=String(calmeter,3); + //Serial.println(odo1,3); + testdoc["calval"]=String(calmeter*1000); // if disabled, the web will get undefined value + //serializeJson(testdoc,Serial); + serializeJson(testdoc,hasil); + //testdoc.printTo(hasil); + // testdoc.clear(); + return hasil; +} + +void printLocalTime(){ + struct tm timeinfo; + if(!getLocalTime(&timeinfo)){ + Serial.println("Failed to obtain time"); + return; + } + Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S"); + Serial.print("Day of week: "); + Serial.println(&timeinfo, "%A"); + Serial.print("Month: "); + Serial.println(&timeinfo, "%B"); + Serial.print("Day of Month: "); + Serial.println(&timeinfo, "%d"); + Serial.print("Year: "); + Serial.println(&timeinfo, "%Y"); + Serial.print("Hour: "); + Serial.println(&timeinfo, "%H"); + Serial.print("Hour (12 hour format): "); + Serial.println(&timeinfo, "%I"); + Serial.print("Minute: "); + Serial.println(&timeinfo, "%M"); + Serial.print("Second: "); + Serial.println(&timeinfo, "%S"); + + Serial.println("Time variables"); + char timeHour[3]; + strftime(timeHour,3, "%H", &timeinfo); + Serial.println(timeHour); + char timeWeekDay[10]; + strftime(timeWeekDay,10, "%A", &timeinfo); + Serial.println(timeWeekDay); + Serial.println(); +} + +boolean isDecimal(String str){ +for(byte i=0;iremoteIP()); + client->text(getPin()); + } else if(type == WS_EVT_DISCONNECT){ + Serial.println("Client disconnected"); + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + } else if(type == WS_EVT_DATA){ + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + Serial.printf("[%u] get Text: %s\n", len, data); + String message = String((char*)( data)); + Serial.println(message); + + DynamicJsonDocument doc(256); + // Deserialize the data + DeserializationError error = deserializeJson(doc, message); + // parse the parameters we expect to receive (TO-DO: error handling) + // test if parsing succeeds + if (error){ + Serial.print("deserialiseJson() failed: "); + Serial.println(error.c_str()); + client->text(error.c_str()); + return; + } + String ledstatus=doc["LED1"]; + if (ledstatus=="null"){Serial.println("led1 is null");} + Serial.print("LED1=");Serial.println(ledstatus); + } +} + +void onWsEvent2(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){ + if(type == WS_EVT_CONNECT){ + Serial.println("wscal Websocket client connection received"); + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + client->text(getCalib()); + } else if(type == WS_EVT_DISCONNECT){ + Serial.println("wscal Client disconnected"); + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + } else if(type == WS_EVT_DATA){ + Serial.print("wscal IPAdd client:"); Serial.println(client->remoteIP()); + Serial.printf("[%u] get Text: %s\n", len, data); + String message = String((char*)( data)); + Serial.println(message); + + DynamicJsonDocument doc(200); + // Deserialize the data + DeserializationError error = deserializeJson(doc, message); + // parse the parameters we expect to receive (TO-DO: error handling) + // test if parsing succeeds + if (error){ + Serial.print("wscal deserialiseJson() failed: "); + Serial.println(error.c_str()); + client->text(error.c_str()); + return; + } + String setdis=doc["setdis"]; + String setcal=doc["setcal"]; + String calstart=doc["calstart"]; + Serial.print("setdis=");Serial.println(setdis); + Serial.print("setcal=");Serial.println(setcal); + Serial.print("calstart=");Serial.println(calstart); + if (setdis!="null"){ + if (isDecimal(setdis)){ + Serial.print("setdis=");Serial.println(setdis.toInt()); + } + } + if (setcal!="null"){ + if (isDecimal(setcal)){ + Serial.print("setcal=");Serial.println(setcal.toInt()); + } + } + if (calstart="null"){ + if (isDecimal(calstart)){ + if(calstart=="1"){ + Serial.print("calstart=");Serial.println("START"); + } else if(calstart=="0"){ + + } + Serial.print("calstart=");Serial.println("STOP"); + } + } + } +} + +// void configModeCallback (WiFiManager *myWiFiManager) { +// Serial.println("Entered config mode"); +// Serial.println(WiFi.softAPIP()); + +// Serial.println(myWiFiManager->getConfigPortalSSID()); +// } + +void setup() { + Serial.begin(115200); + DynamicJsonDocument doc(512); + // Initialize SPIFFS + #ifdef ESP32 + if(!SPIFFS.begin(true)){ + Serial.println("An Error has occurred while mounting SPIFFS"); + return; + } + #else + if(!SPIFFS.begin()){ + Serial.println("An Error has occurred while mounting SPIFFS"); + return; + } + #endif + // wifiManager.setAPCallback(configModeCallback); + // wifiManager.autoConnect(soft_ap_ssid); + + WiFi.onEvent(OnWiFiEvent); + //WiFi.mode(WIFI_STA); + WiFi.mode(WIFI_MODE_APSTA); + + WiFi.softAP(soft_ap_ssid, soft_ap_password); + + String yourSSIDString = readFile(SPIFFS, "/ssidString.txt"); + Serial.print("*** Your ssidString: "); + Serial.println(yourSSIDString); + Serial.println(ssid); + if (yourSSIDString != ""){ + strncpy(ssid, yourSSIDString.c_str() , (sizeof ssid)-1); + } + + Serial.println(ssid); + String yourInputPwd = readFile(SPIFFS, "/inputPwd.txt"); + Serial.print("*** Your inputPwd: "); + Serial.println(yourInputPwd); + if (yourInputPwd != ""){ + strncpy(password, yourInputPwd.c_str() , (sizeof password)-1); + } + + WiFi.begin(ssid, password); + if (WiFi.waitForConnectResult() != WL_CONNECTED) { + Serial.println("WiFi Failed!"); + //return; + } + + Serial.print("ESP32 IP as soft AP: "); + Serial.println(WiFi.softAPIP()); + + Serial.println(); + Serial.print("IP Address: "); + Serial.println(WiFi.localIP()); + + // Init and get the time + configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); + printLocalTime(); + + // Send web page with input fields to client + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ + if (ON_STA_FILTER(request)) { + //request->send(200, "text/plain", "Hello from STA"); + request->send_P(200, "text/html", main_menu, processor); + return; + + } else if (ON_AP_FILTER(request)) { + //request->send(200, "text/plain", "Hello from AP"); + Serial.println("on apfilter /"); + request->send_P(200, "text/html", wifi_html, processor); + return; + } + + }); + + server.on("/wifi", HTTP_GET, [](AsyncWebServerRequest * request) { + + if (ON_STA_FILTER(request)) { + //request->send(200, "text/plain", "Hello from STA"); + request->send_P(200, "text/html", wifi_html, processor); + return; + + } else if (ON_AP_FILTER(request)) { + //request->send(200, "text/plain", "Hello from AP"); + Serial.println("on apfilter /wifi"); + request->send_P(200, "text/html", wifi_html, processor); + return; + } + + request->send(200, "text/plain", "Hello from undefined"); +}); + + + + // Send a GET request to /get?inputString= + server.on("/setwifi", HTTP_POST, [] (AsyncWebServerRequest *request) { + String inputMessage; + boolean bolrestart=false; + Serial.println("ini masuk /setwifi"); + // GET inputString value on /get?inputString= + //List all parameters + int params = request->params(); + for(int i=0;igetParam(i); + if(p->isFile()){ //p->isPost() is also true + Serial.printf("FILE[%s]: %s, size: %u\n", p->name().c_str(), p->value().c_str(), p->size()); + } else if(p->isPost()){ + Serial.printf("POST[%s]: %s\n", p->name().c_str(), p->value().c_str()); + } else { + Serial.printf("GET[%s]: %s\n", p->name().c_str(), p->value().c_str()); + } + } + if (request->hasParam(PARAM_SSID,true)) { + Serial.println("hasparam ssid"); + inputMessage = request->getParam(PARAM_SSID,true)->value(); //add true for POST method. no true for GET method + if (inputMessage!=""){ + writeFile(SPIFFS, "/ssidString.txt", inputMessage.c_str()); + delay(50); + bolrestart=true; + //ESP.restart(); + } + } + // GET inputPwd value on /wifi/get?inputPwd= + if (request->hasParam(PARAM_PWD,true)) { // add true for POST, no true for GET method + Serial.println("hasparam pwd"); + inputMessage = request->getParam(PARAM_PWD,true)->value(); // add true for POST + if (inputMessage!=""){ + writeFile(SPIFFS, "/inputPwd.txt", inputMessage.c_str()); + delay(50); + bolrestart=true; + //ESP.restart(); + } + } + else { + inputMessage = "No message sent"; + } + if (bolrestart) { + ESP.restart(); + } + Serial.println("ini /setwifi aja");Serial.println(inputMessage); + request->send(200, "text/text", inputMessage); + }); + + // // Send a GET request to /wifi/get?ssidString= + // server.on("/wifi/get", HTTP_GET, [] (AsyncWebServerRequest *request) { + // String inputMessage; + // // GET ssidString value on /wifi/get?ssidString= + // Serial.println("ini masuk wifi get"); + // Serial.println(request->params()); + // if (request->hasParam(PARAM_SSID)) { + // inputMessage = request->getParam(PARAM_SSID)->value(); + // writeFile(SPIFFS, "/ssidString.txt", inputMessage.c_str()); + // delay(100); + // ESP.restart(); + // } + // // GET inputPwd value on /wifi/get?inputPwd= + // else if (request->hasParam(PARAM_PWD)) { + // inputMessage = request->getParam(PARAM_PWD)->value(); + // writeFile(SPIFFS, "/inputPwd.txt", inputMessage.c_str()); + // delay(100); + // ESP.restart(); + // } + // else { + // inputMessage = "No message sent"; + // } + // Serial.println("/wifi/get value:"); Serial.println(inputMessage); + // request->send(200, "text/text", inputMessage); + // }); + + server.on("/menu", HTTP_GET, [] (AsyncWebServerRequest *request) { + //String s = MAIN_page; //Read HTML contents + //request->send_P(200, "text/html", s); //Send web page + request->send_P(200, "text/html", main_menu); + }); + + server.on("/startrally", HTTP_GET, [] (AsyncWebServerRequest *request) { + //String s = MAIN_page; //Read HTML contents + //request->send_P(200, "text/html", s); //Send web page + String PAGE; + PAGE += FPSTR(HTML_PAGEHEADER); + PAGE.replace("%serveripaddress%", WiFi.localIP().toString()); + PAGE += FPSTR(HTML_DIVSTARTRALLY); + //PAGE += FPSTR(HTML_SCRIPTSETINTERVAL); + //PAGE += FPSTR(HTML_SCRIPTGETDATA); + PAGE += FPSTR(HTML_END); + //Serial.println(PAGE); + request->send(200, "text/html", PAGE); + }); + + server.on("/startrally1", HTTP_GET, [] (AsyncWebServerRequest *request) { + request->send_P(200, "text/html", HTML_startrally1, processor); + }); + + server.on("/resetodo1", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("ODORESET 1"); + request->redirect("/startrally1"); + }); + + server.on("/resetodo2", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("ODORESET 22222"); + request->redirect("/startrally1"); + }); + + server.on("/copytoodo2", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("COPY ODO 1 to 2"); + request->redirect("/startrally1"); + }); + + server.on("/copytoodo1", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("COPY ODO 2 to 1"); + request->redirect("/startrally1"); + }); + server.on("/DIR", HTTP_GET, [] (AsyncWebServerRequest *request) { + String inputMessage; + String inputParam; + if (request->hasParam("DIR1")){ + inputMessage=request->getParam("DIR1")->value(); + Serial.print("DIR 1->");Serial.println(inputMessage); + switch(inputMessage[0]){ + case 'F': + Serial.println("FW1"); + break; + case 'S': + Serial.println("ST1"); + break; + case 'B': + Serial.println("BACK1"); + break; + default: + Serial.println("Default VAL1"); + } + } + else if (request->hasParam("DIR2")){ + inputMessage=request->getParam("DIR2")->value(); + Serial.print("DIR 2->");Serial.println(inputMessage); + switch(inputMessage[0]){ + case 'F': + Serial.println("FW2"); + break; + case 'S': + Serial.println("ST2"); + break; + case 'B': + Serial.println("BACK2"); + break; + default: + Serial.println("Default VAL2"); + } + } + request->redirect("/startrally1"); + }); + + + server.on("/TG1", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("TOGGLE 1"); + request->redirect("/startrally1"); + }); + + server.on("/TG2", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("TOGGLE 2"); + request->redirect("/startrally1"); + }); +// //server.on("/adc", HTTP_GET); //This is display page +// server.on("/readADC", HTTP_GET, [] (AsyncWebServerRequest *request) { +// // int a = analogRead(A0); +// // String adcValue = String(millis()); +// String adcValue = getPin(); +// Serial.println(adcValue); +// request->send_P(200, "text/plain", adcValue.c_str()); //Send ADC value only to client ajax request +// }); + + server.on("/calibration", HTTP_GET, [] (AsyncWebServerRequest *request) { + //PAGE.replace("%serveripaddress%", WiFi.localIP().toString()); + request->send_P(200, "text/html", HTML_CALIBRATION, processor); + }); + + ws.onEvent(onWsEvent); //add ws event + wscal.onEvent(onWsEvent2); //add ws event + server.addHandler(&ws); + server.addHandler(&wscal); + + server.onNotFound(notFound); + server.begin(); +} + +void loop() { + // // To access your stored values on inputString, inputInt, inputFloat + // String yourInputString = readFile(SPIFFS, "/inputString.txt"); + // Serial.print("*** Your inputString: "); + // Serial.println(yourInputString); + + // int yourInputInt = readFile(SPIFFS, "/inputInt.txt").toInt(); + // Serial.print("*** Your inputInt: "); + // Serial.println(yourInputInt); + + // float yourInputFloat = readFile(SPIFFS, "/inputFloat.txt").toFloat(); + // Serial.print("*** Your inputFloat: "); + // Serial.println(yourInputFloat); + + // String yourSSIDString = readFile(SPIFFS, "/ssidString.txt"); + // Serial.print("*** Your ssidString: "); + // Serial.println(yourSSIDString); + + // String yourInputPwd = readFile(SPIFFS, "/inputPwd.txt"); + // Serial.print("*** Your inputPwd: "); + // Serial.println(yourInputPwd); + // delay(10000); + delay(10330); + ws.textAll(getPin()); + wscal.textAll(getCalib()); + //printLocalTime(); +} + diff --git a/backup/backup_main_before cleaning lcd and at24cx b/backup/backup_main_before cleaning lcd and at24cx new file mode 100644 index 0000000..3f026e8 --- /dev/null +++ b/backup/backup_main_before cleaning lcd and at24cx @@ -0,0 +1,2844 @@ +/********* + Rui Santos + Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-input-data-html-form/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files. + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. +*********/ + +#include +#ifdef ESP32 + #include + #include + #include +#else + #include + #include + #include + #include +#endif +#include +//#include +#include +#include +#include +#include +//#include + +AsyncWebServer server(80); +AsyncWebSocket ws("/ws"); +AsyncWebSocket wscal("/wscal"); +//WiFiManager wifiManager; + +// REPLACE WITH YOUR NETWORK CREDENTIALS +char ssid[] = "WiFi_SuGi"; +char password[] = "12345678901"; + +//strcpy(ssid,"WiFi_SuGi"); + +//password = "1234567890"; + +const char *soft_ap_ssid = "MyESP32AP"; +const char *soft_ap_password = "testpassword"; + +const char* PARAM_STRING = "inputString"; +const char* PARAM_INT = "inputInt"; +const char* PARAM_FLOAT = "inputFloat"; + +const char* PARAM_SSID = "ssidString"; +const char* PARAM_PWD = "inputPwd"; + +const char* ntpServer = "pool.ntp.org"; +const long gmtOffset_sec = 7*3600; +const int daylightOffset_sec = 0; + + + +void notFound(AsyncWebServerRequest *request) { + request->send(404); +} + +String readFile(fs::FS &fs, const char * path){ + Serial.printf("Reading file: %s\r\n", path); + File file = fs.open(path, "r"); + if(!file || file.isDirectory()){ + Serial.println("- empty file or failed to open file"); + return String(); + } + Serial.print("- read from file:"); + String fileContent; + while(file.available()){ + fileContent+=String((char)file.read()); + } + file.close(); + Serial.println(fileContent); + return fileContent; +} + +void writeFile(fs::FS &fs, const char * path, const char * message){ + Serial.printf("Writing file: %s\r\n", path); + File file = fs.open(path, "w"); + if(!file){ + Serial.println("- failed to open file for writing"); + return; + } + if(file.print(message)){ + Serial.println("- file written"); + } else { + Serial.println("- write failed"); + } + file.close(); +} + +// Replaces placeholder with stored values +String processor(const String& var){ + //Serial.println(var); + Serial.print("Processor "); + Serial.print(var); + if(var == "inputString"){ + return readFile(SPIFFS, "/inputString.txt"); + } + else if(var == "inputInt"){ + return readFile(SPIFFS, "/inputInt.txt"); + } + else if(var == "inputFloat"){ + return readFile(SPIFFS, "/inputFloat.txt"); + } + else if(var == "ssidString"){ + return readFile(SPIFFS, "/ssidString.txt"); + } + else if(var == "localip"){ + return WiFi.localIP().toString(); + } + else if(var == "serveripaddress"){ + if (WiFi.localIP().toString()!="0.0.0.0"){ + Serial.println(WiFi.localIP()); + return WiFi.localIP().toString(); + } else { + Serial.println(WiFi.softAPIP()); + return WiFi.softAPIP().toString(); + } + } + // else if(var == "inputPwd"){ + // return readFile(SPIFFS, "/inputPwd.txt"); + // } + return String(); +} + + + + +void OnWiFiEvent(WiFiEvent_t event) +{ + switch (event) { + + case SYSTEM_EVENT_STA_CONNECTED: + Serial.println("ESP32 Connected to WiFi Network"); + break; + case SYSTEM_EVENT_AP_START: + Serial.println("ESP32 soft AP started"); + break; + case SYSTEM_EVENT_AP_STACONNECTED: + Serial.println("Station connected to ESP32 soft AP"); + break; + case SYSTEM_EVENT_AP_STADISCONNECTED: + Serial.println("Station disconnected from ESP32 soft AP"); + break; + default: break; + } +} +String getPin(){ + struct tm timeinfo; + String hasil; + if(!getLocalTime(&timeinfo)){ + Serial.println("Failed to obtain time"); + return hasil; + } + // StaticJsonBuffer<200> jsonBuffer; + // JsonObject& root = JsonBuffer.createObject(); + DynamicJsonDocument testdoc(512); + //String datetime = &timeinfo; + char datetime[21]; + char curtime[9]; + strftime(datetime, 21, "%d %b %Y %H:%M:%S", &timeinfo); + strftime(curtime, 9, "%H:%M:%S", &timeinfo); + //Serial.println(&timeinfo); + //Serial.println(datetime); + testdoc["pin36"]=242; + testdoc["pin39"]=datetime; + testdoc["time"]=curtime; + // testdoc["datetime"]=datetime; + testdoc["pin5"]=millis(); + testdoc["curtime"]=curtime; + testdoc["speed"]=String(float(random(1,20000))/100,1); + testdoc["counter"]=random(0,50000); + String bb[]={"A","B","C","D","E","F","G","H","I","J","K","L"}; + testdoc["curtrack"]=bb[random(12)]; + String dir[]={"FW","STOP","BACK"}; + testdoc["dir1"]=dir[random(3)]; + testdoc["dir2"]=dir[random(3)]; + testdoc["time1"]=curtime; + testdoc["time2"]=curtime; + float odo1=float(millis())/10000; + float odo2=float(millis())/20000; + //Serial.println(odo1,3); + testdoc["odo1"]=String(odo1,3); + testdoc["odo2"]=String(odo2,3); // if disabled, the web will get undefined value + //serializeJson(testdoc,Serial); + serializeJson(testdoc,hasil); + //testdoc.printTo(hasil); + // testdoc.clear(); + return hasil; +} +String getCalib(){ + struct tm timeinfo; + String hasil; + if(!getLocalTime(&timeinfo)){ + Serial.println("Failed to obtain time"); + return hasil; + } + DynamicJsonDocument testdoc(200); + //String datetime = &timeinfo; + char datetime[21]; + char curtime[9]; + strftime(datetime, 21, "%d %b %Y %H:%M:%S", &timeinfo); + strftime(curtime, 9, "%H:%M:%S", &timeinfo); + //Serial.println(&timeinfo); + //Serial.println(datetime); + // testdoc["datetime"]=datetime; + testdoc["curtime"]=curtime; + testdoc["speed"]=String(float(random(1,20000))/100,1); + testdoc["counter"]=random(0,50000); + String bb[]={"A","B","C","D","E","F","G","H","I","J","K","L"}; + testdoc["curtrack"]=bb[random(12)]; + float calkm=float(millis())/100000; + float calmeter=float(millis())/100; + testdoc["caldist"]=random(9); + testdoc["calman"]=random(100000, 150000); + testdoc["calkm"]=String(calkm,3); + testdoc["calmeter"]=String(calmeter,3); + //Serial.println(odo1,3); + testdoc["calval"]=String(calmeter*1000); // if disabled, the web will get undefined value + //serializeJson(testdoc,Serial); + serializeJson(testdoc,hasil); + //testdoc.printTo(hasil); + // testdoc.clear(); + return hasil; +} + +void printLocalTime(){ + struct tm timeinfo; + if(!getLocalTime(&timeinfo)){ + Serial.println("Failed to obtain time"); + return; + } + Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S"); + Serial.print("Day of week: "); + Serial.println(&timeinfo, "%A"); + Serial.print("Month: "); + Serial.println(&timeinfo, "%B"); + Serial.print("Day of Month: "); + Serial.println(&timeinfo, "%d"); + Serial.print("Year: "); + Serial.println(&timeinfo, "%Y"); + Serial.print("Hour: "); + Serial.println(&timeinfo, "%H"); + Serial.print("Hour (12 hour format): "); + Serial.println(&timeinfo, "%I"); + Serial.print("Minute: "); + Serial.println(&timeinfo, "%M"); + Serial.print("Second: "); + Serial.println(&timeinfo, "%S"); + + Serial.println("Time variables"); + char timeHour[3]; + strftime(timeHour,3, "%H", &timeinfo); + Serial.println(timeHour); + char timeWeekDay[10]; + strftime(timeWeekDay,10, "%A", &timeinfo); + Serial.println(timeWeekDay); + Serial.println(); +} + +boolean isDecimal(String str){ +for(byte i=0;iremoteIP()); + client->text(getPin()); + } else if(type == WS_EVT_DISCONNECT){ + Serial.println("Client disconnected"); + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + } else if(type == WS_EVT_DATA){ + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + Serial.printf("[%u] get Text: %s\n", len, data); + String message = String((char*)( data)); + Serial.println(message); + + DynamicJsonDocument doc(256); + // Deserialize the data + DeserializationError error = deserializeJson(doc, message); + // parse the parameters we expect to receive (TO-DO: error handling) + // test if parsing succeeds + if (error){ + Serial.print("deserialiseJson() failed: "); + Serial.println(error.c_str()); + client->text(error.c_str()); + return; + } + String ledstatus=doc["LED1"]; + if (ledstatus=="null"){Serial.println("led1 is null");} + Serial.print("LED1=");Serial.println(ledstatus); + } +} + +void onWsEvent2(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){ + if(type == WS_EVT_CONNECT){ + Serial.println("wscal Websocket client connection received"); + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + client->text(getCalib()); + } else if(type == WS_EVT_DISCONNECT){ + Serial.println("wscal Client disconnected"); + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + } else if(type == WS_EVT_DATA){ + Serial.print("wscal IPAdd client:"); Serial.println(client->remoteIP()); + Serial.printf("[%u] get Text: %s\n", len, data); + String message = String((char*)( data)); + Serial.println(message); + + DynamicJsonDocument doc(200); + // Deserialize the data + DeserializationError error = deserializeJson(doc, message); + // parse the parameters we expect to receive (TO-DO: error handling) + // test if parsing succeeds + if (error){ + Serial.print("wscal deserialiseJson() failed: "); + Serial.println(error.c_str()); + client->text(error.c_str()); + return; + } + String setdis=doc["setdis"]; + String setcal=doc["setcal"]; + String calstart=doc["calstart"]; + Serial.print("setdis=");Serial.println(setdis); + Serial.print("setcal=");Serial.println(setcal); + Serial.print("calstart=");Serial.println(calstart); + if (setdis!="null"){ + if (isDecimal(setdis)){ + Serial.print("setdis=");Serial.println(setdis.toInt()); + } + } + if (setcal!="null"){ + if (isDecimal(setcal)){ + Serial.print("setcal=");Serial.println(setcal.toInt()); + } + } + if (calstart="null"){ + if (isDecimal(calstart)){ + if(calstart=="1"){ + Serial.print("calstart=");Serial.println("START"); + } else if(calstart=="0"){ + + } + Serial.print("calstart=");Serial.println("STOP"); + } + } + } +} + +// void configModeCallback (WiFiManager *myWiFiManager) { +// Serial.println("Entered config mode"); +// Serial.println(WiFi.softAPIP()); + +// Serial.println(myWiFiManager->getConfigPortalSSID()); +// } + + + +////// VSSRALLYMODULE +// +// +// +// +// +// +// +// +// +#ifndef min +#define min(a,b) (((a) < (b)) ? (a) : (b)) +#endif +#ifndef max +#define max(a,b) (((a) > (b)) ? (a) : (b)) +#endif + +#include +#include +#include +#include + +//#define BUFF_MAX 128 + +//****************************************Define I2C LCD Display ********************************* +#define I2C_ADDR 0x27 // Define I2C Address for the PCF8574T +//---(Following are the PCF8574 pin assignments to LCD connections )---- +// This are different than earlier/different I2C LCD displays + +#define Rs_pin 0 +#define Rw_pin 1 +#define En_pin 2 +#define BACKLIGHT_PIN 3 +#define D4_pin 4 +#define D5_pin 5 +#define D6_pin 6 +#define D7_pin 7 +#define UP_pin 4 +#define DOWN_pin 5 +#define LEFT_pin 6 +#define RIGHT_pin 7 +#define OK_pin 8 + +#define ATMEGA328 //comment out this line if it is not ATMEGA328 +//#define DEBUG //comment out this line to disable for Production(No Serial print) + +#define RRcountSIZE 20 +#define count1Address 0 +#define count1count2diffAddress 40 //only one address which is 40*32 +//int count1Address = 0; +//int count1count2diffAddress = 40; +long count1count2diff = 0; + +#define TRIPSIZE 12 //so thestartaddress is 50*32 until (50+12)*32 +#define TRIPADDRESS 50 + +const byte interruptPin = 2; +const byte ledPin = 13; + +#ifndef ATMEGA328 + volatile byte ledstate = LOW; +#endif + +#define LED_OFF 0 +#define LED_ON 1 + +// set the LCD number of columns and rows +const int lcdColumns = 20; +const int lcdRows = 4; + +// set LCD address, number of columns and rows +// if you don't know your display address, run an I2C scanner sketch +LiquidCrystal_I2C lcd(I2C_ADDR, lcdColumns, lcdRows); + +/*-----( Declare objects )-----*/ +//LiquidCrystal_I2C lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin); +AT24CX mem; +boolean cursorON=true; +boolean blinkON=true; +//************************************ END LCD DISPLAY ******************************************* + +uint8_t thistime[8]; +//char recv[BUFF_MAX]; +unsigned int recv_size = 0; +unsigned long prevsettime, intervalsettime = 250; +unsigned long prevtempint, tempinterval=60000; +unsigned long prevtemprally, tempintervalrally=200; +unsigned long prevcalibrationtime, calibrationtimeinterval = 100; +unsigned long updatecounttime=0; +float temperature; +volatile byte x; +volatile byte y; +// #ifndef y++ +// //#define min(a,b) (((a) < (b)) ? (a) : (b)) +// #define y++ y+1 +// #endif +// #ifndef x++ +// //#define min(a,b) (((a) < (b)) ? (a) : (b)) +// #define x++ x+1 +// #endif + +unsigned long startmillis, startVSSCount; +unsigned long startsavemillis; +unsigned long broadcastwebsocket; + +//#include //https://github.com/JChristensen/Button //from change to +#include + +#define DN_PIN 5 //Connect two tactile button switches (or something similar) +#define UP_PIN 4 //from Arduino pin 2 to ground and from pin 3 to ground. +#define LF_PIN 6 +#define RF_PIN 7 +#define OK_PIN 8 +#define ESC_PIN 10 +#define PULLUPRES true //To keep things simple, we use the Arduino's internal PULLUPRES resistor. +#define INVERT true //Since the pullup resistor will keep the pin high unless the + //switch is closed, this is negative logic, i.e. a high state + //means the button is NOT pressed. (Assuming a normally open switch.) +#define DEBOUNCE_MS 40 //A debounce time of 20 milliseconds usually works well for tactile button switches. + +#define REPEAT_FIRST 1000 //ms required before repeating on long press +#define REPEAT_INCR 75 //repeat interval for long press +#define MIN_COUNT 0 +#define MAX_ROW 3 +#define MAX_COL 19 +#define MS_IN_HOUR 3600000 //Number of ms in an hour +#define MS_IN_MIN 60000 //Number of ms in a minute +Button btnUP(UP_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); //Declare the buttons +Button btnDN(DN_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); +Button btnLF(LF_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); +Button btnRF(RF_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); //Declare the buttons +Button btnOK(OK_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); //Declare the buttons +Button btnESC(ESC_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); //Declare the buttons +enum {WAIT, UP, DOWN, LEFT, RIGHT, OKAY, RALLYEDIT, ESC}; //The possible states for the STATE machine +enum {MAIN, CALIBRATION, SETTIME, INPUTSUBTRAYEK, RALLY, CONSTANTA}; //The possible states for the MENU +enum {FORWARD, FREEZE, BACKWARD}; +char const *dircount[] = {"Fw", "Zz", "Bw"}; //CHANGE 2022 +//String dircount[] = {"Fw", "Zz", "Bw"}; + +uint8_t MENU, PREVMENU; +uint8_t STATE, dircount1, dircount2; //The current state machine state +byte hour24, min60, sec60; +unsigned long rpt = REPEAT_FIRST; //A variable time that is used to drive the repeats for long presses +uint8_t prevsec; +float constanta=3.275; +float distance1, distance2; +float prevdistance1, prevdistance2; +long prevcount1, prevcount2; +boolean showTIME = true; + +float tempval; +struct ts t; +byte calibrationDistance=1; +byte tempcalibdist=1; +boolean calibrationON=false; + +float oneMeter=0; +unsigned long startCalibration=0; +unsigned long Calibration=110400; //for CR-V 2012 +unsigned long Calibrationcount; +unsigned long Calibrationtime; +int digit1, digit2, digit3, digit4, digit5, digit6; +byte calibdigit1, calibdigit2, calibdigit3; +int dist1digit1, dist1digit2; +int dist2digit1, dist2digit2; +byte starttractsec, starttractmin, starttracthour; +boolean rallyON=false; + +volatile unsigned long VSSCount =0; + +long count1 = 0; //must be signed as technically distance can go negative +long count2 = 0; +long backcount1 = 0; +long backcount2 = 0; + +//The two time variables are used to store reset times in ms +unsigned long time1 = 1; +unsigned long time2 = 1; +int CURSOR_POS = 1; + +unsigned long count1Seq = 0; +boolean editDist1 = false; + +//to save trayek data +struct RallyData { + char sub; + float speed; + byte startHour; + byte startMin; + byte startSec; +// float distance; +// unsigned int subTime; +}; + //RallyData Trip={"b",23.342, 11,0,0,12.13}; + RallyData Trip[TRIPSIZE]; +//RallyData currentTrip; +byte curTrip=0; +byte prevTrip=0; + + +void printUPchar() +{ + byte thumb1[8] = {B00100,B01110,B11111,B00100,B00100,B00100,B00100,B00100}; + lcd.createChar(1, thumb1); + //lcd.write(1); +} +void printDOWNchar() +{ + byte thumb1[8] = {B00100,B00100,B00100,B00100,B00100,B11111,B01110,B00100}; + lcd.createChar(2, thumb1); + //lcd.write(2); +} +unsigned long memretrieveLong(int startaddress, byte rrpointersize, unsigned long &seq ) +{ + //Serial.print(seq);Serial.print(";R ");Serial.print(rrpointer[0]);Serial.print("; SizeofArr=");Serial.println(rrpointersize); + unsigned long largestcountpointer=0; + int lastpointer = 0; + unsigned long seqnumber = 0; + int pointeradd = 0; + for (int i = 0; i");Serial.println(mem.readLong(pointer+(i*32))); + } +} +*/ + +void memretrieveTrip(int pointer, int startaddress) +{ + //Serial.print (pointer); Serial.println(startaddress); + int pointeradd; + Trip[pointer].speed = mem.readFloat(startaddress); + pointeradd = (startaddress + 6); + Trip[pointer].startHour = mem.read(pointeradd); + pointeradd = (startaddress + 5); + Trip[pointer].startMin = mem.read(pointeradd); + pointeradd = (startaddress + 4); + Trip[pointer].startSec = mem.read(pointeradd); + if (Trip[pointer].startHour >= 24) Trip[pointer].startHour = 23; + if (Trip[pointer].startMin >= 60) Trip[pointer].startMin = 59; + if (Trip[pointer].startSec >= 60) Trip[pointer].startSec = 59; +} + +void constantatodigit() +{ + digit1=(int)(constanta/10); + digit2=(int)constanta%10; + digit3=(int)((constanta - (int)constanta)*10); + digit4=(int)((constanta*10 - (int)(constanta*10))*10); + digit5=(int)((constanta*100 - (int)(constanta*100))*10); + digit6=(int)((constanta*1000 - (int)(constanta*1000))*10); + //digit6=(int)((constanta*10000 - (int)(constanta*10000))*10); +} + +void blink() { +#ifndef ATMEGA328 + ledstate = !ledstate; +// #else +// PORTB ^= B00100000; +#endif + VSSCount++; +} + + +// void setupcopyfromvssrally() +// { +// // Serial.begin(115200); +// #ifdef DEBUG +// Serial.begin(115200); +// Serial.println("Starting Rally"); +// #endif +// Wire.begin(); +// pinMode(UP_pin, INPUT_PULLUP); +// pinMode(DOWN_pin, INPUT_PULLUP); +// pinMode(LEFT_pin, INPUT_PULLUP); +// pinMode(RIGHT_pin, INPUT_PULLUP); +// pinMode(OK_pin, INPUT_PULLUP); +// //DS3231_init(DS3231_INTCN); +// DS3231_init(DS3231_CONTROL_INTCN); +// //memset(recv, 0, BUFF_MAX); +// #ifdef DEBUG +// Serial.println("GET time"); +// #endif +// /* +// Trip[0].sub = "A"; +// Trip[0].speed = 24.275; +// Trip[0].startHour = 25; +// //Trip[0].distance = 12.898; +// Trip[9].sub = "A"; +// Trip[9].speed = 90.2751; +// Trip[9].startHour = 22; +// Trip[9].startMin = 59; +// Trip[9].startSec = 58; +// */ +// //Trip[9].distance = 12.898; +// //Serial.println(Trip[0].sub);Serial.println(Trip[0].speed);Serial.println(Trip[0].startHour);Serial.println(Trip[0].startMin);Serial.println(Trip[0].startSec); +// //Serial.println(Trip[0].distance); +// //Serial.println(Trip[0].subTime); + +// for (int i = 0; i23) starttracthour = 23; +// if (starttractmin>59) starttractmin = 59; +// if (starttractsec>59) starttractsec = 59; +// //constanta=mem.readFloat(800); +// constanta = Trip[curTrip].speed; +// if ((constanta > 150) || (constanta < 0)) constanta = 60; +// long m = mem.readLong(896); //read calibration value; +// if (m >= 0) { +// Calibration = m; +// } +// #ifdef DEBUG +// Serial.println(m); +// Serial.println(Calibration); +// Serial.println(constanta); +// #endif +// constantatodigit(); + +// // Serial.print(digit1);Serial.print(digit2); Serial.print(digit3); Serial.print(digit4);Serial.print(digit5);Serial.println(digit6); +// // Serial.println(constanta,5); +// //Serial.print(digitalRead(UP_pin));Serial.print(digitalRead(DOWN_pin));Serial.print(digitalRead(LEFT_pin));Serial.print(digitalRead(RIGHT_pin));Serial.println(digitalRead(OK_pin)); + +// prevcount1 = count1; +// prevcount2 = count2; + +// prevcalibrationtime+=calibrationtimeinterval; +// prevtempint+=tempinterval; +// prevtemprally+=tempintervalrally; +// prevsettime += intervalsettime; +// startmillis+=1000; + +// pinMode(ledPin, OUTPUT); +// pinMode(interruptPin, INPUT); //Pull down using resistor to ground +// attachInterrupt(digitalPinToInterrupt(interruptPin), blink, FALLING); + +// mainMenu(); +// } + + + + + +#ifdef DEBUG +long prevtimemicros=micros(); //************************************************************************** +#endif +unsigned long rallyEditTime=micros(); +byte rallyEditRpt = 0; +boolean rallyEdit =false; +boolean savedCount = true; +unsigned long intervalsavemillis = 3000; + + +void printMOVEchar() +{ + byte Movechar3[8] = {B00000,B00000,B00000,B00000,B00000,B00000,B00000,B11111}; + lcd.createChar(3, Movechar3); + byte Movechar4[8] = {B00000,B00000,B00000,B00000,B00000,B00000,B11111,B11111}; + lcd.createChar(4, Movechar4); + byte Movechar5[8] = {B00000,B00000,B00000,B00000,B00000,B11111,B11111,B11111}; + lcd.createChar(5, Movechar5); +} + + +void lcdprint2digit(byte val) +{ + if (val<10) lcd.print("0"); + lcd.print(val); +} +void setTheTime(char *cmd) +{ + // ssmmhhWDDMMYYYY set time + + t.sec = inp2toi(cmd, 0); + t.min = inp2toi(cmd, 2); + t.hour = inp2toi(cmd, 4); + t.wday = inp2toi(cmd, 6); + t.mday = inp2toi(cmd, 7); + t.mon = inp2toi(cmd, 9); + t.year = inp2toi(cmd, 11) * 100 + inp2toi(cmd, 13); + DS3231_set(t); +#ifdef DEBUG + Serial.println("OK setTheTime()"); +#endif +} + +void printMonth(int month) +{ + switch(month) + { + case 1: lcd.print(" January ");break; + case 2: lcd.print(" February ");break; + case 3: lcd.print(" March ");break; + case 4: lcd.print(" April ");break; + case 5: lcd.print(" May ");break; + case 6: lcd.print(" June ");break; + case 7: lcd.print(" July ");break; + case 8: lcd.print(" August ");break; + case 9: lcd.print(" September ");break; + case 10: lcd.print(" October ");break; + case 11: lcd.print(" November ");break; + case 12: lcd.print(" December ");break; + default: lcd.print(" Error ");break; + } +} + +void mainMenu() +{ + MENU = MAIN; + lcd.clear(); + lcd.print("1. Rally TSD"); + lcd.setCursor(0,1); + lcd.print("2. Set Main Time"); + lcd.setCursor(0,2); + lcd.print("3. Input Constanta"); + lcd.setCursor(0,3); + lcd.print("4. Calibration ODO"); + //lcd.home(); + x=2; + y=0; + lcd.cursor(); + lcd.setCursor(x,y); + PREVMENU = MENU; +} + +void runningtime(byte x1,byte y1) +{ + lcd.setCursor(x1,y1); //Go to second line of the LCD Screen + if(t.hour<10) + { + lcd.print("0"); + } + lcd.print(t.hour); + lcd.print(":"); + if(t.min<10) + { + lcd.print("0"); + } + lcd.print(t.min); + lcd.print(":"); + if(t.sec<10) + { + lcd.print("0"); + } + lcd.print(t.sec); +} + +void settimeMenu() +{ + lcd.setCursor(0,0); + lcd.print(t.mday); + printMonth(t.mon); + lcd.print(t.year); + + runningtime(0,1); + + lcd.setCursor(x,y); + prevsec = t.sec; + PREVMENU = MENU; +} + + +void calibrationMenu() +{ + MENU = CALIBRATION; + lcd.clear(); + lcd.print("Calibration Back"); + lcd.setCursor(0,1); + lcd.print("Set Distance(Km): "); + lcd.print(calibrationDistance); + lcd.setCursor(0,2); + lcd.print("Start 00.000Km"); + lcd.setCursor(0,3); + lcd.print("1m="); + lcd.print(((float)Calibration/1000),3); + char Calibrationstr[6]; + sprintf(Calibrationstr, "%06lu", Calibration); + lcd.setCursor(14,3); + lcd.print(Calibrationstr); + //lcd.setCursor(0,0); + //lcd.print(Calibration); + //lcd.home(); + x=18; + y=0; + lcd.setCursor(x,y); + lcd.cursor(); + //lcd.blink(); + //blinkON=true; + PREVMENU = MENU; +} + +void constantaMenu() +{ + MENU = CONSTANTA; + lcd.clear(); + lcd.print("Constanta Back"); + lcd.setCursor(0,1); + lcd.print("Sub Trip:"); + lcd.setCursor(14,1); + lcd.print(Trip[curTrip].sub); + lcd.setCursor(0,2); + lcd.print("Set Speed:"); + lcd.setCursor(13,2); + if (constanta<10) lcd.print("0"); + lcd.print(constanta,4); + //lcd.print( + lcd.setCursor(0,3); + lcd.print("Start Time:"); + //DS3231_get(&t); //Get time + lcd.setCursor(12,3); //Go to second line of the LCD Screen + if(starttracthour<10) + { + lcd.print("0"); + } + lcd.print(starttracthour); + lcd.print(":"); + if(starttractmin<10) + { + lcd.print("0"); + } + lcd.print(starttractmin); + lcd.print(":"); + if(starttractsec<10) + { + lcd.print("0"); + } + lcd.print(starttractsec); + lcd.print(""); + //x=14; + //y=0; + lcd.setCursor(x,y); + lcd.cursor(); + //lcd.blink(); + //blinkON=true; + PREVMENU = MENU; + +} +void updateCount() +{ + if (dircount1 == FORWARD) { + count1 = count1 + (VSSCount-time1); + } + else if (dircount1 == BACKWARD) { + count1 = count1 - (VSSCount-time1); + } + + if (dircount2 == FORWARD) { + count2 = count2 + (VSSCount-time2); + } + else if (dircount2 == BACKWARD) { + count2 = count2 - (VSSCount-time2); + } + time1 = VSSCount; + time2 = VSSCount; +} +void saveCount() +{ + if (count1 != prevcount1) { + count1Seq++; + memwritingLong(count1Address, RRcountSIZE, count1Seq, count1);//(int startaddress, byte RRsize, unsigned long seq, unsigned long Data) + prevcount1 = count1; + } + + if ((count1-count2) != count1count2diff) { +#ifdef DEBUG + Serial.print("count1=");Serial.print(count1);Serial.print(";count2=");Serial.print(count2);Serial.print("countdiff=");Serial.println(count1count2diff); +#endif + count1count2diff = count1-count2; + int pointer = count1count2diffAddress*32; + mem.writeLong(pointer,count1count2diff); +#ifdef DEBUG + Serial.println("save count1count2diff"); +#endif + } +} + + +void secondrallyMenu() +{ + char heading2[6]; + char heading4[6]; + lcd.setCursor(9,1); + //sprintf(heading2, "%s", (dirfwdcount1?"Fw":"Bw")); + sprintf(heading2, "%s", dircount[dircount1]); + lcd.print(heading2); + + lcd.setCursor(9,3); + //sprintf(heading4, "%s", (dirfwdcount2?"Fw":"Bw")); + sprintf(heading4, "%s", dircount[dircount2]); + lcd.print(heading4); +#ifdef DEBUG + Serial.println("secondrallyMenu"); +#endif +} + +void rallyMenu() +{ + MENU = RALLY; + + //lcd.clear(); + lcd.setCursor(15,0); + if (showTIME) lcd.print("Time "); + else lcd.print("TDiff"); + + secondrallyMenu(); + PREVMENU = MENU; +#ifdef DEBUG + Serial.println("rallyMenu"); +#endif +} + +unsigned long startspeed=0; +float startdistance=0; + +void redrawcalibrationMenu() +{ + float distance; + Calibrationcount = Calibrationcount + (VSSCount-Calibrationtime); + distance = (float)Calibrationcount/((float)Calibration); + char cur_distance_str[6]; + byte xtemp=13; + if (distance<100) { + sprintf(cur_distance_str, "%02d.%03dKm", (int)distance, (int)((distance - (int)distance)*1000)); + xtemp = 12; + } + else if (distance<1000) { + sprintf(cur_distance_str, "%02d.%02dKm", (int)distance, (int)((distance - (int)distance)*100)); + } + else { + sprintf(cur_distance_str, "%03d.%01dKm", (int)distance, (int)((distance - (int)distance)*10)); + } + Calibrationtime = VSSCount; + lcd.setCursor(xtemp,2); + lcd.print(cur_distance_str); +} +void redrawrallyMenu() +{ + DS3231_get(&t); //Get time + //runningtime(6,0); + //float distance, distance1, distance2; + + //Serial.print(tempcount1);Serial.print(";"); Serial.print(time1);Serial.print("; ");Serial.print(Calibration); Serial.print(";"); Serial.println(count1); + updateCount(); + + //distance = (float)count1/((float)Calibration); + distance1 = (float)count1/((float)Calibration); // * 1); + distance2 = (float)count2/((float)Calibration); + float speed1=0; + + if ((distance1 - startdistance) > 0) { + speed1 = (distance1-startdistance)/(millis()-startspeed)*3600000; + } + + startdistance = distance1; + startspeed = millis(); //startspeed is only one no startspeed2 + + if ((millis()-startsavemillis)>0) { + + if (distance1 != prevdistance1) { + mem.writeFloat(832,distance1); + prevdistance1 = distance1; + } + if (distance2 != prevdistance2) { + mem.writeFloat(864,distance2); + prevdistance2 = distance2; + } + saveCount(); + startsavemillis=millis()+2500; + } + //Serial.print(tempcount1);Serial.print(";"); Serial.print(time1);Serial.print("; ");Serial.print(Calibration); Serial.print(";"); Serial.println(count1); + + //Serial.print(millis());Serial.print(";");Serial.println(distance1,3); + //Serial.print(starttracthour); Serial.print(":"); Serial.print(starttractmin); Serial.print(":"); Serial.println(starttractsec); + //Serial.println(distance2,3); + lcd.setCursor(4,0); + lcd.print(Trip[curTrip].sub); + lcd.setCursor(0,2); + //lcd.print(T + lcd.print(Trip[curTrip].speed); + lcd.print("Km/H"); + + runningtime(6,0); + lcd.setCursor(11,2); + char cur_speed_str[8]; + sprintf(cur_speed_str, "%3d.%01dKm/h", (int)speed1, (int)((speed1 - (int)speed1)*10)); + lcd.print(cur_speed_str); + char cur_distance1_str[6]; + char cur_distance2_str[6]; + lcd.setCursor(0,1); + if (distance1<100) { + sprintf(cur_distance1_str, "%02d.%03dKm", (int)distance1, (int)((distance1 - (int)distance1)*1000)); + } + else if (distance1<1000) { + sprintf(cur_distance1_str, "%02d.%02dKm", (int)distance1, (int)((distance1 - (int)distance1)*100)); + } + else { + sprintf(cur_distance1_str, "%03d.%01dKm", (int)distance1, (int)((distance1 - (int)distance1)*10)); + } + //lcd.print(distance1,3); + lcd.print(cur_distance1_str); + lcd.setCursor(0,3); + if (distance2<100) { + sprintf(cur_distance2_str, "%02d.%03dKm", (int)distance2, (int)((distance2 - (int)distance2)*1000)); + } + else if (distance2<1000) { + sprintf(cur_distance2_str, "%02d.%02dKm", (int)distance2, (int)((distance2 - (int)distance2)*100)); + } + else { + sprintf(cur_distance2_str, "%03d.%01dKm", (int)distance2, (int)((distance2 - (int)distance2)*10)); + } + //lcd.print(distance2,3); + lcd.print(cur_distance2_str); + + float distancetime1 = distance1 * 60 / constanta; + float distancetime2 = distance2 * 60 / constanta; + +//Calculating all about TIME,TDiff(including passing 23:59:59) + lcd.setCursor(9,1); + int secs1, mins1, hours1; + + secs1 = (distancetime1-(int)distancetime1)*60; + mins1 = (int)distancetime1 % 60; + hours1 = (int)distancetime1 / 60; + unsigned long totcurrentsecs = t.sec + (t.min*60) + ((long)t.hour*3600); + unsigned long totsecs1 = secs1 + (mins1*60) + ((long)hours1*3600); + unsigned long totstarttractsecs = starttractsec + (starttractmin*60) + ((long)starttracthour*3600); + unsigned long tottime1 = totsecs1 + totstarttractsecs; + boolean negatifsign = false; + +//Serial.print((long)starttracthour*3600); Serial.print(";"); Serial.print(starttractmin*60); Serial.println(";"); +//Serial.print(totsecs1); Serial.print(";"); Serial.print(totstarttractsecs); Serial.print(";"); +//Serial.print(tottime1);Serial.print(";");Serial.println(totcurrentsecs); + if (totcurrentsecs=0) { //positif means we are too fast, slow down please. + if (tottime1 >= totcurrentsecs) { //positif means we are too fast, slow down please. + // Serial.println("pos"); + negatifsign = false; + tottime1 = tottime1 - totcurrentsecs; + } + else { //negatif means we need to hurry, its late + // Serial.println("neg"); + negatifsign = true; + tottime1 = totcurrentsecs - tottime1; + } + } + //Serial.print(negatifsign);Serial.print(";"); Serial.println(tottime1); + hours1 = ((int)(tottime1 / 3600))%24; + mins1 = (int)((tottime1 % 3600)/60); + secs1 = (tottime1 % 60); + + char cur_time1_str[10]; + if (showTIME) { + sprintf(cur_time1_str, "%s %02d:%02d:%02d", dircount[dircount1], hours1, mins1, secs1); + } + else { + if (hours1 < 10) sprintf(cur_time1_str, "%s %s%01d:%02d:%02d", dircount[dircount1], (negatifsign?"-":" "), hours1, mins1, secs1); + else sprintf(cur_time1_str, "%s%s%02d:%02d:%02d", dircount[dircount1], (negatifsign?"-":" "), hours1, mins1, secs1); + + } + lcd.print(cur_time1_str); + +// Print Second TIME + lcd.setCursor(9,3); + int secs2, mins2, hours2; + + secs2 = (distancetime2-(int)distancetime2)*60; + mins2 = (int)distancetime2 % 60; + hours2 = (int)distancetime2 / 60; + + unsigned long totsecs2 = secs2 + (mins2*60) + ((long)hours2*3600); + unsigned long tottime2 = totsecs2 + totstarttractsecs; +//Serial.println(tottime2); + + if (!showTIME) { + if (tottime2 >= totcurrentsecs) { //positif means we are too fast, slow down please. + negatifsign = false; + tottime2 = tottime2 - totcurrentsecs; + } + else { //negatif means we need to hurry, its late + negatifsign = true; + tottime2 = totcurrentsecs - tottime2 ; + } + } + + hours2 = ((int)(tottime2 / 3600))%24; + mins2 = (int)((tottime2 % 3600)/60); + secs2 = (tottime2 % 60); + char cur_time2_str[10]; + if (showTIME) { + sprintf(cur_time2_str, "%s %02d:%02d:%02d", dircount[dircount2], hours2, mins2, secs2); + } + else { + if (hours2<10) sprintf(cur_time2_str, "%s %s%01d:%02d:%02d", dircount[dircount2], (negatifsign?"-":" "), hours2, mins2, secs2); + else sprintf(cur_time2_str, "%s%s%02d:%02d:%02d", dircount[dircount2], (negatifsign?"-":" "), hours2, mins2, secs2); + } + //sprintf(cur_time2_str, "%s%02d:%02d:%02d", (dirfwdcount2?"Fw":"Bw"), hours2, mins2, secs2); + //sprintf(cur_time2_str, "%s %02d:%02d:%02d", dircount[dircount2], hours2, mins2, secs2); + lcd.print(cur_time2_str); +/* //may be needed to refresh if Km more than 10000Km + lcd.setCursor(8,3); + lcd.write(1); //UP Arrow + + lcd.setCursor(8,1); + lcd.write(2); //DOWN Arrow +*/ + lcd.setCursor(x,y); +} + +void set_cursor_pos(int new_pos) +{ + /* + Cursor Positon map: + ---------------------- + |Count1 TIME AvgSp| + |1 35 |7 9 | + |Count2 KmH| + |2 46 |8 10| + ---------------------- + */ + + //Need to clear the previous cursor position + //int x, y; + switch(CURSOR_POS) + { + case 1: + x = 0; + y = 1; + break; + case 2: + x = 0; + y = 3; + break; + case 3: + x = 8; //Km is 7,1 + y = 1; + break; + case 4: + x = 8; //Km is 7,3 + y = 3; + break; + case 5: + x = 9; + y = 1; + break; + case 6: + x = 9; + y = 3; + break; + case 7: + x = 13; + y = 1; + break; + case 8: + x = 13; + y = 3; + break; + case 9: + x = 18; + y = 1; + break; + case 10: + x = 18; + y = 3; + break; + } + lcd.print(" "); + lcd.blink(); + lcd.setCursor(8,3); + lcd.write(1); //UP Arrow + + lcd.setCursor(8,1); + lcd.write(2); //DOWN Arrow + + lcd.setCursor(x,y); + +/* + switch(new_pos) + { + case 1: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_RIGHT); + break; + case 2: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_RIGHT); + break; + case 3: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 4: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 5: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 6: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 7: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_LEFT); + break; + case 8: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_LEFT); + break; + } +*/ + + CURSOR_POS = new_pos; +#ifdef DEBUG + Serial.print("SetCursorPosition:"); + Serial.println(CURSOR_POS); +#endif +} + + + + + + +void setup() { + +// +// +// +// +#ifdef DEBUG + Serial.begin(115200); + Serial.println("Starting Rally"); +#endif + Wire.begin(); + pinMode(UP_pin, INPUT_PULLUP); + pinMode(DOWN_pin, INPUT_PULLUP); + pinMode(LEFT_pin, INPUT_PULLUP); + pinMode(RIGHT_pin, INPUT_PULLUP); + pinMode(OK_pin, INPUT_PULLUP); + //DS3231_init(DS3231_INTCN); + DS3231_init(DS3231_CONTROL_INTCN); + //memset(recv, 0, BUFF_MAX); +#ifdef DEBUG + Serial.println("GET time"); +#endif +/* +Trip[0].sub = "A"; +Trip[0].speed = 24.275; +Trip[0].startHour = 25; +//Trip[0].distance = 12.898; +Trip[9].sub = "A"; +Trip[9].speed = 90.2751; +Trip[9].startHour = 22; +Trip[9].startMin = 59; +Trip[9].startSec = 58; +*/ +//Trip[9].distance = 12.898; +//Serial.println(Trip[0].sub);Serial.println(Trip[0].speed);Serial.println(Trip[0].startHour);Serial.println(Trip[0].startMin);Serial.println(Trip[0].startSec); +//Serial.println(Trip[0].distance); +//Serial.println(Trip[0].subTime); + +for (int i = 0; i23) starttracthour = 23; + if (starttractmin>59) starttractmin = 59; + if (starttractsec>59) starttractsec = 59; + //constanta=mem.readFloat(800); + constanta = Trip[curTrip].speed; + if ((constanta > 150) || (constanta < 0)) constanta = 60; + long m = mem.readLong(896); //read calibration value; + if (m >= 0) { + Calibration = m; + } +#ifdef DEBUG + Serial.println(m); + Serial.println(Calibration); + Serial.println(constanta); +#endif + constantatodigit(); + +// Serial.print(digit1);Serial.print(digit2); Serial.print(digit3); Serial.print(digit4);Serial.print(digit5);Serial.println(digit6); +// Serial.println(constanta,5); + //Serial.print(digitalRead(UP_pin));Serial.print(digitalRead(DOWN_pin));Serial.print(digitalRead(LEFT_pin));Serial.print(digitalRead(RIGHT_pin));Serial.println(digitalRead(OK_pin)); + + prevcount1 = count1; + prevcount2 = count2; + + prevcalibrationtime+=calibrationtimeinterval; + prevtempint+=tempinterval; + prevtemprally+=tempintervalrally; + prevsettime += intervalsettime; + startmillis+=1000; + + pinMode(ledPin, OUTPUT); + pinMode(interruptPin, INPUT); //Pull down using resistor to ground + attachInterrupt(digitalPinToInterrupt(interruptPin), blink, FALLING); + + mainMenu(); + + +// +// +// +// + + + Serial.begin(115200); + DynamicJsonDocument doc(512); + // Initialize SPIFFS + #ifdef ESP32 + if(!SPIFFS.begin(true)){ + Serial.println("An Error has occurred while mounting SPIFFS"); + return; + } + #else + if(!SPIFFS.begin()){ + Serial.println("An Error has occurred while mounting SPIFFS"); + return; + } + #endif + // wifiManager.setAPCallback(configModeCallback); + // wifiManager.autoConnect(soft_ap_ssid); + + WiFi.onEvent(OnWiFiEvent); + //WiFi.mode(WIFI_STA); + WiFi.mode(WIFI_MODE_APSTA); + + WiFi.softAP(soft_ap_ssid, soft_ap_password); + + String yourSSIDString = readFile(SPIFFS, "/ssidString.txt"); + Serial.print("*** Your ssidString: "); + Serial.println(yourSSIDString); + Serial.println(ssid); + if (yourSSIDString != ""){ + strncpy(ssid, yourSSIDString.c_str() , (sizeof ssid)-1); + } + + Serial.println(ssid); + String yourInputPwd = readFile(SPIFFS, "/inputPwd.txt"); + Serial.print("*** Your inputPwd: "); + Serial.println(yourInputPwd); + if (yourInputPwd != ""){ + strncpy(password, yourInputPwd.c_str() , (sizeof password)-1); + } + + WiFi.begin(ssid, password); + if (WiFi.waitForConnectResult() != WL_CONNECTED) { + Serial.println("WiFi Failed!"); + //return; + } + + Serial.print("ESP32 IP as soft AP: "); + Serial.println(WiFi.softAPIP()); + + Serial.println(); + Serial.print("IP Address: "); + Serial.println(WiFi.localIP()); + + // Init and get the time + configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); + printLocalTime(); + + // Send web page with input fields to client + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ + if (ON_STA_FILTER(request)) { + //request->send(200, "text/plain", "Hello from STA"); + request->send_P(200, "text/html", main_menu, processor); + return; + + } else if (ON_AP_FILTER(request)) { + //request->send(200, "text/plain", "Hello from AP"); + Serial.println("on apfilter /"); + request->send_P(200, "text/html", wifi_html, processor); + return; + } + + }); + + server.on("/wifi", HTTP_GET, [](AsyncWebServerRequest * request) { + + if (ON_STA_FILTER(request)) { + //request->send(200, "text/plain", "Hello from STA"); + request->send_P(200, "text/html", wifi_html, processor); + return; + + } else if (ON_AP_FILTER(request)) { + //request->send(200, "text/plain", "Hello from AP"); + Serial.println("on apfilter /wifi"); + request->send_P(200, "text/html", wifi_html, processor); + return; + } + + request->send(200, "text/plain", "Hello from undefined"); +}); + + + + // Send a GET request to /get?inputString= + server.on("/setwifi", HTTP_POST, [] (AsyncWebServerRequest *request) { + String inputMessage; + boolean bolrestart=false; + Serial.println("ini masuk /setwifi"); + // GET inputString value on /get?inputString= + if (request->hasParam(PARAM_SSID)) { + inputMessage = request->getParam(PARAM_SSID)->value(); + if (inputMessage!=""){ + writeFile(SPIFFS, "/ssidString.txt", inputMessage.c_str()); + delay(50); + bolrestart=true; + //ESP.restart(); + } + } + // GET inputPwd value on /wifi/get?inputPwd= + if (request->hasParam(PARAM_PWD)) { + inputMessage = request->getParam(PARAM_PWD)->value(); + if (inputMessage!=""){ + writeFile(SPIFFS, "/inputPwd.txt", inputMessage.c_str()); + delay(50); + bolrestart=true; + //ESP.restart(); + } + } + else { + inputMessage = "No message sent"; + } + if (bolrestart) { + ESP.restart(); + } + Serial.println("ini /setwifi aja");Serial.println(inputMessage); + request->send(200, "text/text", inputMessage); + }); + + // // Send a GET request to /wifi/get?ssidString= + // server.on("/wifi/get", HTTP_GET, [] (AsyncWebServerRequest *request) { + // String inputMessage; + // // GET ssidString value on /wifi/get?ssidString= + // Serial.println("ini masuk wifi get"); + // Serial.println(request->params()); + // if (request->hasParam(PARAM_SSID)) { + // inputMessage = request->getParam(PARAM_SSID)->value(); + // writeFile(SPIFFS, "/ssidString.txt", inputMessage.c_str()); + // delay(100); + // ESP.restart(); + // } + // // GET inputPwd value on /wifi/get?inputPwd= + // else if (request->hasParam(PARAM_PWD)) { + // inputMessage = request->getParam(PARAM_PWD)->value(); + // writeFile(SPIFFS, "/inputPwd.txt", inputMessage.c_str()); + // delay(100); + // ESP.restart(); + // } + // else { + // inputMessage = "No message sent"; + // } + // Serial.println("/wifi/get value:"); Serial.println(inputMessage); + // request->send(200, "text/text", inputMessage); + // }); + + server.on("/menu", HTTP_GET, [] (AsyncWebServerRequest *request) { + //String s = MAIN_page; //Read HTML contents + //request->send_P(200, "text/html", s); //Send web page + request->send_P(200, "text/html", main_menu); + }); + + server.on("/startrally", HTTP_GET, [] (AsyncWebServerRequest *request) { + //String s = MAIN_page; //Read HTML contents + //request->send_P(200, "text/html", s); //Send web page + String PAGE; + PAGE += FPSTR(HTML_PAGEHEADER); + PAGE.replace("%serveripaddress%", WiFi.localIP().toString()); + PAGE += FPSTR(HTML_DIVSTARTRALLY); + //PAGE += FPSTR(HTML_SCRIPTSETINTERVAL); + //PAGE += FPSTR(HTML_SCRIPTGETDATA); + PAGE += FPSTR(HTML_END); + //Serial.println(PAGE); + request->send(200, "text/html", PAGE); + }); + + server.on("/startrally1", HTTP_GET, [] (AsyncWebServerRequest *request) { + request->send_P(200, "text/html", HTML_startrally1, processor); + }); + + server.on("/resetodo1", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("ODORESET 1"); + request->redirect("/startrally1"); + }); + + server.on("/resetodo2", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("ODORESET 22222"); + request->redirect("/startrally1"); + }); + + server.on("/copytoodo2", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("COPY ODO 1 to 2"); + request->redirect("/startrally1"); + }); + + server.on("/copytoodo1", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("COPY ODO 2 to 1"); + request->redirect("/startrally1"); + }); + server.on("/DIR", HTTP_GET, [] (AsyncWebServerRequest *request) { + String inputMessage; + String inputParam; + if (request->hasParam("DIR1")){ + inputMessage=request->getParam("DIR1")->value(); + Serial.print("DIR 1->");Serial.println(inputMessage); + switch(inputMessage[0]){ + case 'F': + Serial.println("FW1"); + break; + case 'S': + Serial.println("ST1"); + break; + case 'B': + Serial.println("BACK1"); + break; + default: + Serial.println("Default VAL1"); + } + } + else if (request->hasParam("DIR2")){ + inputMessage=request->getParam("DIR2")->value(); + Serial.print("DIR 2->");Serial.println(inputMessage); + switch(inputMessage[0]){ + case 'F': + Serial.println("FW2"); + break; + case 'S': + Serial.println("ST2"); + break; + case 'B': + Serial.println("BACK2"); + break; + default: + Serial.println("Default VAL2"); + } + } + request->redirect("/startrally1"); + }); + + + server.on("/TG1", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("TOGGLE 1"); + request->redirect("/startrally1"); + }); + + server.on("/TG2", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("TOGGLE 2"); + request->redirect("/startrally1"); + }); +// //server.on("/adc", HTTP_GET); //This is display page +// server.on("/readADC", HTTP_GET, [] (AsyncWebServerRequest *request) { +// // int a = analogRead(A0); +// // String adcValue = String(millis()); +// String adcValue = getPin(); +// Serial.println(adcValue); +// request->send_P(200, "text/plain", adcValue.c_str()); //Send ADC value only to client ajax request +// }); + + server.on("/calibration", HTTP_GET, [] (AsyncWebServerRequest *request) { + //PAGE.replace("%serveripaddress%", WiFi.localIP().toString()); + request->send_P(200, "text/html", HTML_CALIBRATION, processor); + }); + + ws.onEvent(onWsEvent); //add ws event + wscal.onEvent(onWsEvent2); //add ws event + server.addHandler(&ws); + server.addHandler(&wscal); + + server.onNotFound(notFound); + server.begin(); +} + +// void loop() { +// // // To access your stored values on inputString, inputInt, inputFloat +// // String yourInputString = readFile(SPIFFS, "/inputString.txt"); +// // Serial.print("*** Your inputString: "); +// // Serial.println(yourInputString); + +// // int yourInputInt = readFile(SPIFFS, "/inputInt.txt").toInt(); +// // Serial.print("*** Your inputInt: "); +// // Serial.println(yourInputInt); + +// // float yourInputFloat = readFile(SPIFFS, "/inputFloat.txt").toFloat(); +// // Serial.print("*** Your inputFloat: "); +// // Serial.println(yourInputFloat); + +// // String yourSSIDString = readFile(SPIFFS, "/ssidString.txt"); +// // Serial.print("*** Your ssidString: "); +// // Serial.println(yourSSIDString); + +// // String yourInputPwd = readFile(SPIFFS, "/inputPwd.txt"); +// // Serial.print("*** Your inputPwd: "); +// // Serial.println(yourInputPwd); +// // delay(10000); +// delay(10330); +// ws.textAll(getPin()); +// wscal.textAll(getCalib()); +// //printLocalTime(); +// } + + + +void loop() //loop from VSS RALLY V2 +{ +#ifdef DEBUG + prevtimemicros = micros(); +#endif +#ifndef ATMEGA328 + digitalWrite(ledPin, ledstate); +#endif + char tempF[6]; + unsigned long now1 = millis(); + + btnUP.read(); //read the buttons + btnDN.read(); + btnLF.read(); //read the buttons + btnRF.read(); + btnOK.read(); + btnESC.read(); + if (millis()-rallyEditTime >1500) rallyEditRpt = 0; + switch (STATE) { + case WAIT: //wait for a button event + if (btnUP.wasPressed()) + STATE = UP; + else if (btnDN.wasPressed()) + STATE = DOWN; + else if (btnLF.wasPressed()) + STATE = LEFT; + else if (btnRF.wasPressed()) + STATE = RIGHT; + else if (btnUP.wasReleased()) //reset the long press interval + rpt = REPEAT_FIRST; + else if (btnDN.wasReleased()) + rpt = REPEAT_FIRST; + else if (btnLF.wasReleased()) //reset the long press interval + rpt = REPEAT_FIRST; + else if (btnRF.wasReleased()) + rpt = REPEAT_FIRST; + else if (btnUP.pressedFor(rpt)) { //check for long press + rpt += REPEAT_INCR; //increment the long press interval + STATE = UP; + } + else if (btnDN.pressedFor(rpt)) { + rpt += REPEAT_INCR; + STATE = DOWN; + } + else if (btnLF.pressedFor(rpt)) { //check for long press + rpt += REPEAT_INCR; //increment the long press interval + STATE = LEFT; + } + else if (btnRF.pressedFor(1000)) { + rpt += REPEAT_INCR; + STATE = RIGHT; + } + else if (btnOK.wasPressed() && (MENU != RALLY)) { + STATE = OKAY; + } + else if (btnOK.wasPressed() && (CURSOR_POS > 4)) { + STATE = OKAY; + } + else if (btnOK.wasPressed() && (CURSOR_POS <= 2)) { + //STATE = OKAY; + if (!rallyEditRpt) { + rallyEditTime = millis(); + rallyEditRpt++; + //Serial.println("!rallyEditRpt"); + //Serial.println(rallyEditRpt); + } + else if (millis()-rallyEditTime > 1500) { + rallyEditRpt = 0; + //Serial.println("rallyEditRpt = 0"); + //Serial.println(rallyEditRpt); + } + else if (rallyEditRpt == 2) { + //Serial.println("rallyEditRpt = ");Serial.println(rallyEditRpt); + STATE = RALLYEDIT; + rallyEditRpt = 0; + } + else { + rallyEditRpt++; + //Serial.println("rallyEditRpt++"); + //Serial.println(rallyEditRpt); + } + } + else if (btnOK.pressedFor(rpt) && (CURSOR_POS <= 4)) { + STATE = OKAY; + } + else if (btnESC.wasPressed()){ + STATE = ESC; + //Serial.println("ESC pressed"); + } + break; + + case DOWN: //increment the counter + switch (MENU) { + case MAIN: + y = min(y+1, MAX_ROW); //but not more than the specified maximum + break; + + case RALLY: + if (blinkON) { + if (y == 1) { + if (x == 0 || x == 1) { + dist1digit1 = max(dist1digit1-1, 0); + lcd.setCursor(0,y); + if (dist1digit1 <10) lcd.print("0"); + lcd.print(dist1digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist1digit2 = max(dist1digit2-1, 0); + lcd.setCursor(3,y); + if (dist1digit2 <10) { + lcd.print("00"); + }else if (dist1digit2 <100) lcd.print("0"); + lcd.print(dist1digit2); + } + } + else if (y ==3) { + if (x == 0 || x == 1) { + dist2digit1 = max(dist2digit1-1, 0); + lcd.setCursor(0,y); + if (dist2digit1 <10) lcd.print("0"); + lcd.print(dist2digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist2digit2 = max(dist2digit2-1, 0); + lcd.setCursor(3,y); + if (dist2digit2 <10) { + lcd.print("00"); + }else if (dist2digit2 <100) lcd.print("0"); + lcd.print(dist2digit2); + } + + } + + } + else { + CURSOR_POS=min(CURSOR_POS+1,10); + set_cursor_pos(CURSOR_POS); + } + + break; + + case CALIBRATION: + if (!blinkON) y = min(y+1, MAX_ROW ); //but not more than the specified maximum + else if (blinkON && y==1) { + //calibrationDistance=max(calibrationDistance-1, 1); + tempcalibdist=max(tempcalibdist-1, 1); + lcd.print(tempcalibdist); + } + else if (blinkON && y==3 && (x==18||x==19)) { + calibdigit3 = max(calibdigit3-1,0); + lcd.setCursor(18,3); + if (calibdigit3<10) lcd.print("0"); + lcd.print(calibdigit3); + } + else if (blinkON && y==3 && (x==16||x==17)) { + calibdigit2 = max(calibdigit2-1,0); + lcd.setCursor(16,3); + if (calibdigit2<10) lcd.print("0"); + lcd.print(calibdigit2); + } + else if (blinkON && y==3 && (x==14||x==15)) { + calibdigit1 = max(calibdigit1-1,0); + lcd.setCursor(14,3); + if (calibdigit1<10) lcd.print("0"); + lcd.print(calibdigit1); + } + break; + + case CONSTANTA: + if (!blinkON) { + y = min(y+1, 3); //but not less than the specified minimum + if (y==1) x=15; + } + else if (y==1) { + prevTrip = min(prevTrip+1,TRIPSIZE-1); + //curTrip = min(curTrip+1,TRIPSIZE-1); + lcd.setCursor(14,y); + lcd.print(Trip[prevTrip].sub); + } + else if (x==13 && y==2) { + digit1 = max(digit1-1, MIN_COUNT); + lcd.print(digit1); + } + else if (x==14 && y==2) { + digit2 = max(digit2-1, MIN_COUNT); + lcd.print(digit2); + } + else if (x==16 && y==2) { + digit3 = max(digit3-1, MIN_COUNT); + lcd.print(digit3); + } + else if (x==17 && y==2) { + digit4 = max(digit4-1, MIN_COUNT); + lcd.print(digit4); + } + else if (x==18 && y==2) { + digit5 = max(digit5-1, MIN_COUNT); + lcd.print(digit5); + } + else if (x==19 && y==2) { + digit6 = max(digit6-1, MIN_COUNT); + lcd.print(digit6); + } + else if ((x==12 || x==13) && y==3) { //******SET CONSTANTA TIME ******* + hour24=max(hour24-1, MIN_COUNT); + lcd.setCursor(12,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==15 || x==16) && y==3) { + min60=max(min60-1, MIN_COUNT); + lcd.setCursor(15,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==18 || x==19) && y==3) { + sec60=max(sec60-1, MIN_COUNT); + lcd.setCursor(18,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + + case SETTIME: + if (!blinkON) { + y = min(y+1, MAX_ROW); //but not more than the specified maximum + lcd.setCursor(x,y); + } + else if ((x==0 || x==1) && y==3) { + hour24=max(hour24-1, MIN_COUNT); + lcd.setCursor(0,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==3 || x==4) && y==3) { + min60=max(min60-1, MIN_COUNT); + lcd.setCursor(3,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==6 || x==7) && y==3) { + sec60=max(sec60-1, MIN_COUNT); + lcd.setCursor(6,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case UP: //decrement the counter + switch(MENU) { + case MAIN: + y = max(y-1, MIN_COUNT); //but not less than the specified minimum + break; + + case CALIBRATION: + if (!blinkON) { + y = max(y-1, MIN_COUNT); //but not less than the specified minimum + x = 18; + } + else if (blinkON && y==1) { + //calibrationDistance=min(calibrationDistance+1, 9); + tempcalibdist=min(tempcalibdist+1, 9); + lcd.print(tempcalibdist); + } + else if (blinkON && y==3 && (x==18||x==19)) { + calibdigit3 = min(calibdigit3+1,99); + lcd.setCursor(18,3); + if (calibdigit3<10) lcd.print("0"); + lcd.print(calibdigit3); + } + else if (blinkON && y==3 && (x==16||x==17)) { + calibdigit2 = min(calibdigit2+1,99); + lcd.setCursor(16,3); + if (calibdigit2<10) lcd.print("0"); + lcd.print(calibdigit2); + } + else if (blinkON && y==3 && (x==14||x==15)) { + calibdigit1 = min(calibdigit1+1,50); + lcd.setCursor(14,3); + if (calibdigit1<10) lcd.print("0"); + lcd.print(calibdigit1); + } + break; + + case RALLY: + if (blinkON) { + if (y == 1) { + if (x == 0 || x == 1) { + dist1digit1 = min(dist1digit1+1, 999); + lcd.setCursor(0,y); + if (dist1digit1 <10) lcd.print("0"); + lcd.print(dist1digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist1digit2 = min(dist1digit2+1, 999); + lcd.setCursor(3,y); + if (dist1digit2 <10) { + lcd.print("00"); + }else if (dist1digit2 <100) lcd.print("0"); + lcd.print(dist1digit2); + } + } + else if (y == 3) { + if (x == 0 || x == 1) { + dist2digit1 = min(dist2digit1+1, 99); + lcd.setCursor(0,y); + if (dist2digit1 <10) lcd.print("0"); + lcd.print(dist2digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist2digit2 = min(dist2digit2+1, 999); + lcd.setCursor(3,y); + if (dist2digit2 <10) { + lcd.print("00"); + }else if (dist2digit2 <100) lcd.print("0"); + lcd.print(dist2digit2); + } + } + + } + else { + CURSOR_POS=max(CURSOR_POS-1,1); + set_cursor_pos(CURSOR_POS); + } + break; + + case CONSTANTA: + if (!blinkON) { + y = max(y-1, MIN_COUNT); //but not less than the specified minimum + if (y==0) x=16; + else if (y==1) x=15; + } + else if (y==1) { + prevTrip = max(prevTrip-1, MIN_COUNT); + //curTrip = max(curTrip-1, MIN_COUNT); + lcd.setCursor(14,y); + lcd.print(Trip[prevTrip].sub); + } + else if (x==13 && y==2) { + digit1=min(digit1+1, 9); + lcd.print(digit1); + } + else if (x==14 && y==2) { + digit2=min(digit2+1, 9); + lcd.print(digit2); + } + else if (x==16 && y==2) { + digit3=min(digit3+1, 9); + lcd.print(digit3); + } + else if (x==17 && y==2) { + digit4=min(digit4+1, 9); + lcd.print(digit4); + } + else if (x==18 && y==2) { + digit5=min(digit5+1, 9); + lcd.print(digit5); + } + else if (x==19 && y==2) { + digit6=min(digit6+1, 9); + lcd.print(digit6); + } + else if ((x==12 || x==13) && y==3) { //******SET CONSTANTA TIME ******* + hour24=min(hour24+1, 23); + lcd.setCursor(12,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==15 || x==16) && y==3) { + min60=min(min60+1, 59); + lcd.setCursor(15,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==18 || x==19) && y==3) { + sec60=min(sec60+1, 59); + lcd.setCursor(18,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + + case SETTIME: + if (!blinkON) { + y = max(y-1, MIN_COUNT); //but not less than the specified minimum + //Serial.print(x); Serial.print(","); Serial.println(y); + //lcd.setCursor(x,y); + } + else if ((x==0 || x==1) && y==3) { + hour24=min(hour24+1, 23); + lcd.setCursor(0,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==3 || x==4) && y==3) { + min60=min(min60+1, 59); + lcd.setCursor(3,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==6 || x==7) && y==3) { + sec60=min(sec60+1, 59); + lcd.setCursor(6,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case RIGHT: //increment the counter + switch (MENU) { + case SETTIME: + x = min(x+1, MAX_COL); //MAX_COUNT); //but not more than the specified maximum + //STATE = WAIT; + //Serial.print(x); Serial.print(","); Serial.println(y); + //lcd.setCursor(x,y); + break; + + case RALLY: + if (blinkON) { + + x = min(x+1, 5); + //Serial.println(x); + } + else if (CURSOR_POS % 2 ==0) CURSOR_POS=min(CURSOR_POS+2,10); + else CURSOR_POS=min(CURSOR_POS+2,9); + if (!blinkON) set_cursor_pos(CURSOR_POS); + break; + + case CONSTANTA: + if (y==2 || y==3) { + x = min(x+1, MAX_COL); //MAX_COUNT); + } + break; + + case CALIBRATION: + if (y==3) { + x = min(x+1,MAX_COL); + } + else x = 18; + break; + + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case LEFT: //decrement the counter + switch (MENU) { + case SETTIME: + x = max(x-1, MIN_COUNT); //but not less than the specified minimum + //STATE = WAIT; + //Serial.print(x); Serial.print(","); Serial.println(y); + //lcd.setCursor(x,y); + break; + + case RALLY: + if (blinkON) { + x = max(x-1, MIN_COUNT); + } + else if (CURSOR_POS % 2 == 0) CURSOR_POS=max(CURSOR_POS-2,2); + else CURSOR_POS=max(CURSOR_POS-2,1); + if (!blinkON) set_cursor_pos(CURSOR_POS); + break; + + case CONSTANTA: + if (y==2 || y==3){ + x = max(x-1, 12); + } + break; + + case CALIBRATION: + if (y==3) { + x = max(x-1, 14); + } + else x = 18; + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case OKAY: + switch (MENU) { + case MAIN: + if (y==1) { + MENU = SETTIME; + //prevsettime += millis(); + //prevtempint+=millis(); + } + else if (y==0) { + MENU = RALLY; + //prevtemprally=millis(); + } + else if (y==2) MENU = CONSTANTA; + else if (y==3) { + MENU = CALIBRATION; + //prevcalibrationtime+=millis(); + } + break; + + case CONSTANTA: + if (y==0) MENU = MAIN; + //else if (!blinkON && y==1) { + + // } + else if (!blinkON && y==2) { + constantatodigit(); + lcd.blink(); + blinkON=!blinkON; + } + else if (!blinkON && y==3) { + sec60 = starttractsec; + min60 = starttractmin; + hour24 = starttracthour; + lcd.blink(); + blinkON=!blinkON; + } + else if (!blinkON && y==1) { + prevTrip = curTrip; + lcd.blink(); + blinkON = !blinkON; + } + else if (blinkON && y==1) { + curTrip = prevTrip; + constanta = Trip[curTrip].speed; + starttractsec = Trip[curTrip].startSec; + starttractmin = Trip[curTrip].startMin; + starttracthour = Trip[curTrip].startHour; + lcd.noBlink(); + blinkON=!blinkON; + constantaMenu(); + } + else if (blinkON && y==2) { + lcd.noBlink(); + blinkON=!blinkON; + constanta = (digit1*10)+digit2+(float)digit3/10+(float)digit4/100+(float)digit5/1000+(float)digit6/10000; //+(float)digit6/100000; + //mem.writeFloat(800, constanta); + int pointeradd = ((TRIPADDRESS+curTrip)*32); + mem.writeFloat(pointeradd, constanta); + Trip[curTrip].speed = constanta; +#ifdef DEBUG + Serial.println(pointeradd); Serial.print(";");Serial.println(constanta,5); +#endif + } + else if (blinkON && y==3) { + starttractsec=sec60; + starttractmin=min60; + starttracthour=hour24; + unsigned long valuesettime = starttracthour; + valuesettime = valuesettime * 256 + starttractmin; // effectively shift the first byte 8 bit positions + valuesettime = valuesettime * 256 + starttractsec; + //mem.writeLong(768,valuesettime); + int pointeradd = ((TRIPADDRESS+curTrip)*32+4); + mem.writeLong(pointeradd, valuesettime); + Trip[curTrip].startHour = starttracthour; + Trip[curTrip].startMin = starttractmin; + Trip[curTrip].startSec = starttractsec; + lcd.noBlink(); + blinkON=!blinkON; +#ifdef DEBUG + Serial.println(pointeradd); Serial.println(valuesettime); +#endif + } + else {// if (y==3) { + lcd.blink(); + blinkON=!blinkON; + } + break; + + case RALLY: +#ifdef DEBUG + Serial.println("OKRALLY"); +#endif + switch(CURSOR_POS) + { + case 1: + count1 = 0; + backcount1 = 0; + time1 = VSSCount; + //Serial.println("case 1"); + break; + case 2: + count2 = 0; + backcount2 = 0; + time2 = VSSCount; + //Serial.println("case 2"); + break; + case 3: + count2 = count1; //no yet UNDO next update can UNDO + backcount2 = 0; + //time2 = VSSCount; + //Serial.println("case 3"); + break; + case 4: + count1 = count2; //no yet UNDO next update can UNDO + backcount1 = 0; + //time1 = VSSCount; + //Serial.println("case 4"); + break; + case 5: + //dirfwdcount1 = !dirfwdcount1; + switch (dircount1) + { + case FORWARD: + dircount1 = FREEZE; + break; + case FREEZE: + dircount1 = BACKWARD; + break; + case BACKWARD: + dircount1 = FORWARD; + break; + default: + dircount1 = FORWARD; + break; + } + secondrallyMenu(); + //Serial.println("case 5"); + break; + case 6: + //dirfwdcount2 = !dirfwdcount2; + switch (dircount2) + { + case FORWARD: + dircount2 = FREEZE; + break; + case FREEZE: + dircount2 = BACKWARD; + break; + case BACKWARD: + dircount2 = FORWARD; + break; + default: + dircount2 = FORWARD; + break; + } + secondrallyMenu(); + //Serial.println("case 6"); + break; + case 7: + showTIME = !showTIME; + rallyMenu(); + break; + case 8: + showTIME = !showTIME; + rallyMenu(); + break; + case 9: + //Serial.println("case 9"); + MENU = MAIN; + lcd.noBlink(); + break; + case 10: + //Serial.println("case 10"); + MENU = MAIN; + lcd.noBlink(); + break; + + } + break; + + case CALIBRATION: + if (blinkON && y==1) { + lcd.noBlink(); + blinkON=!blinkON; + calibrationDistance = tempcalibdist; + } + else if (!blinkON && y==1) { + lcd.blink(); + blinkON=!blinkON; + tempcalibdist = calibrationDistance; + } + else if (!blinkON && y==2) { + //startCalibration = millis(); + Calibrationcount = 0; + startCalibration = VSSCount; + Calibrationtime = startCalibration; + blinkON=!blinkON; + lcd.blink(); + calibrationON=true; + lcd.setCursor(0,2); + lcd.print("Calibrating 00.000Km"); + } + else if (blinkON && y==2) { + Calibration = (VSSCount-startCalibration)/(float)calibrationDistance; + mem.writeLong(896, Calibration); //Save Calibration to memory + oneMeter=(millis()-startCalibration)/(1000*(float)calibrationDistance);//*calibrationDistance); + oneMeter=((float)VSSCount-startCalibration)/(1000*(float)calibrationDistance);//*calibrationDistance); + oneMeter=(float)(Calibration)/1000*(float)calibrationDistance; + blinkON=!blinkON; + lcd.noBlink(); + calibrationON=false; + lcd.setCursor(0,2); + lcd.print("Start "); + lcd.setCursor(0,3); + lcd.print("1m="); + //Serial.print(startCalibration);Serial.print(";");Serial.print((millis()-startCalibration)/1000);Serial.print(";"); +#ifdef DEBUG + Serial.println(oneMeter,5); +#endif + lcd.print(oneMeter,3); + lcd.print(";"); + } + else if (!blinkON && y==3) { //not yet implemented + lcd.blink(); + blinkON=!blinkON; + calibdigit1 = (byte)(Calibration/10000); + calibdigit2 = (byte)((Calibration % 10000)/100); + calibdigit3 = Calibration % 100; + //Serial.println(calibdigit1);Serial.println(calibdigit2);Serial.println(calibdigit3); + } + else if (blinkON && y==3) { + lcd.noBlink(); + blinkON=!blinkON; + //Serial.println(calibdigit1);Serial.println(calibdigit2);Serial.println(calibdigit3); + Calibration = ((long)calibdigit1*10000) + ((long)calibdigit2*100) + (calibdigit3); + //Serial.println(Calibration); + mem.writeLong(896, Calibration); + } + else if (y==0) MENU = MAIN; + break; + + case SETTIME: + if (blinkON && y==3) { + t.sec=sec60; + t.min=min60; + t.hour=hour24; + DS3231_set(t); + lcd.noBlink(); + blinkON=!blinkON; + //Serial.println("OKAY"); + } + else if (y==3) { + lcd.blink(); + blinkON=!blinkON; + } + else {//(blinkON) { + MENU = MAIN; + lcd.noBlink(); + } + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case RALLYEDIT: + if ((CURSOR_POS == 1 || CURSOR_POS == 2) && !blinkON) { + rallyEdit = true; + blinkON = true; + lcd.blink(); + //if (distance<100) { + dist1digit1=((int)distance1%1000); + dist1digit2=(int)((distance1 - (int)distance1)*1000); + dist2digit1=((int)distance2%1000); + dist2digit2=(int)((distance2 - (int)distance2)*1000); + //} + /* + Serial.print(dist1digit1);Serial.println(dist1digit2); //Serial.print(dist1digit3); Serial.print(dist1digit4);Serial.println(dist1digit5);//Serial.println(digit6); + Serial.println(distance1,3); + Serial.print(dist2digit1);Serial.println(dist2digit2); //Serial.print(dist1digit3); Serial.print(dist1digit4);Serial.println(dist1digit5);//Serial.println(digit6); + Serial.println(distance2,3); + */ + } + else if (blinkON) { //set the new distance to count + blinkON = false; + rallyEdit = false; + /* + Serial.println(count1); + Serial.println(distance1,5); + Serial.println(""); + */ + if (CURSOR_POS == 1) { + distance1 = dist1digit1 + (float)dist1digit2/1000; + count1 = (unsigned long)(distance1 * Calibration) + 5; + //distance1 = (float)count1/((float)Calibration); + }else if (CURSOR_POS == 2) { + distance2 = dist2digit1 + (float)dist2digit2/1000; + count2 = (unsigned long)(distance2 * Calibration) + 5; + //distance2 = (float)count2/((float)Calibration); + } + /* + Serial.println(count1); + Serial.println(distance1,3); + */ + set_cursor_pos(CURSOR_POS); + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case ESC: + switch (MENU) + { + case RALLY: + lcd.noBlink(); + MENU=MAIN; + if (rallyEdit) { + rallyEdit = false; + lcd.blink(); + MENU = RALLY; + set_cursor_pos(CURSOR_POS); + } + blinkON=false; + + break; + case SETTIME: + lcd.noBlink(); + if (!blinkON) MENU = MAIN; + blinkON=false; + //MENU=MAIN; + break; + case CONSTANTA: + //MENU=MAIN; + if (!blinkON) MENU = MAIN; + else constantaMenu(); + lcd.noBlink(); + blinkON=false; + break; + case CALIBRATION: + lcd.noBlink(); + if (!blinkON) MENU = MAIN; + blinkON=false; + calibrationON=false; + //MENU=MAIN; + break; + + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + } + +//***************************************************************** +//*************************************** M E N U ***************** +// +// +// +//*************************************** M E N U ***************** +//***************************************************************** + + if (PREVMENU!=MENU) + { + switch (MENU) + { + case (MAIN): + mainMenu(); + break; + + case (RALLY): + lcd.clear(); + rallyMenu(); + rallyON=true; + //lcd.blink(); + CURSOR_POS=10; + set_cursor_pos(CURSOR_POS); + break; + + case (SETTIME): + lcd.clear(); + settimeMenu(); + sec60=t.sec; + min60=t.min; + hour24=t.hour; + lcd.setCursor(0,3); + lcdprint2digit(hour24); + lcd.print(":"); + lcdprint2digit(min60); + lcd.print(":"); + lcdprint2digit(sec60); + x=0; + y=2; + lcd.setCursor(x,y); + break; + + case (CALIBRATION): + calibrationMenu(); + break; + + case CONSTANTA: + sec60=starttractsec; + min60=starttractmin; + hour24=starttracthour; + x = 16; + y = 0; + constantaMenu(); + break; + + case (INPUTSUBTRAYEK): + break; + } + } + + if (MENU==RALLY) { + if ((now1 - prevtemprally) >= tempintervalrally) { + //if ((long)(now1 - prevtemprally) >= 0) { + //rallyMenu(); + if (!rallyEdit) redrawrallyMenu(); //Distance is edited? + prevtemprally=now1; + //prevtemprally+=tempintervalrally; + } + } + + if (MENU==SETTIME) { + //if ((long)(now1 - prevtempint) >=0 ){ + if ((now1 - prevtempint) >=tempinterval ){ + temperature = DS3231_get_treg(); //Get temperature + dtostrf(temperature, 5, 1, tempF); + lcd.setCursor(9,1); + lcd.print(tempF); + lcd.print((char)223); + lcd.print("C "); + //prevtempint+=tempinterval; + prevtempint=now1; + lcd.setCursor(x,y); + //lcd.setCursor(15,0); + //lcd.print(now); + } + //if ((long)(now1- prevsettime) >=0 ){ //show SET TIME MENU + if ((now1 - prevsettime) >=intervalsettime ){ //show SET TIME MENU + DS3231_get(&t); //Get time + if (prevsec!=t.sec) { //will update the LCD every sec(as long as the t.sec is different) eventhough intervalseetime is 250ms + settimeMenu(); + prevsettime = now1; + //prevsettime += intervalsettime; + } + } + } + + if (MENU==CALIBRATION) { + if (calibrationON) { + if ((now1 - prevcalibrationtime) >= calibrationtimeinterval ) { + //if ((long)(now1 - prevcalibrationtime) >=0 ) { + redrawcalibrationMenu(); + char Calibrationstr[6]; + unsigned long calibtemp = VSSCount - startCalibration; + sprintf(Calibrationstr, "%06lu", calibtemp); + lcd.setCursor(14,3); + lcd.print(Calibrationstr); + lcd.setCursor(x,y); + prevcalibrationtime=now1; + //prevcalibrationtime+=calibrationtimeinterval; + } + } + } + + //if (((long)(millis()-startmillis)>=0) && MENU!=CALIBRATION) { + if ((now1-startmillis)>=500) { //&& MENU!=CALIBRATION && MENU!=MAIN) { + unsigned long VSSCountDiff = VSSCount - startVSSCount; + startVSSCount=VSSCount; + if ((VSSCountDiff == 0) && savedCount) { + intervalsavemillis = 4000000; + } + else if ((VSSCountDiff == 0) && !savedCount) { + saveCount(); + savedCount = !savedCount; + intervalsavemillis = 2000000; + } + else if (VSSCountDiff < 15) intervalsavemillis = 3000; + else if (VSSCountDiff < 70) intervalsavemillis = 60000; + else intervalsavemillis = 4000000; + if (VSSCountDiff > 0) savedCount = false; + if (MENU!=CALIBRATION && MENU!=MAIN && MENU!=CONSTANTA) { + lcd.setCursor(0,0); + if (VSSCountDiff==0) lcd.print("0"); + else if (VSSCountDiff <= 10) lcd.print("1"); + else if (VSSCountDiff <= 50) lcd.print("2"); + else if (VSSCountDiff <= 150) lcd.print("3"); + else if (VSSCountDiff <= 250) lcd.print("4"); + else if (VSSCountDiff <= 400) lcd.print("5"); + else if (VSSCountDiff <= 600) lcd.print("6"); + else if (VSSCountDiff <= 900) lcd.print("7"); + else if (VSSCountDiff <= 1200) lcd.print("8"); + else if (VSSCountDiff > 1200) lcd.print("9"); + + //lcd.print(VSSCountDiff); + //lcd.print(" "); + lcd.setCursor(x,y); + } + //startmillis+=400; + startmillis=now1; + + } + +/* + if (((millis() % 100)==0) && MENU!=CALIBRATION) { + lcd.setCursor(0,2); + lcd.print(VSSCount); + lcd.print(" "); + lcd.setCursor(x,y); + } +*/ + if ((millis()-updatecounttime)>=250) { + updateCount(); + updatecounttime = millis(); + } + + if ((millis()-startsavemillis) > intervalsavemillis) { + saveCount(); + //startsavemillis += 3000; + startsavemillis = millis(); + } + if ((millis()-broadcastwebsocket) > 1000) { + broadcastwebsocket = millis(); + ws.textAll(getPin()); + wscal.textAll(getCalib()); + } +#ifdef DEBUG + Serial.print(micros()-prevtimemicros); Serial.println("**"); +#endif +} diff --git a/backup/backup_main_before tryingVSSRALLYv2only.cpp b/backup/backup_main_before tryingVSSRALLYv2only.cpp new file mode 100644 index 0000000..40e3bb1 --- /dev/null +++ b/backup/backup_main_before tryingVSSRALLYv2only.cpp @@ -0,0 +1,2844 @@ +/********* + Rui Santos + Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-input-data-html-form/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files. + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. +*********/ + +#include +#ifdef ESP32 + #include + #include + #include +#else + #include + #include + #include + #include +#endif +#include +//#include +#include +#include +#include +#include +//#include + +AsyncWebServer server(80); +AsyncWebSocket ws("/ws"); +AsyncWebSocket wscal("/wscal"); +//WiFiManager wifiManager; + +// REPLACE WITH YOUR NETWORK CREDENTIALS +char ssid[] = "WiFi_SuGi"; +char password[] = "12345678901"; + +//strcpy(ssid,"WiFi_SuGi"); + +//password = "1234567890"; + +const char *soft_ap_ssid = "MyESP32AP"; +const char *soft_ap_password = "testpassword"; + +const char* PARAM_STRING = "inputString"; +const char* PARAM_INT = "inputInt"; +const char* PARAM_FLOAT = "inputFloat"; + +const char* PARAM_SSID = "ssidString"; +const char* PARAM_PWD = "inputPwd"; + +const char* ntpServer = "pool.ntp.org"; +const long gmtOffset_sec = 7*3600; +const int daylightOffset_sec = 0; + + + +void notFound(AsyncWebServerRequest *request) { + request->send(404); +} + +String readFile(fs::FS &fs, const char * path){ + Serial.printf("Reading file: %s\r\n", path); + File file = fs.open(path, "r"); + if(!file || file.isDirectory()){ + Serial.println("- empty file or failed to open file"); + return String(); + } + Serial.print("- read from file:"); + String fileContent; + while(file.available()){ + fileContent+=String((char)file.read()); + } + file.close(); + Serial.println(fileContent); + return fileContent; +} + +void writeFile(fs::FS &fs, const char * path, const char * message){ + Serial.printf("Writing file: %s\r\n", path); + File file = fs.open(path, "w"); + if(!file){ + Serial.println("- failed to open file for writing"); + return; + } + if(file.print(message)){ + Serial.println("- file written"); + } else { + Serial.println("- write failed"); + } + file.close(); +} + +// Replaces placeholder with stored values +String processor(const String& var){ + //Serial.println(var); + Serial.print("Processor "); + Serial.print(var); + if(var == "inputString"){ + return readFile(SPIFFS, "/inputString.txt"); + } + else if(var == "inputInt"){ + return readFile(SPIFFS, "/inputInt.txt"); + } + else if(var == "inputFloat"){ + return readFile(SPIFFS, "/inputFloat.txt"); + } + else if(var == "ssidString"){ + return readFile(SPIFFS, "/ssidString.txt"); + } + else if(var == "localip"){ + return WiFi.localIP().toString(); + } + else if(var == "serveripaddress"){ + if (WiFi.localIP().toString()!="0.0.0.0"){ + Serial.println(WiFi.localIP()); + return WiFi.localIP().toString(); + } else { + Serial.println(WiFi.softAPIP()); + return WiFi.softAPIP().toString(); + } + } + // else if(var == "inputPwd"){ + // return readFile(SPIFFS, "/inputPwd.txt"); + // } + return String(); +} + + + + +void OnWiFiEvent(WiFiEvent_t event) +{ + switch (event) { + + case SYSTEM_EVENT_STA_CONNECTED: + Serial.println("ESP32 Connected to WiFi Network"); + break; + case SYSTEM_EVENT_AP_START: + Serial.println("ESP32 soft AP started"); + break; + case SYSTEM_EVENT_AP_STACONNECTED: + Serial.println("Station connected to ESP32 soft AP"); + break; + case SYSTEM_EVENT_AP_STADISCONNECTED: + Serial.println("Station disconnected from ESP32 soft AP"); + break; + default: break; + } +} +String getPin(){ + struct tm timeinfo; + String hasil; + if(!getLocalTime(&timeinfo)){ + Serial.println("Failed to obtain time"); + return hasil; + } + // StaticJsonBuffer<200> jsonBuffer; + // JsonObject& root = JsonBuffer.createObject(); + DynamicJsonDocument testdoc(512); + //String datetime = &timeinfo; + char datetime[21]; + char curtime[9]; + strftime(datetime, 21, "%d %b %Y %H:%M:%S", &timeinfo); + strftime(curtime, 9, "%H:%M:%S", &timeinfo); + //Serial.println(&timeinfo); + //Serial.println(datetime); + testdoc["pin36"]=242; + testdoc["pin39"]=datetime; + testdoc["time"]=curtime; + // testdoc["datetime"]=datetime; + testdoc["pin5"]=millis(); + testdoc["curtime"]=curtime; + testdoc["speed"]=String(float(random(1,20000))/100,1); + testdoc["counter"]=random(0,50000); + String bb[]={"A","B","C","D","E","F","G","H","I","J","K","L"}; + testdoc["curtrack"]=bb[random(12)]; + String dir[]={"FW","STOP","BACK"}; + testdoc["dir1"]=dir[random(3)]; + testdoc["dir2"]=dir[random(3)]; + testdoc["time1"]=curtime; + testdoc["time2"]=curtime; + float odo1=float(millis())/10000; + float odo2=float(millis())/20000; + //Serial.println(odo1,3); + testdoc["odo1"]=String(odo1,3); + testdoc["odo2"]=String(odo2,3); // if disabled, the web will get undefined value + //serializeJson(testdoc,Serial); + serializeJson(testdoc,hasil); + //testdoc.printTo(hasil); + // testdoc.clear(); + return hasil; +} +String getCalib(){ + struct tm timeinfo; + String hasil; + if(!getLocalTime(&timeinfo)){ + Serial.println("Failed to obtain time"); + return hasil; + } + DynamicJsonDocument testdoc(200); + //String datetime = &timeinfo; + char datetime[21]; + char curtime[9]; + strftime(datetime, 21, "%d %b %Y %H:%M:%S", &timeinfo); + strftime(curtime, 9, "%H:%M:%S", &timeinfo); + //Serial.println(&timeinfo); + //Serial.println(datetime); + // testdoc["datetime"]=datetime; + testdoc["curtime"]=curtime; + testdoc["speed"]=String(float(random(1,20000))/100,1); + testdoc["counter"]=random(0,50000); + String bb[]={"A","B","C","D","E","F","G","H","I","J","K","L"}; + testdoc["curtrack"]=bb[random(12)]; + float calkm=float(millis())/100000; + float calmeter=float(millis())/100; + testdoc["caldist"]=random(9); + testdoc["calman"]=random(100000, 150000); + testdoc["calkm"]=String(calkm,3); + testdoc["calmeter"]=String(calmeter,3); + //Serial.println(odo1,3); + testdoc["calval"]=String(calmeter*1000); // if disabled, the web will get undefined value + //serializeJson(testdoc,Serial); + serializeJson(testdoc,hasil); + //testdoc.printTo(hasil); + // testdoc.clear(); + return hasil; +} + +void printLocalTime(){ + struct tm timeinfo; + if(!getLocalTime(&timeinfo)){ + Serial.println("Failed to obtain time"); + return; + } + Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S"); + Serial.print("Day of week: "); + Serial.println(&timeinfo, "%A"); + Serial.print("Month: "); + Serial.println(&timeinfo, "%B"); + Serial.print("Day of Month: "); + Serial.println(&timeinfo, "%d"); + Serial.print("Year: "); + Serial.println(&timeinfo, "%Y"); + Serial.print("Hour: "); + Serial.println(&timeinfo, "%H"); + Serial.print("Hour (12 hour format): "); + Serial.println(&timeinfo, "%I"); + Serial.print("Minute: "); + Serial.println(&timeinfo, "%M"); + Serial.print("Second: "); + Serial.println(&timeinfo, "%S"); + + Serial.println("Time variables"); + char timeHour[3]; + strftime(timeHour,3, "%H", &timeinfo); + Serial.println(timeHour); + char timeWeekDay[10]; + strftime(timeWeekDay,10, "%A", &timeinfo); + Serial.println(timeWeekDay); + Serial.println(); +} + +boolean isDecimal(String str){ +for(byte i=0;iremoteIP()); + client->text(getPin()); + } else if(type == WS_EVT_DISCONNECT){ + Serial.println("Client disconnected"); + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + } else if(type == WS_EVT_DATA){ + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + Serial.printf("[%u] get Text: %s\n", len, data); + String message = String((char*)( data)); + Serial.println(message); + + DynamicJsonDocument doc(256); + // Deserialize the data + DeserializationError error = deserializeJson(doc, message); + // parse the parameters we expect to receive (TO-DO: error handling) + // test if parsing succeeds + if (error){ + Serial.print("deserialiseJson() failed: "); + Serial.println(error.c_str()); + client->text(error.c_str()); + return; + } + String ledstatus=doc["LED1"]; + if (ledstatus=="null"){Serial.println("led1 is null");} + Serial.print("LED1=");Serial.println(ledstatus); + } +} + +void onWsEvent2(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){ + if(type == WS_EVT_CONNECT){ + Serial.println("wscal Websocket client connection received"); + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + client->text(getCalib()); + } else if(type == WS_EVT_DISCONNECT){ + Serial.println("wscal Client disconnected"); + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + } else if(type == WS_EVT_DATA){ + Serial.print("wscal IPAdd client:"); Serial.println(client->remoteIP()); + Serial.printf("[%u] get Text: %s\n", len, data); + String message = String((char*)( data)); + Serial.println(message); + + DynamicJsonDocument doc(200); + // Deserialize the data + DeserializationError error = deserializeJson(doc, message); + // parse the parameters we expect to receive (TO-DO: error handling) + // test if parsing succeeds + if (error){ + Serial.print("wscal deserialiseJson() failed: "); + Serial.println(error.c_str()); + client->text(error.c_str()); + return; + } + String setdis=doc["setdis"]; + String setcal=doc["setcal"]; + String calstart=doc["calstart"]; + Serial.print("setdis=");Serial.println(setdis); + Serial.print("setcal=");Serial.println(setcal); + Serial.print("calstart=");Serial.println(calstart); + if (setdis!="null"){ + if (isDecimal(setdis)){ + Serial.print("setdis=");Serial.println(setdis.toInt()); + } + } + if (setcal!="null"){ + if (isDecimal(setcal)){ + Serial.print("setcal=");Serial.println(setcal.toInt()); + } + } + if (calstart="null"){ + if (isDecimal(calstart)){ + if(calstart=="1"){ + Serial.print("calstart=");Serial.println("START"); + } else if(calstart=="0"){ + + } + Serial.print("calstart=");Serial.println("STOP"); + } + } + } +} + +// void configModeCallback (WiFiManager *myWiFiManager) { +// Serial.println("Entered config mode"); +// Serial.println(WiFi.softAPIP()); + +// Serial.println(myWiFiManager->getConfigPortalSSID()); +// } + + + +////// VSSRALLYMODULE +// +// +// +// +// +// +// +// +// +#ifndef min +#define min(a,b) (((a) < (b)) ? (a) : (b)) +#endif +#ifndef max +#define max(a,b) (((a) > (b)) ? (a) : (b)) +#endif + +#include +#include +#include +#include + +//#define BUFF_MAX 128 + +//****************************************Define I2C LCD Display ********************************* +#define I2C_ADDR 0x27 // Define I2C Address for the PCF8574T +//---(Following are the PCF8574 pin assignments to LCD connections )---- +// This are different than earlier/different I2C LCD displays + +#define Rs_pin 0 +#define Rw_pin 1 +#define En_pin 2 +#define BACKLIGHT_PIN 3 +#define D4_pin 4 +#define D5_pin 5 +#define D6_pin 6 +#define D7_pin 7 +#define UP_pin 14 //4 +#define DOWN_pin 12 //5 +#define LEFT_pin 27 //6 +#define RIGHT_pin 26 //7 +#define OK_pin 25 //8 + +#define ATMEGA328 //comment out this line if it is not ATMEGA328 +//#define DEBUG //comment out this line to disable for Production(No Serial print) + +#define RRcountSIZE 20 +#define count1Address 0 +#define count1count2diffAddress 40 //only one address which is 40*32 +//int count1Address = 0; +//int count1count2diffAddress = 40; +long count1count2diff = 0; + +#define TRIPSIZE 12 //so thestartaddress is 50*32 until (50+12)*32 +#define TRIPADDRESS 50 + +const byte interruptPin = 2; +const byte ledPin = 13; + +#ifndef ATMEGA328 + volatile byte ledstate = LOW; +#endif + +#define LED_OFF 0 +#define LED_ON 1 + +// set the LCD number of columns and rows +const int lcdColumns = 20; +const int lcdRows = 4; + +// set LCD address, number of columns and rows +// if you don't know your display address, run an I2C scanner sketch +LiquidCrystal_I2C lcd(I2C_ADDR, lcdColumns, lcdRows); + +/*-----( Declare objects )-----*/ +//LiquidCrystal_I2C lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin); +AT24CX mem; +boolean cursorON=true; +boolean blinkON=true; +//************************************ END LCD DISPLAY ******************************************* + +uint8_t thistime[8]; +//char recv[BUFF_MAX]; +unsigned int recv_size = 0; +unsigned long prevsettime, intervalsettime = 250; +unsigned long prevtempint, tempinterval=60000; +unsigned long prevtemprally, tempintervalrally=200; +unsigned long prevcalibrationtime, calibrationtimeinterval = 100; +unsigned long updatecounttime=0; +float temperature; +volatile byte x; +volatile byte y; +// #ifndef y++ +// //#define min(a,b) (((a) < (b)) ? (a) : (b)) +// #define y++ y+1 +// #endif +// #ifndef x++ +// //#define min(a,b) (((a) < (b)) ? (a) : (b)) +// #define x++ x+1 +// #endif + +unsigned long startmillis, startVSSCount; +unsigned long startsavemillis; +unsigned long broadcastwebsocket; + +//#include //https://github.com/JChristensen/Button //from change to +#include + +#define DN_PIN 5 //Connect two tactile button switches (or something similar) +#define UP_PIN 4 //from Arduino pin 2 to ground and from pin 3 to ground. +#define LF_PIN 6 +#define RF_PIN 7 +#define OK_PIN 8 +#define ESC_PIN 10 +#define PULLUPRES true //To keep things simple, we use the Arduino's internal PULLUPRES resistor. +#define INVERT true //Since the pullup resistor will keep the pin high unless the + //switch is closed, this is negative logic, i.e. a high state + //means the button is NOT pressed. (Assuming a normally open switch.) +#define DEBOUNCE_MS 40 //A debounce time of 20 milliseconds usually works well for tactile button switches. + +#define REPEAT_FIRST 1000 //ms required before repeating on long press +#define REPEAT_INCR 75 //repeat interval for long press +#define MIN_COUNT 0 +#define MAX_ROW 3 +#define MAX_COL 19 +#define MS_IN_HOUR 3600000 //Number of ms in an hour +#define MS_IN_MIN 60000 //Number of ms in a minute +Button btnUP(UP_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); //Declare the buttons +Button btnDN(DN_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); +Button btnLF(LF_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); +Button btnRF(RF_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); //Declare the buttons +Button btnOK(OK_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); //Declare the buttons +Button btnESC(ESC_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); //Declare the buttons +enum {WAIT, UP, DOWN, LEFT, RIGHT, OKAY, RALLYEDIT, ESC}; //The possible states for the STATE machine +enum {MAIN, CALIBRATION, SETTIME, INPUTSUBTRAYEK, RALLY, CONSTANTA}; //The possible states for the MENU +enum {FORWARD, FREEZE, BACKWARD}; +char const *dircount[] = {"Fw", "Zz", "Bw"}; //CHANGE 2022 +//String dircount[] = {"Fw", "Zz", "Bw"}; + +uint8_t MENU, PREVMENU; +uint8_t STATE, dircount1, dircount2; //The current state machine state +byte hour24, min60, sec60; +unsigned long rpt = REPEAT_FIRST; //A variable time that is used to drive the repeats for long presses +uint8_t prevsec; +float constanta=3.275; +float distance1, distance2; +float prevdistance1, prevdistance2; +long prevcount1, prevcount2; +boolean showTIME = true; + +float tempval; +struct ts t; +byte calibrationDistance=1; +byte tempcalibdist=1; +boolean calibrationON=false; + +float oneMeter=0; +unsigned long startCalibration=0; +unsigned long Calibration=110400; //for CR-V 2012 +unsigned long Calibrationcount; +unsigned long Calibrationtime; +int digit1, digit2, digit3, digit4, digit5, digit6; +byte calibdigit1, calibdigit2, calibdigit3; +int dist1digit1, dist1digit2; +int dist2digit1, dist2digit2; +byte starttractsec, starttractmin, starttracthour; +boolean rallyON=false; + +volatile unsigned long VSSCount =0; + +long count1 = 0; //must be signed as technically distance can go negative +long count2 = 0; +long backcount1 = 0; +long backcount2 = 0; + +//The two time variables are used to store reset times in ms +unsigned long time1 = 1; +unsigned long time2 = 1; +int CURSOR_POS = 1; + +unsigned long count1Seq = 0; +boolean editDist1 = false; + +//to save trayek data +struct RallyData { + char sub; + float speed; + byte startHour; + byte startMin; + byte startSec; +// float distance; +// unsigned int subTime; +}; + //RallyData Trip={"b",23.342, 11,0,0,12.13}; + RallyData Trip[TRIPSIZE]; +//RallyData currentTrip; +byte curTrip=0; +byte prevTrip=0; + + +void printUPchar() +{ + byte thumb1[8] = {B00100,B01110,B11111,B00100,B00100,B00100,B00100,B00100}; + lcd.createChar(1, thumb1); + //lcd.write(1); +} +void printDOWNchar() +{ + byte thumb1[8] = {B00100,B00100,B00100,B00100,B00100,B11111,B01110,B00100}; + lcd.createChar(2, thumb1); + //lcd.write(2); +} +// unsigned long memretrieveLong(int startaddress, byte rrpointersize, unsigned long &seq ) +// { +// //Serial.print(seq);Serial.print(";R ");Serial.print(rrpointer[0]);Serial.print("; SizeofArr=");Serial.println(rrpointersize); +// unsigned long largestcountpointer=0; +// int lastpointer = 0; +// unsigned long seqnumber = 0; +// int pointeradd = 0; +// for (int i = 0; i");Serial.println(mem.readLong(pointer+(i*32))); + } +} +*/ + +// void memretrieveTrip(int pointer, int startaddress) +// { +// //Serial.print (pointer); Serial.println(startaddress); +// int pointeradd; +// Trip[pointer].speed = mem.readFloat(startaddress); +// pointeradd = (startaddress + 6); +// Trip[pointer].startHour = mem.read(pointeradd); +// pointeradd = (startaddress + 5); +// Trip[pointer].startMin = mem.read(pointeradd); +// pointeradd = (startaddress + 4); +// Trip[pointer].startSec = mem.read(pointeradd); +// if (Trip[pointer].startHour >= 24) Trip[pointer].startHour = 23; +// if (Trip[pointer].startMin >= 60) Trip[pointer].startMin = 59; +// if (Trip[pointer].startSec >= 60) Trip[pointer].startSec = 59; +// } + +void constantatodigit() +{ + digit1=(int)(constanta/10); + digit2=(int)constanta%10; + digit3=(int)((constanta - (int)constanta)*10); + digit4=(int)((constanta*10 - (int)(constanta*10))*10); + digit5=(int)((constanta*100 - (int)(constanta*100))*10); + digit6=(int)((constanta*1000 - (int)(constanta*1000))*10); + //digit6=(int)((constanta*10000 - (int)(constanta*10000))*10); +} + +void blink() { +#ifndef ATMEGA328 + ledstate = !ledstate; +// #else +// PORTB ^= B00100000; +#endif + VSSCount++; +} + + +// void setupcopyfromvssrally() +// { +// // Serial.begin(115200); +// #ifdef DEBUG +// Serial.begin(115200); +// Serial.println("Starting Rally"); +// #endif +// Wire.begin(); +// pinMode(UP_pin, INPUT_PULLUP); +// pinMode(DOWN_pin, INPUT_PULLUP); +// pinMode(LEFT_pin, INPUT_PULLUP); +// pinMode(RIGHT_pin, INPUT_PULLUP); +// pinMode(OK_pin, INPUT_PULLUP); +// //DS3231_init(DS3231_INTCN); +// DS3231_init(DS3231_CONTROL_INTCN); +// //memset(recv, 0, BUFF_MAX); +// #ifdef DEBUG +// Serial.println("GET time"); +// #endif +// /* +// Trip[0].sub = "A"; +// Trip[0].speed = 24.275; +// Trip[0].startHour = 25; +// //Trip[0].distance = 12.898; +// Trip[9].sub = "A"; +// Trip[9].speed = 90.2751; +// Trip[9].startHour = 22; +// Trip[9].startMin = 59; +// Trip[9].startSec = 58; +// */ +// //Trip[9].distance = 12.898; +// //Serial.println(Trip[0].sub);Serial.println(Trip[0].speed);Serial.println(Trip[0].startHour);Serial.println(Trip[0].startMin);Serial.println(Trip[0].startSec); +// //Serial.println(Trip[0].distance); +// //Serial.println(Trip[0].subTime); + +// for (int i = 0; i23) starttracthour = 23; +// if (starttractmin>59) starttractmin = 59; +// if (starttractsec>59) starttractsec = 59; +// //constanta=mem.readFloat(800); +// constanta = Trip[curTrip].speed; +// if ((constanta > 150) || (constanta < 0)) constanta = 60; +// long m = mem.readLong(896); //read calibration value; +// if (m >= 0) { +// Calibration = m; +// } +// #ifdef DEBUG +// Serial.println(m); +// Serial.println(Calibration); +// Serial.println(constanta); +// #endif +// constantatodigit(); + +// // Serial.print(digit1);Serial.print(digit2); Serial.print(digit3); Serial.print(digit4);Serial.print(digit5);Serial.println(digit6); +// // Serial.println(constanta,5); +// //Serial.print(digitalRead(UP_pin));Serial.print(digitalRead(DOWN_pin));Serial.print(digitalRead(LEFT_pin));Serial.print(digitalRead(RIGHT_pin));Serial.println(digitalRead(OK_pin)); + +// prevcount1 = count1; +// prevcount2 = count2; + +// prevcalibrationtime+=calibrationtimeinterval; +// prevtempint+=tempinterval; +// prevtemprally+=tempintervalrally; +// prevsettime += intervalsettime; +// startmillis+=1000; + +// pinMode(ledPin, OUTPUT); +// pinMode(interruptPin, INPUT); //Pull down using resistor to ground +// attachInterrupt(digitalPinToInterrupt(interruptPin), blink, FALLING); + +// mainMenu(); +// } + + + + + +#ifdef DEBUG +long prevtimemicros=micros(); //************************************************************************** +#endif +unsigned long rallyEditTime=micros(); +byte rallyEditRpt = 0; +boolean rallyEdit =false; +boolean savedCount = true; +unsigned long intervalsavemillis = 3000; + + +void printMOVEchar() +{ + byte Movechar3[8] = {B00000,B00000,B00000,B00000,B00000,B00000,B00000,B11111}; + lcd.createChar(3, Movechar3); + byte Movechar4[8] = {B00000,B00000,B00000,B00000,B00000,B00000,B11111,B11111}; + lcd.createChar(4, Movechar4); + byte Movechar5[8] = {B00000,B00000,B00000,B00000,B00000,B11111,B11111,B11111}; + lcd.createChar(5, Movechar5); +} + + +void lcdprint2digit(byte val) +{ + if (val<10) lcd.print("0"); + lcd.print(val); +} +void setTheTime(char *cmd) +{ + // ssmmhhWDDMMYYYY set time + + t.sec = inp2toi(cmd, 0); + t.min = inp2toi(cmd, 2); + t.hour = inp2toi(cmd, 4); + t.wday = inp2toi(cmd, 6); + t.mday = inp2toi(cmd, 7); + t.mon = inp2toi(cmd, 9); + t.year = inp2toi(cmd, 11) * 100 + inp2toi(cmd, 13); + DS3231_set(t); +#ifdef DEBUG + Serial.println("OK setTheTime()"); +#endif +} + +void printMonth(int month) +{ + switch(month) + { + case 1: lcd.print(" January ");break; + case 2: lcd.print(" February ");break; + case 3: lcd.print(" March ");break; + case 4: lcd.print(" April ");break; + case 5: lcd.print(" May ");break; + case 6: lcd.print(" June ");break; + case 7: lcd.print(" July ");break; + case 8: lcd.print(" August ");break; + case 9: lcd.print(" September ");break; + case 10: lcd.print(" October ");break; + case 11: lcd.print(" November ");break; + case 12: lcd.print(" December ");break; + default: lcd.print(" Error ");break; + } +} + +void mainMenu() +{ + MENU = MAIN; + lcd.clear(); + lcd.print("1. Rally TSD"); + lcd.setCursor(0,1); + lcd.print("2. Set Main Time"); + lcd.setCursor(0,2); + lcd.print("3. Input Constanta"); + lcd.setCursor(0,3); + lcd.print("4. Calibration ODO"); + //lcd.home(); + x=2; + y=0; + lcd.cursor(); + lcd.setCursor(x,y); + PREVMENU = MENU; +} + +void runningtime(byte x1,byte y1) +{ + lcd.setCursor(x1,y1); //Go to second line of the LCD Screen + if(t.hour<10) + { + lcd.print("0"); + } + lcd.print(t.hour); + lcd.print(":"); + if(t.min<10) + { + lcd.print("0"); + } + lcd.print(t.min); + lcd.print(":"); + if(t.sec<10) + { + lcd.print("0"); + } + lcd.print(t.sec); +} + +void settimeMenu() +{ + lcd.setCursor(0,0); + lcd.print(t.mday); + printMonth(t.mon); + lcd.print(t.year); + + runningtime(0,1); + + lcd.setCursor(x,y); + prevsec = t.sec; + PREVMENU = MENU; +} + + +void calibrationMenu() +{ + MENU = CALIBRATION; + lcd.clear(); + lcd.print("Calibration Back"); + lcd.setCursor(0,1); + lcd.print("Set Distance(Km): "); + lcd.print(calibrationDistance); + lcd.setCursor(0,2); + lcd.print("Start 00.000Km"); + lcd.setCursor(0,3); + lcd.print("1m="); + lcd.print(((float)Calibration/1000),3); + char Calibrationstr[6]; + sprintf(Calibrationstr, "%06lu", Calibration); + lcd.setCursor(14,3); + lcd.print(Calibrationstr); + //lcd.setCursor(0,0); + //lcd.print(Calibration); + //lcd.home(); + x=18; + y=0; + lcd.setCursor(x,y); + lcd.cursor(); + //lcd.blink(); + //blinkON=true; + PREVMENU = MENU; +} + +void constantaMenu() +{ + MENU = CONSTANTA; + lcd.clear(); + lcd.print("Constanta Back"); + lcd.setCursor(0,1); + lcd.print("Sub Trip:"); + lcd.setCursor(14,1); + lcd.print(Trip[curTrip].sub); + lcd.setCursor(0,2); + lcd.print("Set Speed:"); + lcd.setCursor(13,2); + if (constanta<10) lcd.print("0"); + lcd.print(constanta,4); + //lcd.print( + lcd.setCursor(0,3); + lcd.print("Start Time:"); + //DS3231_get(&t); //Get time + lcd.setCursor(12,3); //Go to second line of the LCD Screen + if(starttracthour<10) + { + lcd.print("0"); + } + lcd.print(starttracthour); + lcd.print(":"); + if(starttractmin<10) + { + lcd.print("0"); + } + lcd.print(starttractmin); + lcd.print(":"); + if(starttractsec<10) + { + lcd.print("0"); + } + lcd.print(starttractsec); + lcd.print(""); + //x=14; + //y=0; + lcd.setCursor(x,y); + lcd.cursor(); + //lcd.blink(); + //blinkON=true; + PREVMENU = MENU; + +} +void updateCount() +{ + if (dircount1 == FORWARD) { + count1 = count1 + (VSSCount-time1); + } + else if (dircount1 == BACKWARD) { + count1 = count1 - (VSSCount-time1); + } + + if (dircount2 == FORWARD) { + count2 = count2 + (VSSCount-time2); + } + else if (dircount2 == BACKWARD) { + count2 = count2 - (VSSCount-time2); + } + time1 = VSSCount; + time2 = VSSCount; +} +void saveCount() +{ + if (count1 != prevcount1) { + count1Seq++; +// memwritingLong(count1Address, RRcountSIZE, count1Seq, count1);//(int startaddress, byte RRsize, unsigned long seq, unsigned long Data) + prevcount1 = count1; + } + + if ((count1-count2) != count1count2diff) { +#ifdef DEBUG + Serial.print("count1=");Serial.print(count1);Serial.print(";count2=");Serial.print(count2);Serial.print("countdiff=");Serial.println(count1count2diff); +#endif + count1count2diff = count1-count2; + int pointer = count1count2diffAddress*32; +// mem.writeLong(pointer,count1count2diff); +#ifdef DEBUG + Serial.println("save count1count2diff"); +#endif + } +} + + +void secondrallyMenu() +{ + char heading2[6]; + char heading4[6]; + lcd.setCursor(9,1); + //sprintf(heading2, "%s", (dirfwdcount1?"Fw":"Bw")); + sprintf(heading2, "%s", dircount[dircount1]); + lcd.print(heading2); + + lcd.setCursor(9,3); + //sprintf(heading4, "%s", (dirfwdcount2?"Fw":"Bw")); + sprintf(heading4, "%s", dircount[dircount2]); + lcd.print(heading4); +#ifdef DEBUG + Serial.println("secondrallyMenu"); +#endif +} + +void rallyMenu() +{ + MENU = RALLY; + + //lcd.clear(); + lcd.setCursor(15,0); + if (showTIME) lcd.print("Time "); + else lcd.print("TDiff"); + + secondrallyMenu(); + PREVMENU = MENU; +#ifdef DEBUG + Serial.println("rallyMenu"); +#endif +} + +unsigned long startspeed=0; +float startdistance=0; + +void redrawcalibrationMenu() +{ + float distance; + Calibrationcount = Calibrationcount + (VSSCount-Calibrationtime); + distance = (float)Calibrationcount/((float)Calibration); + char cur_distance_str[6]; + byte xtemp=13; + if (distance<100) { + sprintf(cur_distance_str, "%02d.%03dKm", (int)distance, (int)((distance - (int)distance)*1000)); + xtemp = 12; + } + else if (distance<1000) { + sprintf(cur_distance_str, "%02d.%02dKm", (int)distance, (int)((distance - (int)distance)*100)); + } + else { + sprintf(cur_distance_str, "%03d.%01dKm", (int)distance, (int)((distance - (int)distance)*10)); + } + Calibrationtime = VSSCount; + lcd.setCursor(xtemp,2); + lcd.print(cur_distance_str); +} +void redrawrallyMenu() +{ + DS3231_get(&t); //Get time + //runningtime(6,0); + //float distance, distance1, distance2; + + //Serial.print(tempcount1);Serial.print(";"); Serial.print(time1);Serial.print("; ");Serial.print(Calibration); Serial.print(";"); Serial.println(count1); + updateCount(); + + //distance = (float)count1/((float)Calibration); + distance1 = (float)count1/((float)Calibration); // * 1); + distance2 = (float)count2/((float)Calibration); + float speed1=0; + + if ((distance1 - startdistance) > 0) { + speed1 = (distance1-startdistance)/(millis()-startspeed)*3600000; + } + + startdistance = distance1; + startspeed = millis(); //startspeed is only one no startspeed2 + + if ((millis()-startsavemillis)>0) { + + if (distance1 != prevdistance1) { + mem.writeFloat(832,distance1); + prevdistance1 = distance1; + } + if (distance2 != prevdistance2) { + mem.writeFloat(864,distance2); + prevdistance2 = distance2; + } + saveCount(); + startsavemillis=millis()+2500; + } + //Serial.print(tempcount1);Serial.print(";"); Serial.print(time1);Serial.print("; ");Serial.print(Calibration); Serial.print(";"); Serial.println(count1); + + //Serial.print(millis());Serial.print(";");Serial.println(distance1,3); + //Serial.print(starttracthour); Serial.print(":"); Serial.print(starttractmin); Serial.print(":"); Serial.println(starttractsec); + //Serial.println(distance2,3); + lcd.setCursor(4,0); + lcd.print(Trip[curTrip].sub); + lcd.setCursor(0,2); + //lcd.print(T + lcd.print(Trip[curTrip].speed); + lcd.print("Km/H"); + + runningtime(6,0); + lcd.setCursor(11,2); + char cur_speed_str[8]; + sprintf(cur_speed_str, "%3d.%01dKm/h", (int)speed1, (int)((speed1 - (int)speed1)*10)); + lcd.print(cur_speed_str); + char cur_distance1_str[6]; + char cur_distance2_str[6]; + lcd.setCursor(0,1); + if (distance1<100) { + sprintf(cur_distance1_str, "%02d.%03dKm", (int)distance1, (int)((distance1 - (int)distance1)*1000)); + } + else if (distance1<1000) { + sprintf(cur_distance1_str, "%02d.%02dKm", (int)distance1, (int)((distance1 - (int)distance1)*100)); + } + else { + sprintf(cur_distance1_str, "%03d.%01dKm", (int)distance1, (int)((distance1 - (int)distance1)*10)); + } + //lcd.print(distance1,3); + lcd.print(cur_distance1_str); + lcd.setCursor(0,3); + if (distance2<100) { + sprintf(cur_distance2_str, "%02d.%03dKm", (int)distance2, (int)((distance2 - (int)distance2)*1000)); + } + else if (distance2<1000) { + sprintf(cur_distance2_str, "%02d.%02dKm", (int)distance2, (int)((distance2 - (int)distance2)*100)); + } + else { + sprintf(cur_distance2_str, "%03d.%01dKm", (int)distance2, (int)((distance2 - (int)distance2)*10)); + } + //lcd.print(distance2,3); + lcd.print(cur_distance2_str); + + float distancetime1 = distance1 * 60 / constanta; + float distancetime2 = distance2 * 60 / constanta; + +//Calculating all about TIME,TDiff(including passing 23:59:59) + lcd.setCursor(9,1); + int secs1, mins1, hours1; + + secs1 = (distancetime1-(int)distancetime1)*60; + mins1 = (int)distancetime1 % 60; + hours1 = (int)distancetime1 / 60; + unsigned long totcurrentsecs = t.sec + (t.min*60) + ((long)t.hour*3600); + unsigned long totsecs1 = secs1 + (mins1*60) + ((long)hours1*3600); + unsigned long totstarttractsecs = starttractsec + (starttractmin*60) + ((long)starttracthour*3600); + unsigned long tottime1 = totsecs1 + totstarttractsecs; + boolean negatifsign = false; + +//Serial.print((long)starttracthour*3600); Serial.print(";"); Serial.print(starttractmin*60); Serial.println(";"); +//Serial.print(totsecs1); Serial.print(";"); Serial.print(totstarttractsecs); Serial.print(";"); +//Serial.print(tottime1);Serial.print(";");Serial.println(totcurrentsecs); + if (totcurrentsecs=0) { //positif means we are too fast, slow down please. + if (tottime1 >= totcurrentsecs) { //positif means we are too fast, slow down please. + // Serial.println("pos"); + negatifsign = false; + tottime1 = tottime1 - totcurrentsecs; + } + else { //negatif means we need to hurry, its late + // Serial.println("neg"); + negatifsign = true; + tottime1 = totcurrentsecs - tottime1; + } + } + //Serial.print(negatifsign);Serial.print(";"); Serial.println(tottime1); + hours1 = ((int)(tottime1 / 3600))%24; + mins1 = (int)((tottime1 % 3600)/60); + secs1 = (tottime1 % 60); + + char cur_time1_str[10]; + if (showTIME) { + sprintf(cur_time1_str, "%s %02d:%02d:%02d", dircount[dircount1], hours1, mins1, secs1); + } + else { + if (hours1 < 10) sprintf(cur_time1_str, "%s %s%01d:%02d:%02d", dircount[dircount1], (negatifsign?"-":" "), hours1, mins1, secs1); + else sprintf(cur_time1_str, "%s%s%02d:%02d:%02d", dircount[dircount1], (negatifsign?"-":" "), hours1, mins1, secs1); + + } + lcd.print(cur_time1_str); + +// Print Second TIME + lcd.setCursor(9,3); + int secs2, mins2, hours2; + + secs2 = (distancetime2-(int)distancetime2)*60; + mins2 = (int)distancetime2 % 60; + hours2 = (int)distancetime2 / 60; + + unsigned long totsecs2 = secs2 + (mins2*60) + ((long)hours2*3600); + unsigned long tottime2 = totsecs2 + totstarttractsecs; +//Serial.println(tottime2); + + if (!showTIME) { + if (tottime2 >= totcurrentsecs) { //positif means we are too fast, slow down please. + negatifsign = false; + tottime2 = tottime2 - totcurrentsecs; + } + else { //negatif means we need to hurry, its late + negatifsign = true; + tottime2 = totcurrentsecs - tottime2 ; + } + } + + hours2 = ((int)(tottime2 / 3600))%24; + mins2 = (int)((tottime2 % 3600)/60); + secs2 = (tottime2 % 60); + char cur_time2_str[10]; + if (showTIME) { + sprintf(cur_time2_str, "%s %02d:%02d:%02d", dircount[dircount2], hours2, mins2, secs2); + } + else { + if (hours2<10) sprintf(cur_time2_str, "%s %s%01d:%02d:%02d", dircount[dircount2], (negatifsign?"-":" "), hours2, mins2, secs2); + else sprintf(cur_time2_str, "%s%s%02d:%02d:%02d", dircount[dircount2], (negatifsign?"-":" "), hours2, mins2, secs2); + } + //sprintf(cur_time2_str, "%s%02d:%02d:%02d", (dirfwdcount2?"Fw":"Bw"), hours2, mins2, secs2); + //sprintf(cur_time2_str, "%s %02d:%02d:%02d", dircount[dircount2], hours2, mins2, secs2); + lcd.print(cur_time2_str); +/* //may be needed to refresh if Km more than 10000Km + lcd.setCursor(8,3); + lcd.write(1); //UP Arrow + + lcd.setCursor(8,1); + lcd.write(2); //DOWN Arrow +*/ + lcd.setCursor(x,y); +} + +void set_cursor_pos(int new_pos) +{ + /* + Cursor Positon map: + ---------------------- + |Count1 TIME AvgSp| + |1 35 |7 9 | + |Count2 KmH| + |2 46 |8 10| + ---------------------- + */ + + //Need to clear the previous cursor position + //int x, y; + switch(CURSOR_POS) + { + case 1: + x = 0; + y = 1; + break; + case 2: + x = 0; + y = 3; + break; + case 3: + x = 8; //Km is 7,1 + y = 1; + break; + case 4: + x = 8; //Km is 7,3 + y = 3; + break; + case 5: + x = 9; + y = 1; + break; + case 6: + x = 9; + y = 3; + break; + case 7: + x = 13; + y = 1; + break; + case 8: + x = 13; + y = 3; + break; + case 9: + x = 18; + y = 1; + break; + case 10: + x = 18; + y = 3; + break; + } + lcd.print(" "); + lcd.blink(); + lcd.setCursor(8,3); + lcd.write(1); //UP Arrow + + lcd.setCursor(8,1); + lcd.write(2); //DOWN Arrow + + lcd.setCursor(x,y); + +/* + switch(new_pos) + { + case 1: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_RIGHT); + break; + case 2: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_RIGHT); + break; + case 3: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 4: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 5: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 6: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 7: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_LEFT); + break; + case 8: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_LEFT); + break; + } +*/ + + CURSOR_POS = new_pos; +#ifdef DEBUG + Serial.print("SetCursorPosition:"); + Serial.println(CURSOR_POS); +#endif +} + + + + + + +void setup() { + +// +// +// +// +#ifdef DEBUG + Serial.begin(115200); + Serial.println("Starting Rally"); +#endif + Wire.begin(); + pinMode(UP_pin, INPUT_PULLUP); + pinMode(DOWN_pin, INPUT_PULLUP); + pinMode(LEFT_pin, INPUT_PULLUP); + pinMode(RIGHT_pin, INPUT_PULLUP); + pinMode(OK_pin, INPUT_PULLUP); + //DS3231_init(DS3231_INTCN); + DS3231_init(DS3231_CONTROL_INTCN); + //memset(recv, 0, BUFF_MAX); +#ifdef DEBUG + Serial.println("GET time"); +#endif +/* +Trip[0].sub = "A"; +Trip[0].speed = 24.275; +Trip[0].startHour = 25; +//Trip[0].distance = 12.898; +Trip[9].sub = "A"; +Trip[9].speed = 90.2751; +Trip[9].startHour = 22; +Trip[9].startMin = 59; +Trip[9].startSec = 58; +*/ +//Trip[9].distance = 12.898; +//Serial.println(Trip[0].sub);Serial.println(Trip[0].speed);Serial.println(Trip[0].startHour);Serial.println(Trip[0].startMin);Serial.println(Trip[0].startSec); +//Serial.println(Trip[0].distance); +//Serial.println(Trip[0].subTime); + +for (int i = 0; i23) starttracthour = 23; + if (starttractmin>59) starttractmin = 59; + if (starttractsec>59) starttractsec = 59; + //constanta=mem.readFloat(800); + constanta = Trip[curTrip].speed; + if ((constanta > 150) || (constanta < 0)) constanta = 60; + long m = mem.readLong(896); //read calibration value; + if (m >= 0) { + Calibration = m; + } +#ifdef DEBUG + Serial.println(m); + Serial.println(Calibration); + Serial.println(constanta); +#endif + constantatodigit(); + +// Serial.print(digit1);Serial.print(digit2); Serial.print(digit3); Serial.print(digit4);Serial.print(digit5);Serial.println(digit6); +// Serial.println(constanta,5); + //Serial.print(digitalRead(UP_pin));Serial.print(digitalRead(DOWN_pin));Serial.print(digitalRead(LEFT_pin));Serial.print(digitalRead(RIGHT_pin));Serial.println(digitalRead(OK_pin)); + + prevcount1 = count1; + prevcount2 = count2; + + prevcalibrationtime+=calibrationtimeinterval; + prevtempint+=tempinterval; + prevtemprally+=tempintervalrally; + prevsettime += intervalsettime; + startmillis+=1000; + + pinMode(ledPin, OUTPUT); + pinMode(interruptPin, INPUT); //Pull down using resistor to ground + attachInterrupt(digitalPinToInterrupt(interruptPin), blink, FALLING); + + mainMenu(); + + +// +// +// +// + + + Serial.begin(115200); + DynamicJsonDocument doc(512); + // Initialize SPIFFS + #ifdef ESP32 + if(!SPIFFS.begin(true)){ + Serial.println("An Error has occurred while mounting SPIFFS"); + return; + } + #else + if(!SPIFFS.begin()){ + Serial.println("An Error has occurred while mounting SPIFFS"); + return; + } + #endif + // wifiManager.setAPCallback(configModeCallback); + // wifiManager.autoConnect(soft_ap_ssid); + + WiFi.onEvent(OnWiFiEvent); + //WiFi.mode(WIFI_STA); + WiFi.mode(WIFI_MODE_APSTA); + + WiFi.softAP(soft_ap_ssid, soft_ap_password); + + String yourSSIDString = readFile(SPIFFS, "/ssidString.txt"); + Serial.print("*** Your ssidString: "); + Serial.println(yourSSIDString); + Serial.println(ssid); + if (yourSSIDString != ""){ + strncpy(ssid, yourSSIDString.c_str() , (sizeof ssid)-1); + } + + Serial.println(ssid); + String yourInputPwd = readFile(SPIFFS, "/inputPwd.txt"); + Serial.print("*** Your inputPwd: "); + Serial.println(yourInputPwd); + if (yourInputPwd != ""){ + strncpy(password, yourInputPwd.c_str() , (sizeof password)-1); + } + + WiFi.begin(ssid, password); + if (WiFi.waitForConnectResult() != WL_CONNECTED) { + Serial.println("WiFi Failed!"); + //return; + } + + Serial.print("ESP32 IP as soft AP: "); + Serial.println(WiFi.softAPIP()); + + Serial.println(); + Serial.print("IP Address: "); + Serial.println(WiFi.localIP()); + + // Init and get the time + configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); + printLocalTime(); + + // Send web page with input fields to client + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ + if (ON_STA_FILTER(request)) { + //request->send(200, "text/plain", "Hello from STA"); + request->send_P(200, "text/html", main_menu, processor); + return; + + } else if (ON_AP_FILTER(request)) { + //request->send(200, "text/plain", "Hello from AP"); + Serial.println("on apfilter /"); + request->send_P(200, "text/html", wifi_html, processor); + return; + } + + }); + + server.on("/wifi", HTTP_GET, [](AsyncWebServerRequest * request) { + + if (ON_STA_FILTER(request)) { + //request->send(200, "text/plain", "Hello from STA"); + request->send_P(200, "text/html", wifi_html, processor); + return; + + } else if (ON_AP_FILTER(request)) { + //request->send(200, "text/plain", "Hello from AP"); + Serial.println("on apfilter /wifi"); + request->send_P(200, "text/html", wifi_html, processor); + return; + } + + request->send(200, "text/plain", "Hello from undefined"); +}); + + + + // Send a GET request to /get?inputString= + server.on("/setwifi", HTTP_POST, [] (AsyncWebServerRequest *request) { + String inputMessage; + boolean bolrestart=false; + Serial.println("ini masuk /setwifi"); + // GET inputString value on /get?inputString= + if (request->hasParam(PARAM_SSID)) { + inputMessage = request->getParam(PARAM_SSID)->value(); + if (inputMessage!=""){ + writeFile(SPIFFS, "/ssidString.txt", inputMessage.c_str()); + delay(50); + bolrestart=true; + //ESP.restart(); + } + } + // GET inputPwd value on /wifi/get?inputPwd= + if (request->hasParam(PARAM_PWD)) { + inputMessage = request->getParam(PARAM_PWD)->value(); + if (inputMessage!=""){ + writeFile(SPIFFS, "/inputPwd.txt", inputMessage.c_str()); + delay(50); + bolrestart=true; + //ESP.restart(); + } + } + else { + inputMessage = "No message sent"; + } + if (bolrestart) { + ESP.restart(); + } + Serial.println("ini /setwifi aja");Serial.println(inputMessage); + request->send(200, "text/text", inputMessage); + }); + + // // Send a GET request to /wifi/get?ssidString= + // server.on("/wifi/get", HTTP_GET, [] (AsyncWebServerRequest *request) { + // String inputMessage; + // // GET ssidString value on /wifi/get?ssidString= + // Serial.println("ini masuk wifi get"); + // Serial.println(request->params()); + // if (request->hasParam(PARAM_SSID)) { + // inputMessage = request->getParam(PARAM_SSID)->value(); + // writeFile(SPIFFS, "/ssidString.txt", inputMessage.c_str()); + // delay(100); + // ESP.restart(); + // } + // // GET inputPwd value on /wifi/get?inputPwd= + // else if (request->hasParam(PARAM_PWD)) { + // inputMessage = request->getParam(PARAM_PWD)->value(); + // writeFile(SPIFFS, "/inputPwd.txt", inputMessage.c_str()); + // delay(100); + // ESP.restart(); + // } + // else { + // inputMessage = "No message sent"; + // } + // Serial.println("/wifi/get value:"); Serial.println(inputMessage); + // request->send(200, "text/text", inputMessage); + // }); + + server.on("/menu", HTTP_GET, [] (AsyncWebServerRequest *request) { + //String s = MAIN_page; //Read HTML contents + //request->send_P(200, "text/html", s); //Send web page + request->send_P(200, "text/html", main_menu); + }); + + server.on("/startrally", HTTP_GET, [] (AsyncWebServerRequest *request) { + //String s = MAIN_page; //Read HTML contents + //request->send_P(200, "text/html", s); //Send web page + String PAGE; + PAGE += FPSTR(HTML_PAGEHEADER); + PAGE.replace("%serveripaddress%", WiFi.localIP().toString()); + PAGE += FPSTR(HTML_DIVSTARTRALLY); + //PAGE += FPSTR(HTML_SCRIPTSETINTERVAL); + //PAGE += FPSTR(HTML_SCRIPTGETDATA); + PAGE += FPSTR(HTML_END); + //Serial.println(PAGE); + request->send(200, "text/html", PAGE); + }); + + server.on("/startrally1", HTTP_GET, [] (AsyncWebServerRequest *request) { + request->send_P(200, "text/html", HTML_startrally1, processor); + }); + + server.on("/resetodo1", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("ODORESET 1"); + request->redirect("/startrally1"); + }); + + server.on("/resetodo2", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("ODORESET 22222"); + request->redirect("/startrally1"); + }); + + server.on("/copytoodo2", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("COPY ODO 1 to 2"); + request->redirect("/startrally1"); + }); + + server.on("/copytoodo1", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("COPY ODO 2 to 1"); + request->redirect("/startrally1"); + }); + server.on("/DIR", HTTP_GET, [] (AsyncWebServerRequest *request) { + String inputMessage; + String inputParam; + if (request->hasParam("DIR1")){ + inputMessage=request->getParam("DIR1")->value(); + Serial.print("DIR 1->");Serial.println(inputMessage); + switch(inputMessage[0]){ + case 'F': + Serial.println("FW1"); + break; + case 'S': + Serial.println("ST1"); + break; + case 'B': + Serial.println("BACK1"); + break; + default: + Serial.println("Default VAL1"); + } + } + else if (request->hasParam("DIR2")){ + inputMessage=request->getParam("DIR2")->value(); + Serial.print("DIR 2->");Serial.println(inputMessage); + switch(inputMessage[0]){ + case 'F': + Serial.println("FW2"); + break; + case 'S': + Serial.println("ST2"); + break; + case 'B': + Serial.println("BACK2"); + break; + default: + Serial.println("Default VAL2"); + } + } + request->redirect("/startrally1"); + }); + + + server.on("/TG1", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("TOGGLE 1"); + request->redirect("/startrally1"); + }); + + server.on("/TG2", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("TOGGLE 2"); + request->redirect("/startrally1"); + }); +// //server.on("/adc", HTTP_GET); //This is display page +// server.on("/readADC", HTTP_GET, [] (AsyncWebServerRequest *request) { +// // int a = analogRead(A0); +// // String adcValue = String(millis()); +// String adcValue = getPin(); +// Serial.println(adcValue); +// request->send_P(200, "text/plain", adcValue.c_str()); //Send ADC value only to client ajax request +// }); + + server.on("/calibration", HTTP_GET, [] (AsyncWebServerRequest *request) { + //PAGE.replace("%serveripaddress%", WiFi.localIP().toString()); + request->send_P(200, "text/html", HTML_CALIBRATION, processor); + }); + + ws.onEvent(onWsEvent); //add ws event + wscal.onEvent(onWsEvent2); //add ws event + server.addHandler(&ws); + server.addHandler(&wscal); + + server.onNotFound(notFound); + server.begin(); +} + +// void loop() { +// // // To access your stored values on inputString, inputInt, inputFloat +// // String yourInputString = readFile(SPIFFS, "/inputString.txt"); +// // Serial.print("*** Your inputString: "); +// // Serial.println(yourInputString); + +// // int yourInputInt = readFile(SPIFFS, "/inputInt.txt").toInt(); +// // Serial.print("*** Your inputInt: "); +// // Serial.println(yourInputInt); + +// // float yourInputFloat = readFile(SPIFFS, "/inputFloat.txt").toFloat(); +// // Serial.print("*** Your inputFloat: "); +// // Serial.println(yourInputFloat); + +// // String yourSSIDString = readFile(SPIFFS, "/ssidString.txt"); +// // Serial.print("*** Your ssidString: "); +// // Serial.println(yourSSIDString); + +// // String yourInputPwd = readFile(SPIFFS, "/inputPwd.txt"); +// // Serial.print("*** Your inputPwd: "); +// // Serial.println(yourInputPwd); +// // delay(10000); +// delay(10330); +// ws.textAll(getPin()); +// wscal.textAll(getCalib()); +// //printLocalTime(); +// } + + + +void loop() //loop from VSS RALLY V2 +{ +#ifdef DEBUG + prevtimemicros = micros(); +#endif +#ifndef ATMEGA328 + digitalWrite(ledPin, ledstate); +#endif + char tempF[6]; + unsigned long now1 = millis(); + + btnUP.read(); //read the buttons + btnDN.read(); + btnLF.read(); //read the buttons + btnRF.read(); + btnOK.read(); + btnESC.read(); + if (millis()-rallyEditTime >1500) rallyEditRpt = 0; + switch (STATE) { + case WAIT: //wait for a button event + if (btnUP.wasPressed()) + STATE = UP; + else if (btnDN.wasPressed()) + STATE = DOWN; + else if (btnLF.wasPressed()) + STATE = LEFT; + else if (btnRF.wasPressed()) + STATE = RIGHT; + else if (btnUP.wasReleased()) //reset the long press interval + rpt = REPEAT_FIRST; + else if (btnDN.wasReleased()) + rpt = REPEAT_FIRST; + else if (btnLF.wasReleased()) //reset the long press interval + rpt = REPEAT_FIRST; + else if (btnRF.wasReleased()) + rpt = REPEAT_FIRST; + else if (btnUP.pressedFor(rpt)) { //check for long press + rpt += REPEAT_INCR; //increment the long press interval + STATE = UP; + } + else if (btnDN.pressedFor(rpt)) { + rpt += REPEAT_INCR; + STATE = DOWN; + } + else if (btnLF.pressedFor(rpt)) { //check for long press + rpt += REPEAT_INCR; //increment the long press interval + STATE = LEFT; + } + else if (btnRF.pressedFor(1000)) { + rpt += REPEAT_INCR; + STATE = RIGHT; + } + else if (btnOK.wasPressed() && (MENU != RALLY)) { + STATE = OKAY; + } + else if (btnOK.wasPressed() && (CURSOR_POS > 4)) { + STATE = OKAY; + } + else if (btnOK.wasPressed() && (CURSOR_POS <= 2)) { + //STATE = OKAY; + if (!rallyEditRpt) { + rallyEditTime = millis(); + rallyEditRpt++; + //Serial.println("!rallyEditRpt"); + //Serial.println(rallyEditRpt); + } + else if (millis()-rallyEditTime > 1500) { + rallyEditRpt = 0; + //Serial.println("rallyEditRpt = 0"); + //Serial.println(rallyEditRpt); + } + else if (rallyEditRpt == 2) { + //Serial.println("rallyEditRpt = ");Serial.println(rallyEditRpt); + STATE = RALLYEDIT; + rallyEditRpt = 0; + } + else { + rallyEditRpt++; + //Serial.println("rallyEditRpt++"); + //Serial.println(rallyEditRpt); + } + } + else if (btnOK.pressedFor(rpt) && (CURSOR_POS <= 4)) { + STATE = OKAY; + } + else if (btnESC.wasPressed()){ + STATE = ESC; + //Serial.println("ESC pressed"); + } + break; + + case DOWN: //increment the counter + switch (MENU) { + case MAIN: + y = min(y+1, MAX_ROW); //but not more than the specified maximum + break; + + case RALLY: + if (blinkON) { + if (y == 1) { + if (x == 0 || x == 1) { + dist1digit1 = max(dist1digit1-1, 0); + lcd.setCursor(0,y); + if (dist1digit1 <10) lcd.print("0"); + lcd.print(dist1digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist1digit2 = max(dist1digit2-1, 0); + lcd.setCursor(3,y); + if (dist1digit2 <10) { + lcd.print("00"); + }else if (dist1digit2 <100) lcd.print("0"); + lcd.print(dist1digit2); + } + } + else if (y ==3) { + if (x == 0 || x == 1) { + dist2digit1 = max(dist2digit1-1, 0); + lcd.setCursor(0,y); + if (dist2digit1 <10) lcd.print("0"); + lcd.print(dist2digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist2digit2 = max(dist2digit2-1, 0); + lcd.setCursor(3,y); + if (dist2digit2 <10) { + lcd.print("00"); + }else if (dist2digit2 <100) lcd.print("0"); + lcd.print(dist2digit2); + } + + } + + } + else { + CURSOR_POS=min(CURSOR_POS+1,10); + set_cursor_pos(CURSOR_POS); + } + + break; + + case CALIBRATION: + if (!blinkON) y = min(y+1, MAX_ROW ); //but not more than the specified maximum + else if (blinkON && y==1) { + //calibrationDistance=max(calibrationDistance-1, 1); + tempcalibdist=max(tempcalibdist-1, 1); + lcd.print(tempcalibdist); + } + else if (blinkON && y==3 && (x==18||x==19)) { + calibdigit3 = max(calibdigit3-1,0); + lcd.setCursor(18,3); + if (calibdigit3<10) lcd.print("0"); + lcd.print(calibdigit3); + } + else if (blinkON && y==3 && (x==16||x==17)) { + calibdigit2 = max(calibdigit2-1,0); + lcd.setCursor(16,3); + if (calibdigit2<10) lcd.print("0"); + lcd.print(calibdigit2); + } + else if (blinkON && y==3 && (x==14||x==15)) { + calibdigit1 = max(calibdigit1-1,0); + lcd.setCursor(14,3); + if (calibdigit1<10) lcd.print("0"); + lcd.print(calibdigit1); + } + break; + + case CONSTANTA: + if (!blinkON) { + y = min(y+1, 3); //but not less than the specified minimum + if (y==1) x=15; + } + else if (y==1) { + prevTrip = min(prevTrip+1,TRIPSIZE-1); + //curTrip = min(curTrip+1,TRIPSIZE-1); + lcd.setCursor(14,y); + lcd.print(Trip[prevTrip].sub); + } + else if (x==13 && y==2) { + digit1 = max(digit1-1, MIN_COUNT); + lcd.print(digit1); + } + else if (x==14 && y==2) { + digit2 = max(digit2-1, MIN_COUNT); + lcd.print(digit2); + } + else if (x==16 && y==2) { + digit3 = max(digit3-1, MIN_COUNT); + lcd.print(digit3); + } + else if (x==17 && y==2) { + digit4 = max(digit4-1, MIN_COUNT); + lcd.print(digit4); + } + else if (x==18 && y==2) { + digit5 = max(digit5-1, MIN_COUNT); + lcd.print(digit5); + } + else if (x==19 && y==2) { + digit6 = max(digit6-1, MIN_COUNT); + lcd.print(digit6); + } + else if ((x==12 || x==13) && y==3) { //******SET CONSTANTA TIME ******* + hour24=max(hour24-1, MIN_COUNT); + lcd.setCursor(12,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==15 || x==16) && y==3) { + min60=max(min60-1, MIN_COUNT); + lcd.setCursor(15,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==18 || x==19) && y==3) { + sec60=max(sec60-1, MIN_COUNT); + lcd.setCursor(18,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + + case SETTIME: + if (!blinkON) { + y = min(y+1, MAX_ROW); //but not more than the specified maximum + lcd.setCursor(x,y); + } + else if ((x==0 || x==1) && y==3) { + hour24=max(hour24-1, MIN_COUNT); + lcd.setCursor(0,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==3 || x==4) && y==3) { + min60=max(min60-1, MIN_COUNT); + lcd.setCursor(3,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==6 || x==7) && y==3) { + sec60=max(sec60-1, MIN_COUNT); + lcd.setCursor(6,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case UP: //decrement the counter + switch(MENU) { + case MAIN: + y = max(y-1, MIN_COUNT); //but not less than the specified minimum + break; + + case CALIBRATION: + if (!blinkON) { + y = max(y-1, MIN_COUNT); //but not less than the specified minimum + x = 18; + } + else if (blinkON && y==1) { + //calibrationDistance=min(calibrationDistance+1, 9); + tempcalibdist=min(tempcalibdist+1, 9); + lcd.print(tempcalibdist); + } + else if (blinkON && y==3 && (x==18||x==19)) { + calibdigit3 = min(calibdigit3+1,99); + lcd.setCursor(18,3); + if (calibdigit3<10) lcd.print("0"); + lcd.print(calibdigit3); + } + else if (blinkON && y==3 && (x==16||x==17)) { + calibdigit2 = min(calibdigit2+1,99); + lcd.setCursor(16,3); + if (calibdigit2<10) lcd.print("0"); + lcd.print(calibdigit2); + } + else if (blinkON && y==3 && (x==14||x==15)) { + calibdigit1 = min(calibdigit1+1,50); + lcd.setCursor(14,3); + if (calibdigit1<10) lcd.print("0"); + lcd.print(calibdigit1); + } + break; + + case RALLY: + if (blinkON) { + if (y == 1) { + if (x == 0 || x == 1) { + dist1digit1 = min(dist1digit1+1, 999); + lcd.setCursor(0,y); + if (dist1digit1 <10) lcd.print("0"); + lcd.print(dist1digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist1digit2 = min(dist1digit2+1, 999); + lcd.setCursor(3,y); + if (dist1digit2 <10) { + lcd.print("00"); + }else if (dist1digit2 <100) lcd.print("0"); + lcd.print(dist1digit2); + } + } + else if (y == 3) { + if (x == 0 || x == 1) { + dist2digit1 = min(dist2digit1+1, 99); + lcd.setCursor(0,y); + if (dist2digit1 <10) lcd.print("0"); + lcd.print(dist2digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist2digit2 = min(dist2digit2+1, 999); + lcd.setCursor(3,y); + if (dist2digit2 <10) { + lcd.print("00"); + }else if (dist2digit2 <100) lcd.print("0"); + lcd.print(dist2digit2); + } + } + + } + else { + CURSOR_POS=max(CURSOR_POS-1,1); + set_cursor_pos(CURSOR_POS); + } + break; + + case CONSTANTA: + if (!blinkON) { + y = max(y-1, MIN_COUNT); //but not less than the specified minimum + if (y==0) x=16; + else if (y==1) x=15; + } + else if (y==1) { + prevTrip = max(prevTrip-1, MIN_COUNT); + //curTrip = max(curTrip-1, MIN_COUNT); + lcd.setCursor(14,y); + lcd.print(Trip[prevTrip].sub); + } + else if (x==13 && y==2) { + digit1=min(digit1+1, 9); + lcd.print(digit1); + } + else if (x==14 && y==2) { + digit2=min(digit2+1, 9); + lcd.print(digit2); + } + else if (x==16 && y==2) { + digit3=min(digit3+1, 9); + lcd.print(digit3); + } + else if (x==17 && y==2) { + digit4=min(digit4+1, 9); + lcd.print(digit4); + } + else if (x==18 && y==2) { + digit5=min(digit5+1, 9); + lcd.print(digit5); + } + else if (x==19 && y==2) { + digit6=min(digit6+1, 9); + lcd.print(digit6); + } + else if ((x==12 || x==13) && y==3) { //******SET CONSTANTA TIME ******* + hour24=min(hour24+1, 23); + lcd.setCursor(12,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==15 || x==16) && y==3) { + min60=min(min60+1, 59); + lcd.setCursor(15,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==18 || x==19) && y==3) { + sec60=min(sec60+1, 59); + lcd.setCursor(18,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + + case SETTIME: + if (!blinkON) { + y = max(y-1, MIN_COUNT); //but not less than the specified minimum + //Serial.print(x); Serial.print(","); Serial.println(y); + //lcd.setCursor(x,y); + } + else if ((x==0 || x==1) && y==3) { + hour24=min(hour24+1, 23); + lcd.setCursor(0,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==3 || x==4) && y==3) { + min60=min(min60+1, 59); + lcd.setCursor(3,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==6 || x==7) && y==3) { + sec60=min(sec60+1, 59); + lcd.setCursor(6,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case RIGHT: //increment the counter + switch (MENU) { + case SETTIME: + x = min(x+1, MAX_COL); //MAX_COUNT); //but not more than the specified maximum + //STATE = WAIT; + //Serial.print(x); Serial.print(","); Serial.println(y); + //lcd.setCursor(x,y); + break; + + case RALLY: + if (blinkON) { + + x = min(x+1, 5); + //Serial.println(x); + } + else if (CURSOR_POS % 2 ==0) CURSOR_POS=min(CURSOR_POS+2,10); + else CURSOR_POS=min(CURSOR_POS+2,9); + if (!blinkON) set_cursor_pos(CURSOR_POS); + break; + + case CONSTANTA: + if (y==2 || y==3) { + x = min(x+1, MAX_COL); //MAX_COUNT); + } + break; + + case CALIBRATION: + if (y==3) { + x = min(x+1,MAX_COL); + } + else x = 18; + break; + + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case LEFT: //decrement the counter + switch (MENU) { + case SETTIME: + x = max(x-1, MIN_COUNT); //but not less than the specified minimum + //STATE = WAIT; + //Serial.print(x); Serial.print(","); Serial.println(y); + //lcd.setCursor(x,y); + break; + + case RALLY: + if (blinkON) { + x = max(x-1, MIN_COUNT); + } + else if (CURSOR_POS % 2 == 0) CURSOR_POS=max(CURSOR_POS-2,2); + else CURSOR_POS=max(CURSOR_POS-2,1); + if (!blinkON) set_cursor_pos(CURSOR_POS); + break; + + case CONSTANTA: + if (y==2 || y==3){ + x = max(x-1, 12); + } + break; + + case CALIBRATION: + if (y==3) { + x = max(x-1, 14); + } + else x = 18; + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case OKAY: + switch (MENU) { + case MAIN: + if (y==1) { + MENU = SETTIME; + //prevsettime += millis(); + //prevtempint+=millis(); + } + else if (y==0) { + MENU = RALLY; + //prevtemprally=millis(); + } + else if (y==2) MENU = CONSTANTA; + else if (y==3) { + MENU = CALIBRATION; + //prevcalibrationtime+=millis(); + } + break; + + case CONSTANTA: + if (y==0) MENU = MAIN; + //else if (!blinkON && y==1) { + + // } + else if (!blinkON && y==2) { + constantatodigit(); + lcd.blink(); + blinkON=!blinkON; + } + else if (!blinkON && y==3) { + sec60 = starttractsec; + min60 = starttractmin; + hour24 = starttracthour; + lcd.blink(); + blinkON=!blinkON; + } + else if (!blinkON && y==1) { + prevTrip = curTrip; + lcd.blink(); + blinkON = !blinkON; + } + else if (blinkON && y==1) { + curTrip = prevTrip; + constanta = Trip[curTrip].speed; + starttractsec = Trip[curTrip].startSec; + starttractmin = Trip[curTrip].startMin; + starttracthour = Trip[curTrip].startHour; + lcd.noBlink(); + blinkON=!blinkON; + constantaMenu(); + } + else if (blinkON && y==2) { + lcd.noBlink(); + blinkON=!blinkON; + constanta = (digit1*10)+digit2+(float)digit3/10+(float)digit4/100+(float)digit5/1000+(float)digit6/10000; //+(float)digit6/100000; + //mem.writeFloat(800, constanta); + int pointeradd = ((TRIPADDRESS+curTrip)*32); + mem.writeFloat(pointeradd, constanta); + Trip[curTrip].speed = constanta; +#ifdef DEBUG + Serial.println(pointeradd); Serial.print(";");Serial.println(constanta,5); +#endif + } + else if (blinkON && y==3) { + starttractsec=sec60; + starttractmin=min60; + starttracthour=hour24; + unsigned long valuesettime = starttracthour; + valuesettime = valuesettime * 256 + starttractmin; // effectively shift the first byte 8 bit positions + valuesettime = valuesettime * 256 + starttractsec; + //mem.writeLong(768,valuesettime); + int pointeradd = ((TRIPADDRESS+curTrip)*32+4); + mem.writeLong(pointeradd, valuesettime); + Trip[curTrip].startHour = starttracthour; + Trip[curTrip].startMin = starttractmin; + Trip[curTrip].startSec = starttractsec; + lcd.noBlink(); + blinkON=!blinkON; +#ifdef DEBUG + Serial.println(pointeradd); Serial.println(valuesettime); +#endif + } + else {// if (y==3) { + lcd.blink(); + blinkON=!blinkON; + } + break; + + case RALLY: +#ifdef DEBUG + Serial.println("OKRALLY"); +#endif + switch(CURSOR_POS) + { + case 1: + count1 = 0; + backcount1 = 0; + time1 = VSSCount; + //Serial.println("case 1"); + break; + case 2: + count2 = 0; + backcount2 = 0; + time2 = VSSCount; + //Serial.println("case 2"); + break; + case 3: + count2 = count1; //no yet UNDO next update can UNDO + backcount2 = 0; + //time2 = VSSCount; + //Serial.println("case 3"); + break; + case 4: + count1 = count2; //no yet UNDO next update can UNDO + backcount1 = 0; + //time1 = VSSCount; + //Serial.println("case 4"); + break; + case 5: + //dirfwdcount1 = !dirfwdcount1; + switch (dircount1) + { + case FORWARD: + dircount1 = FREEZE; + break; + case FREEZE: + dircount1 = BACKWARD; + break; + case BACKWARD: + dircount1 = FORWARD; + break; + default: + dircount1 = FORWARD; + break; + } + secondrallyMenu(); + //Serial.println("case 5"); + break; + case 6: + //dirfwdcount2 = !dirfwdcount2; + switch (dircount2) + { + case FORWARD: + dircount2 = FREEZE; + break; + case FREEZE: + dircount2 = BACKWARD; + break; + case BACKWARD: + dircount2 = FORWARD; + break; + default: + dircount2 = FORWARD; + break; + } + secondrallyMenu(); + //Serial.println("case 6"); + break; + case 7: + showTIME = !showTIME; + rallyMenu(); + break; + case 8: + showTIME = !showTIME; + rallyMenu(); + break; + case 9: + //Serial.println("case 9"); + MENU = MAIN; + lcd.noBlink(); + break; + case 10: + //Serial.println("case 10"); + MENU = MAIN; + lcd.noBlink(); + break; + + } + break; + + case CALIBRATION: + if (blinkON && y==1) { + lcd.noBlink(); + blinkON=!blinkON; + calibrationDistance = tempcalibdist; + } + else if (!blinkON && y==1) { + lcd.blink(); + blinkON=!blinkON; + tempcalibdist = calibrationDistance; + } + else if (!blinkON && y==2) { + //startCalibration = millis(); + Calibrationcount = 0; + startCalibration = VSSCount; + Calibrationtime = startCalibration; + blinkON=!blinkON; + lcd.blink(); + calibrationON=true; + lcd.setCursor(0,2); + lcd.print("Calibrating 00.000Km"); + } + else if (blinkON && y==2) { + Calibration = (VSSCount-startCalibration)/(float)calibrationDistance; + mem.writeLong(896, Calibration); //Save Calibration to memory + oneMeter=(millis()-startCalibration)/(1000*(float)calibrationDistance);//*calibrationDistance); + oneMeter=((float)VSSCount-startCalibration)/(1000*(float)calibrationDistance);//*calibrationDistance); + oneMeter=(float)(Calibration)/1000*(float)calibrationDistance; + blinkON=!blinkON; + lcd.noBlink(); + calibrationON=false; + lcd.setCursor(0,2); + lcd.print("Start "); + lcd.setCursor(0,3); + lcd.print("1m="); + //Serial.print(startCalibration);Serial.print(";");Serial.print((millis()-startCalibration)/1000);Serial.print(";"); +#ifdef DEBUG + Serial.println(oneMeter,5); +#endif + lcd.print(oneMeter,3); + lcd.print(";"); + } + else if (!blinkON && y==3) { //not yet implemented + lcd.blink(); + blinkON=!blinkON; + calibdigit1 = (byte)(Calibration/10000); + calibdigit2 = (byte)((Calibration % 10000)/100); + calibdigit3 = Calibration % 100; + //Serial.println(calibdigit1);Serial.println(calibdigit2);Serial.println(calibdigit3); + } + else if (blinkON && y==3) { + lcd.noBlink(); + blinkON=!blinkON; + //Serial.println(calibdigit1);Serial.println(calibdigit2);Serial.println(calibdigit3); + Calibration = ((long)calibdigit1*10000) + ((long)calibdigit2*100) + (calibdigit3); + //Serial.println(Calibration); + mem.writeLong(896, Calibration); + } + else if (y==0) MENU = MAIN; + break; + + case SETTIME: + if (blinkON && y==3) { + t.sec=sec60; + t.min=min60; + t.hour=hour24; + DS3231_set(t); + lcd.noBlink(); + blinkON=!blinkON; + //Serial.println("OKAY"); + } + else if (y==3) { + lcd.blink(); + blinkON=!blinkON; + } + else {//(blinkON) { + MENU = MAIN; + lcd.noBlink(); + } + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case RALLYEDIT: + if ((CURSOR_POS == 1 || CURSOR_POS == 2) && !blinkON) { + rallyEdit = true; + blinkON = true; + lcd.blink(); + //if (distance<100) { + dist1digit1=((int)distance1%1000); + dist1digit2=(int)((distance1 - (int)distance1)*1000); + dist2digit1=((int)distance2%1000); + dist2digit2=(int)((distance2 - (int)distance2)*1000); + //} + /* + Serial.print(dist1digit1);Serial.println(dist1digit2); //Serial.print(dist1digit3); Serial.print(dist1digit4);Serial.println(dist1digit5);//Serial.println(digit6); + Serial.println(distance1,3); + Serial.print(dist2digit1);Serial.println(dist2digit2); //Serial.print(dist1digit3); Serial.print(dist1digit4);Serial.println(dist1digit5);//Serial.println(digit6); + Serial.println(distance2,3); + */ + } + else if (blinkON) { //set the new distance to count + blinkON = false; + rallyEdit = false; + /* + Serial.println(count1); + Serial.println(distance1,5); + Serial.println(""); + */ + if (CURSOR_POS == 1) { + distance1 = dist1digit1 + (float)dist1digit2/1000; + count1 = (unsigned long)(distance1 * Calibration) + 5; + //distance1 = (float)count1/((float)Calibration); + }else if (CURSOR_POS == 2) { + distance2 = dist2digit1 + (float)dist2digit2/1000; + count2 = (unsigned long)(distance2 * Calibration) + 5; + //distance2 = (float)count2/((float)Calibration); + } + /* + Serial.println(count1); + Serial.println(distance1,3); + */ + set_cursor_pos(CURSOR_POS); + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case ESC: + switch (MENU) + { + case RALLY: + lcd.noBlink(); + MENU=MAIN; + if (rallyEdit) { + rallyEdit = false; + lcd.blink(); + MENU = RALLY; + set_cursor_pos(CURSOR_POS); + } + blinkON=false; + + break; + case SETTIME: + lcd.noBlink(); + if (!blinkON) MENU = MAIN; + blinkON=false; + //MENU=MAIN; + break; + case CONSTANTA: + //MENU=MAIN; + if (!blinkON) MENU = MAIN; + else constantaMenu(); + lcd.noBlink(); + blinkON=false; + break; + case CALIBRATION: + lcd.noBlink(); + if (!blinkON) MENU = MAIN; + blinkON=false; + calibrationON=false; + //MENU=MAIN; + break; + + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + } + +//***************************************************************** +//*************************************** M E N U ***************** +// +// +// +//*************************************** M E N U ***************** +//***************************************************************** + + if (PREVMENU!=MENU) + { + switch (MENU) + { + case (MAIN): + mainMenu(); + break; + + case (RALLY): + lcd.clear(); + rallyMenu(); + rallyON=true; + //lcd.blink(); + CURSOR_POS=10; + set_cursor_pos(CURSOR_POS); + break; + + case (SETTIME): + lcd.clear(); + settimeMenu(); + sec60=t.sec; + min60=t.min; + hour24=t.hour; + lcd.setCursor(0,3); + lcdprint2digit(hour24); + lcd.print(":"); + lcdprint2digit(min60); + lcd.print(":"); + lcdprint2digit(sec60); + x=0; + y=2; + lcd.setCursor(x,y); + break; + + case (CALIBRATION): + calibrationMenu(); + break; + + case CONSTANTA: + sec60=starttractsec; + min60=starttractmin; + hour24=starttracthour; + x = 16; + y = 0; + constantaMenu(); + break; + + case (INPUTSUBTRAYEK): + break; + } + } + + if (MENU==RALLY) { + if ((now1 - prevtemprally) >= tempintervalrally) { + //if ((long)(now1 - prevtemprally) >= 0) { + //rallyMenu(); + if (!rallyEdit) redrawrallyMenu(); //Distance is edited? + prevtemprally=now1; + //prevtemprally+=tempintervalrally; + } + } + + if (MENU==SETTIME) { + //if ((long)(now1 - prevtempint) >=0 ){ + if ((now1 - prevtempint) >=tempinterval ){ + temperature = DS3231_get_treg(); //Get temperature + dtostrf(temperature, 5, 1, tempF); + lcd.setCursor(9,1); + lcd.print(tempF); + lcd.print((char)223); + lcd.print("C "); + //prevtempint+=tempinterval; + prevtempint=now1; + lcd.setCursor(x,y); + //lcd.setCursor(15,0); + //lcd.print(now); + } + //if ((long)(now1- prevsettime) >=0 ){ //show SET TIME MENU + if ((now1 - prevsettime) >=intervalsettime ){ //show SET TIME MENU + DS3231_get(&t); //Get time + if (prevsec!=t.sec) { //will update the LCD every sec(as long as the t.sec is different) eventhough intervalseetime is 250ms + settimeMenu(); + prevsettime = now1; + //prevsettime += intervalsettime; + } + } + } + + if (MENU==CALIBRATION) { + if (calibrationON) { + if ((now1 - prevcalibrationtime) >= calibrationtimeinterval ) { + //if ((long)(now1 - prevcalibrationtime) >=0 ) { + redrawcalibrationMenu(); + char Calibrationstr[6]; + unsigned long calibtemp = VSSCount - startCalibration; + sprintf(Calibrationstr, "%06lu", calibtemp); + lcd.setCursor(14,3); + lcd.print(Calibrationstr); + lcd.setCursor(x,y); + prevcalibrationtime=now1; + //prevcalibrationtime+=calibrationtimeinterval; + } + } + } + + //if (((long)(millis()-startmillis)>=0) && MENU!=CALIBRATION) { + if ((now1-startmillis)>=500) { //&& MENU!=CALIBRATION && MENU!=MAIN) { + unsigned long VSSCountDiff = VSSCount - startVSSCount; + startVSSCount=VSSCount; + if ((VSSCountDiff == 0) && savedCount) { + intervalsavemillis = 4000000; + } + else if ((VSSCountDiff == 0) && !savedCount) { + saveCount(); + savedCount = !savedCount; + intervalsavemillis = 2000000; + } + else if (VSSCountDiff < 15) intervalsavemillis = 3000; + else if (VSSCountDiff < 70) intervalsavemillis = 60000; + else intervalsavemillis = 4000000; + if (VSSCountDiff > 0) savedCount = false; + if (MENU!=CALIBRATION && MENU!=MAIN && MENU!=CONSTANTA) { + lcd.setCursor(0,0); + if (VSSCountDiff==0) lcd.print("0"); + else if (VSSCountDiff <= 10) lcd.print("1"); + else if (VSSCountDiff <= 50) lcd.print("2"); + else if (VSSCountDiff <= 150) lcd.print("3"); + else if (VSSCountDiff <= 250) lcd.print("4"); + else if (VSSCountDiff <= 400) lcd.print("5"); + else if (VSSCountDiff <= 600) lcd.print("6"); + else if (VSSCountDiff <= 900) lcd.print("7"); + else if (VSSCountDiff <= 1200) lcd.print("8"); + else if (VSSCountDiff > 1200) lcd.print("9"); + + //lcd.print(VSSCountDiff); + //lcd.print(" "); + lcd.setCursor(x,y); + } + //startmillis+=400; + startmillis=now1; + + } + +/* + if (((millis() % 100)==0) && MENU!=CALIBRATION) { + lcd.setCursor(0,2); + lcd.print(VSSCount); + lcd.print(" "); + lcd.setCursor(x,y); + } +*/ + if ((millis()-updatecounttime)>=250) { + updateCount(); + updatecounttime = millis(); + } + + if ((millis()-startsavemillis) > intervalsavemillis) { + saveCount(); + //startsavemillis += 3000; + startsavemillis = millis(); + } + // if ((millis()-broadcastwebsocket) > 1000) { + // broadcastwebsocket = millis(); + // ws.textAll(getPin()); + // wscal.textAll(getCalib()); + // } +#ifdef DEBUG + Serial.print(micros()-prevtimemicros); Serial.println("**"); +#endif +} diff --git a/backup/startrally1.html b/backup/startrally1.html new file mode 100644 index 0000000..5ec26a6 --- /dev/null +++ b/backup/startrally1.html @@ -0,0 +1,302 @@ + + Rally TerraTrip v1 + + + + + + + +
+
+
12345
+

Time: 00:00:00

+

123.4Km/h

+
+
+
+
+ +
+
S:123.45Km | V:123.4Km/h | T: 123Min
+ +
sTime: 12:34:50
+ +
+
+ +
+

OD 1->

+

123.4567 km

+

DIRECT

+

00:00:00

+
+
+

+ +

+
+

+ + +

+
+

+
+ +

+
+
+
+ +
+

OD 2->123.456 km

+

DIRECT

+

00:00:00

+
+
+
+ +
+
+
+ + +
+
+

+
+ +
+

+
+ +
+ + + + + + + \ No newline at end of file diff --git a/data/constanta.html b/data/constanta.html new file mode 100644 index 0000000..d466a64 --- /dev/null +++ b/data/constanta.html @@ -0,0 +1,177 @@ + + + Rally TerraTrip v1 Constanta + + + + + + + + +
+
+

12345

+

TRACK A

+

Time: 00:00:00

+

123.4Km/h

+
+
+ + + +
+
+
+
+
+
+
+
+
+
+ + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + + + + + + + +
+ + + + + \ No newline at end of file diff --git a/data/inputPwd.txt b/data/inputPwd.txt new file mode 100644 index 0000000..6a537b5 --- /dev/null +++ b/data/inputPwd.txt @@ -0,0 +1 @@ +1234567890 \ No newline at end of file diff --git a/data/ssidString.txt b/data/ssidString.txt new file mode 100644 index 0000000..d137a2f --- /dev/null +++ b/data/ssidString.txt @@ -0,0 +1 @@ +WiFi_SuGi \ No newline at end of file diff --git a/data/text.txt b/data/text.txt new file mode 100644 index 0000000..f3d331d --- /dev/null +++ b/data/text.txt @@ -0,0 +1 @@ +Hello world from data \ No newline at end of file diff --git a/data/tripA b/data/tripA new file mode 100644 index 0000000..e69de29 diff --git a/data/tripB b/data/tripB new file mode 100644 index 0000000..e69de29 diff --git a/data/tripC b/data/tripC new file mode 100644 index 0000000..e69de29 diff --git a/data/tripD b/data/tripD new file mode 100644 index 0000000..e69de29 diff --git a/data/tripE b/data/tripE new file mode 100644 index 0000000..e69de29 diff --git a/data/tripF b/data/tripF new file mode 100644 index 0000000..e69de29 diff --git a/data/tripG b/data/tripG new file mode 100644 index 0000000..e69de29 diff --git a/data/tripH b/data/tripH new file mode 100644 index 0000000..e69de29 diff --git a/data/tripI b/data/tripI new file mode 100644 index 0000000..e69de29 diff --git a/data/tripJ b/data/tripJ new file mode 100644 index 0000000..e69de29 diff --git a/data/tripK b/data/tripK new file mode 100644 index 0000000..e69de29 diff --git a/data/tripL b/data/tripL new file mode 100644 index 0000000..e69de29 diff --git a/data/tripM b/data/tripM new file mode 100644 index 0000000..e69de29 diff --git a/data/tripN b/data/tripN new file mode 100644 index 0000000..e69de29 diff --git a/data/tripO b/data/tripO new file mode 100644 index 0000000..e69de29 diff --git a/data/tripP b/data/tripP new file mode 100644 index 0000000..e69de29 diff --git a/include/README b/include/README new file mode 100644 index 0000000..194dcd4 --- /dev/null +++ b/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/lib/README b/lib/README new file mode 100644 index 0000000..6debab1 --- /dev/null +++ b/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/platformio.ini b/platformio.ini new file mode 100644 index 0000000..71060f2 --- /dev/null +++ b/platformio.ini @@ -0,0 +1,34 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:lolin32_lite] +platform = espressif32 +board = lolin32_lite +framework = arduino +monitor_speed = 115200 +lib_deps = + ottowinter/ESPAsyncWebServer-esphome@^2.1.0 + esphome/AsyncTCP-esphome@^1.2.2 + SPIFFS + bblanchon/ArduinoJson@^6.19.4 + khoih-prog/ESPAsync_WiFiManager@^1.12.2 + rodan/ds3231@^1.0 + ;fmalpartida/LiquidCrystal@^1.5.0 + https://github.com/cyberp/AT24Cx.git + https://github.com/JChristensen/JC_Button.git + Wire + ;arduino-libraries/LiquidCrystal@^1.0.7 + https://github.com/fdebrabander/Arduino-LiquidCrystal-I2C-library.git + +[env:env1] +lib_deps = + khoih-prog/ESPAsync_WiFiManager@^1.12.2 + rodan/ds3231@^1.0 + arduino-libraries/LiquidCrystal@^1.0.7 diff --git a/src/constanta.h b/src/constanta.h new file mode 100644 index 0000000..39c5637 --- /dev/null +++ b/src/constanta.h @@ -0,0 +1,194 @@ +const char HTML_CONSTHEADER[] PROGMEM = R"rawliteral( + + Rally TerraTrip v1 Constanta + + + + + + + +
+
+

12345

+

TRACK A

+

Time: 00:00:00

+

123.4Km/h

+
+
+ + + +
+
+
+
+
+
+
+
+
+
+)rawliteral"; + +const char HTML_CONSTROW[] PROGMEM = R"rawliteral( +
+
+
+
+
+
+
+
+
+
+
+
+
+)rawliteral"; + +const char HTML_CONSTEND[] PROGMEM = R"rawliteral( + +
+ + + + +)rawliteral"; \ No newline at end of file diff --git a/src/index.h b/src/index.h new file mode 100644 index 0000000..dcab25b --- /dev/null +++ b/src/index.h @@ -0,0 +1,406 @@ +const char HTML_startrally1[] PROGMEM = R"rawliteral( + + Rally TerraTrip v1 + + + + + + + +
+
+
12345
+

Time: 00:00:00

+

123.4Km/h

+
+
+
+
+ +
+
S: 123.45Km | V: 123.4Km/h | T: 123Min
+ +
ST: 12:34:50
+
+
+ +
+

OD 1->

+

123.4567 km

+

DIRECT

+

00:00:00

+
+
+

+ +

+
+

+ + +

+
+

+
+ +

+
+
+ + +
+

OD 2->123.456 km

+

DIRECT

+

00:00:00

+
+
+
+ +
+
+
+ + +
+
+

+
+ +
+

+
+ +
+ + + + + + + +)rawliteral"; + +//HTML_CALIBRATION + + + +const char HTML_CALIBRATION[] PROGMEM = R"rawliteral( + + Rally TerraTrip v1 Calibration + + + + + + + +
+
+

12345

+

TRACK A

+

Time: 00:00:00

+

123.4Km/h

+
+
+ +
+

Set Distance (9 Km)->

+

+ + + +

+
+
+

Set Calibration Manually (110000)->

+

+ + + +

+
+
+

+ +

+
+

+ 00.000Km

+
+
+
+

1 meter=123.456

+

123456 Calibration Value

+
+ + +
+ + + +)rawliteral"; \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..f4efd22 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,3652 @@ +/********* + Rui Santos + Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-input-data-html-form/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files. + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. +*********/ + +#include +#ifdef ESP32 + #include + #include + #include + #include +#else + #include + #include + #include + #include +#endif +#include +// #include +//#include +#include +#include +#include +#include +#include +//#include + +AsyncWebServer server(80); +AsyncWebSocket ws("/ws"); +AsyncWebSocket wscal("/wscal"); +//WiFiManager wifiManager; + +// REPLACE WITH YOUR NETWORK CREDENTIALS +// char ssid[] = "WiFi_SuGi"; +char ssid[] = "123456789012345678901234567890"; +char password[] = "123456789012345678901234567890"; + +//strcpy(ssid,"WiFi_SuGi"); + +//password = "1234567890"; + +const char *soft_ap_ssid = "MyESP32AP"; +const char *soft_ap_password = "testpassword"; + +const char* PARAM_STRING = "inputString"; +const char* PARAM_INT = "inputInt"; +const char* PARAM_FLOAT = "inputFloat"; + +const char* PARAM_SSID = "ssidString"; +const char* PARAM_PWD = "inputPwd"; + +const char* ntpServer = "pool.ntp.org"; +const long gmtOffset_sec = 7*3600; +const int daylightOffset_sec = 0; + +uint8_t STATE, dircount1, dircount2; //The current state machine state + +//volatile DynamicJsonDocument getRally(200); +String getRallyJson="{\"counter\":0}"; +String getCalibJson="{\"counter\":0}"; +int globalClientRally=0; +int globalClientCalib=0; + +#define REQUESTCOUNT 3 +AsyncWebServerRequest *gRequest[REQUESTCOUNT]; +JsonVariant gJson[REQUESTCOUNT]; +uint8_t gReqCount=0; +bool gGotRequest[REQUESTCOUNT]; + + + +AsyncWebServerRequest *gRequestConstHTML[REQUESTCOUNT]; +uint8_t gReqCountConstHTML=0; +bool gGotRequestConstHTML[REQUESTCOUNT]; +//////// +// +// +// +// +// + +#ifndef min +#define min(a,b) (((a) < (b)) ? (a) : (b)) +#endif +#ifndef max +#define max(a,b) (((a) > (b)) ? (a) : (b)) +#endif + +#include +#include +#include +#include + +//#define BUFF_MAX 128 + +//****************************************Define I2C LCD Display ********************************* +#define I2C_ADDR 0x27 // Define I2C Address for the PCF8574T +//---(Following are the PCF8574 pin assignments to LCD connections )---- +// This are different than earlier/different I2C LCD displays + +#define Rs_pin 0 +#define Rw_pin 1 +#define En_pin 2 +#define BACKLIGHT_PIN 3 +#define D4_pin 4 +#define D5_pin 5 +#define D6_pin 6 +#define D7_pin 7 + + +#define ATMEGA328 //comment out this line if it is not ATMEGA328 +//#define DEBUG //comment out this line to disable for Production(No Serial print) + +#define RRcountSIZE 20 +#define count1Address 0 +#define count1count2diffAddress 40 //only one address which is 40*32 +//int count1Address = 0; +//int count1count2diffAddress = 40; +long count1count2diff = 0; + +#define TRIPSIZE 16 //so thestartaddress is 50*32 until (50+12)*32 +#define TRIPADDRESS 50 + +const byte interruptPin = 32; //2; +#define simulatorPWMPin 19 +bool simstate = false; +volatile bool isloadingConst = false; +bool iscalculatingRally = false; +//const byte ledPin = 13; + +// #ifndef ATMEGA328 + volatile byte ledstate = LOW; +// #endif + +#define LED_OFF 0 +#define LED_ON 1 + +// set the LCD number of columns and rows +const int lcdColumns = 20; +const int lcdRows = 4; + +///lolin esp32 lite i2c pin +#define I2C_SDA 15 +#define I2C_SCL 13 +#define LED_BUILTIN 22 // LED built in pada ESP32 Lolin32 Lite +// set LCD address, number of columns and rows +// if you don't know your display address, run an I2C scanner sketch +LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows); // marcoschwartz. ujungnya jelek + +/*-----( Declare objects )-----*/ +//LiquidCrystal_I2C lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin); +// LiquidCrystal_I2C lcd(I2C_ADDR); +AT24CX mem; +boolean cursorON=true; +boolean blinkON=true; +//************************************ END LCD DISPLAY ******************************************* + +uint8_t thistime[8]; +//char recv[BUFF_MAX]; +unsigned int recv_size = 0; +unsigned long prevsettime, intervalsettime = 250; +unsigned long prevtempint, tempinterval=60000; +unsigned long prevtemprally, tempintervalrally=333; +unsigned long prevcalibrationtime, calibrationtimeinterval = 200; +unsigned long updatecounttime=0; +float temperature; +byte x; +byte y; +// #ifndef y++ +// //#define min(a,b) (((a) < (b)) ? (a) : (b)) +// #define y++ y+1 +// #endif +// #ifndef x++ +// //#define min(a,b) (((a) < (b)) ? (a) : (b)) +// #define x++ x+1 +// #endif + +unsigned long startmillis, startVSSCount; +unsigned long startsavemillis; +unsigned long broadcastwebsocket; +unsigned long broadcastwebsocketcalib; +volatile unsigned long howLongInMillis; + +//#include //https://github.com/JChristensen/Button //from change to +#include + +#define UP_pin 25 //4 +#define DOWN_pin 26 //5 +#define LEFT_pin 27 //6 +#define RIGHT_pin 14 //7 +#define OK_pin 12 //8 + +#define UP_PIN 25 //4 //Connect two tactile button switches (or something similar) +#define DN_PIN 26 //5 //from Arduino pin 2 to ground and from pin 3 to ground. +#define LF_PIN 27 //6 +#define RF_PIN 14 //7 +#define OK_PIN 12 //8 +#define ESC_PIN 33 //10 +#define PULLUPRES true //To keep things simple, we use the Arduino's internal PULLUPRES resistor. +#define INVERT true //Since the pullup resistor will keep the pin high unless the + //switch is closed, this is negative logic, i.e. a high state + //means the button is NOT pressed. (Assuming a normally open switch.) +#define DEBOUNCE_MS 40 //A debounce time of 20 milliseconds usually works well for tactile button switches. + +#define REPEAT_FIRST 1000 //ms required before repeating on long press +#define REPEAT_INCR 75 //repeat interval for long press +#define MIN_COUNT 0 +#define MAX_ROW 3 +#define MAX_COL 19 +#define MS_IN_HOUR 3600000 //Number of ms in an hour +#define MS_IN_MIN 60000 //Number of ms in a minute +// Button btnUP(UP_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); //Declare the buttons +// Button btnDN(DN_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); +// Button btnLF(LF_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); +// Button btnRF(RF_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); //Declare the buttons +// Button btnOK(OK_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); //Declare the buttons +// Button btnESC(ESC_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); //Declare the buttons + +Button btnUP(UP_PIN, DEBOUNCE_MS, PULLUPRES, INVERT); //Declare the buttons +Button btnDN(DN_PIN, DEBOUNCE_MS, PULLUPRES, INVERT); +Button btnLF(LF_PIN, DEBOUNCE_MS, PULLUPRES, INVERT); +Button btnRF(RF_PIN, DEBOUNCE_MS, PULLUPRES, INVERT); //Declare the buttons +Button btnOK(OK_PIN, DEBOUNCE_MS, PULLUPRES, INVERT); //Declare the buttons +Button btnESC(ESC_PIN, DEBOUNCE_MS, PULLUPRES, INVERT); //Declare the buttons + +enum {WAIT, UP, DOWN, LEFT, RIGHT, OKAY, RALLYEDIT, ESC}; //The possible states for the STATE machine +enum {MAIN, CALIBRATION, SETTIME, INPUTSUBTRAYEK, RALLY, CONSTANTA}; //The possible states for the MENU +enum {FORWARD, FREEZE, BACKWARD}; +char const *dircount[] = {"Fw", "Zz", "Bw"}; //CHANGE 2022 +//String dircount[] = {"Fw", "Zz", "Bw"}; + +uint8_t MENU, PREVMENU; +///uint8_t STATE, dircount1, dircount2; ///move to top //The current state machine state +byte hour24, min60, sec60; +unsigned long rpt = REPEAT_FIRST; //A variable time that is used to drive the repeats for long presses +uint8_t prevsec; +float constanta=3.275; +float distance1, distance2; +volatile float prevdistance1, prevdistance2; +volatile long prevcount1, prevcount2; +boolean showTIME = true; + +float tempval; +struct ts t; +byte calibrationDistance=1; +byte tempcalibdist=1; +boolean calibrationON=false; + +float oneMeter=0; +unsigned long startCalibration=0; +unsigned long Calibration=110400; //for CR-V 2012 +unsigned long Calibrationcount; +unsigned long Calibrationcountbackup; +unsigned long Calibrationtime; +int digit1, digit2, digit3, digit4, digit5, digit6; +byte calibdigit1, calibdigit2, calibdigit3; +int dist1digit1, dist1digit2; +int dist2digit1, dist2digit2; +byte starttractsec, starttractmin, starttracthour; +boolean rallyON=false; + +volatile unsigned long VSSCount =0; + +long count1 = 0; //must be signed as technically distance can go negative +long count2 = 0; +long backcount1 = 0; +long backcount2 = 0; + +//The two time variables are used to store reset times in ms +unsigned long time1 = 1; +unsigned long time2 = 1; +int CURSOR_POS = 1; + +unsigned long count1Seq = 0; +boolean editDist1 = false; + +//to save trayek data +struct RallyData { + char sub; + float speed; + byte startHour; + byte startMin; + byte startSec; + float distance; + unsigned int subTime; +}; + //RallyData Trip={"b",23.342, 11,0,0,12.13}; + RallyData Trip[TRIPSIZE]; +//RallyData currentTrip; + +byte curTrip=0; +byte prevTrip=0; + + + +// +// +// +// +// + +void notFound(AsyncWebServerRequest *request) { + request->send(404); +} + +String readFile(fs::FS &fs, const char * path){ + // Serial.printf("Reading file: %s\r\n", path); + if (fs.exists(path)){ + File file = fs.open(path, "r"); + if(!file || file.isDirectory()){ + Serial.println("- empty file or failed to open file"); + return String(); + } + // Serial.print("filesize:");Serial.println(file.size()); + if (!file.size()){ + Serial.println("File is empty"); + file.close(); + return String(); + } + Serial.print("- read from file:"); + String fileContent; + + while(file.available()){ + fileContent+=String((char)file.read()); + } + file.close(); + Serial.println(fileContent); + return fileContent; + } else {return String();} +} + +boolean writeFile(fs::FS &fs, const char * path, const char * message){ + Serial.println(message); + Serial.println(sizeof(message)); + if ((message != NULL) && (message[0] == '\0')) { + Serial.println("message is empty\n"); + return false; + } + if (sizeof(message)==0){ + return false; + } + Serial.printf("Writing file: %s\r\n", path); + File file = fs.open(path, "w"); + if(!file){ + Serial.println("- failed to open file for writing"); + file.close(); + return false; + } + if(file.print(message)){ + Serial.println("- file written"); + file.close(); + return true; + } else { + Serial.println("- write failed"); + file.close(); + return false; + } + file.close(); + return false; +} + +// Replaces placeholder with stored values +String processor(const String& var){ + //Serial.println(var); + Serial.print("Processor "); + Serial.print(var); + if(var == "ssidString"){ + return readFile(SPIFFS, "/ssidString.txt"); + } + else if(var == "localip"){ + return WiFi.localIP().toString(); + } + else if(var == "serveripaddress"){ + if (WiFi.localIP().toString()!="0.0.0.0"){ + Serial.println(WiFi.localIP()); + return WiFi.localIP().toString(); + } else { + Serial.println(WiFi.softAPIP()); + return WiFi.softAPIP().toString(); + } + } + // else if(var == "inputPwd"){ + // return readFile(SPIFFS, "/inputPwd.txt"); + // } + return String(); +} +String procConst(const String& var){ + Serial.print("proConst->"); + Serial.print(var); + return String(); +} + + + + +void OnWiFiEvent(WiFiEvent_t event) +{ + switch (event) { + + case SYSTEM_EVENT_STA_CONNECTED: + Serial.println("ESP32 Connected to WiFi Network"); + break; + case SYSTEM_EVENT_AP_START: + Serial.println("ESP32 soft AP started"); + break; + case SYSTEM_EVENT_AP_STACONNECTED: + Serial.println("Station connected to ESP32 soft AP"); + break; + case SYSTEM_EVENT_AP_STADISCONNECTED: + Serial.println("Station disconnected from ESP32 soft AP"); + break; + default: break; + } +} +String getPin(){ + struct tm timeinfo; + String hasil; + if(!getLocalTime(&timeinfo)){ + Serial.println("Failed to obtain time"); + return hasil; + } + // StaticJsonBuffer<200> jsonBuffer; + // JsonObject& root = JsonBuffer.createObject(); + DynamicJsonDocument testdoc(512); + //String datetime = &timeinfo; + char datetime[21]; + char curtime[9]; + strftime(datetime, 21, "%d %b %Y %H:%M:%S", &timeinfo); + strftime(curtime, 9, "%H:%M:%S", &timeinfo); + //Serial.println(&timeinfo); + //Serial.println(datetime); + testdoc["pin36"]=242; + testdoc["pin39"]=datetime; + testdoc["time"]=curtime; + // testdoc["datetime"]=datetime; + testdoc["pin5"]=millis(); + testdoc["curtime"]=curtime; + testdoc["speed"]=String(float(random(1,20000))/100,1); + testdoc["counter"]=random(0,50000); + String bb[]={"A","B","C","D","E","F","G","H","I","J","K","L"}; + testdoc["curtrack"]=bb[random(12)]; + String dir[]={"FW","STOP","BACK"}; + testdoc["dir1"]=dir[random(3)]; + testdoc["dir2"]=dir[random(3)]; + testdoc["time1"]=curtime; + testdoc["time2"]=curtime; + float odo1=float(millis())/10000; + float odo2=float(millis())/20000; + //Serial.println(odo1,3); + testdoc["odo1"]=String(odo1,3); + testdoc["odo2"]=String(odo2,3); // if disabled, the web will get undefined value + //serializeJson(testdoc,Serial); + serializeJson(testdoc,hasil); + //testdoc.printTo(hasil); + // testdoc.clear(); + return hasil; +} +String getCalib(){ + struct tm timeinfo; + String hasil; + if(!getLocalTime(&timeinfo)){ + Serial.println("Failed to obtain time"); + return hasil; + } + DynamicJsonDocument testdoc(200); + //String datetime = &timeinfo; + char datetime[21]; + char curtime[9]; + strftime(datetime, 21, "%d %b %Y %H:%M:%S", &timeinfo); + strftime(curtime, 9, "%H:%M:%S", &timeinfo); + //Serial.println(&timeinfo); + //Serial.println(datetime); + // testdoc["datetime"]=datetime; + testdoc["curtime"]=curtime; + testdoc["speed"]=String(float(random(1,20000))/100,1); + testdoc["counter"]=random(0,50000); + String bb[]={"A","B","C","D","E","F","G","H","I","J","K","L"}; + testdoc["curtrack"]=bb[random(12)]; + float calkm=float(millis())/100000; + float calmeter=float(millis())/100; + testdoc["caldist"]=random(9); + testdoc["calman"]=random(100000, 150000); + testdoc["calkm"]=String(calkm,3); + testdoc["calmeter"]=String(calmeter,3); + //Serial.println(odo1,3); + testdoc["calval"]=String(calmeter*1000); // if disabled, the web will get undefined value + //serializeJson(testdoc,Serial); + serializeJson(testdoc,hasil); + //testdoc.printTo(hasil); + // testdoc.clear(); + return hasil; +} + +void printLocalTime(){ + struct tm timeinfo; + if(!getLocalTime(&timeinfo)){ + Serial.println("Failed to obtain time"); + return; + } + t.hour=timeinfo.tm_hour; + t.min=timeinfo.tm_min; + t.sec=timeinfo.tm_sec; + t.mday=timeinfo.tm_mday; + t.mon=timeinfo.tm_mon; + t.year=timeinfo.tm_year; + DS3231_set(t); + Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S"); + Serial.print("Day of week: "); + Serial.println(&timeinfo, "%A"); + Serial.print("Month: "); + Serial.println(&timeinfo, "%B"); + Serial.print("Day of Month: "); + Serial.println(&timeinfo, "%d"); + Serial.print("Year: "); + Serial.println(&timeinfo, "%Y"); + Serial.print("Hour: "); + Serial.println(&timeinfo, "%H"); + Serial.print("Hour (12 hour format): "); + Serial.println(&timeinfo, "%I"); + Serial.print("Minute: "); + Serial.println(&timeinfo, "%M"); + Serial.print("Second: "); + Serial.println(&timeinfo, "%S"); + + Serial.println("Time variables"); + char timeHour[3]; + strftime(timeHour,3, "%H", &timeinfo); + Serial.println(timeHour); + char timeWeekDay[10]; + strftime(timeWeekDay,10, "%A", &timeinfo); + Serial.println(timeWeekDay); + Serial.println(); +} + +boolean isDecimal(String str){ + // boolean digit=true; + for(byte i=0;i '9') return false; + } + return true; +} + +boolean isShortTime(const char* st){ + Serial.println(sizeof(st)); //ini size pointer saja longint(4) + Serial.println(strlen(st)); //ini yg benar + Serial.println(st); + + if(strlen(st)!=5) return false; + for (int i=0; iindex ? data.substring(strIndex[0], strIndex[1]) : ""; +} +unsigned long getValueSetTime(const char* st){ + Serial.print("getValueSetTime=");Serial.println(st); + if (!isShortTime(st)) { + Serial.println("getValueSetTime=-1"); + return -1; + } + String x = getSplitValue(st, ':', 0); + int xval=x.toInt(); + String y = getSplitValue(st, ':', 1); + int yval=y.toInt(); + + return ((xval*256)+yval)*256+0; +} + +unsigned long getMemStime(uint8_t getmemsTimecurTrip); + +String getsTime(uint8_t getsTimecurtrip){ + unsigned long sTimeinconstanta; + int sTimeHour; + int sTimeMin; + for(int i=0; i<4; i++){ + sTimeinconstanta = getMemStime(getsTimecurtrip); + sTimeHour = sTimeinconstanta/65536; + sTimeMin = (sTimeinconstanta/256)-sTimeHour*256; + if (sTimeHour<=24 && sTimeMin<=60){ + break; + } + delayMicroseconds(20); + } + // String sTime; + char sTime[6]; + // if (sTimeHour<10){ + sprintf(sTime, "%02d:%02d", sTimeHour, sTimeMin); + Serial.print(getsTimecurtrip);Serial.print("getsTime:");Serial.print(sTimeHour);Serial.print(":");Serial.print(sTimeMin);Serial.print(";");Serial.println(sTime); + // } + return sTime; +} + +void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){ + + if(type == WS_EVT_CONNECT){ + globalClientRally++; + Serial.println("Websocket client connection received"); + Serial.print("Rally Client=");Serial.println(globalClientRally); + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + client->text(getRallyJson); + } else if(type == WS_EVT_DISCONNECT){ + globalClientRally--; + Serial.println("Client disconnected"); + Serial.print("Rally Client=");Serial.println(globalClientRally); + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + } else if(type == WS_EVT_DATA){ + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + Serial.printf("[%u] get Text: %s\n", len, data); + String message = String((char*)( data)); + Serial.println(message); + + DynamicJsonDocument doc(256); + // Deserialize the data + DeserializationError error = deserializeJson(doc, message); + // parse the parameters we expect to receive (TO-DO: error handling) + // test if parsing succeeds + if (error){ + Serial.print("deserialiseJson() failed: "); + Serial.println(error.c_str()); + client->text(error.c_str()); + return; + } + String resetodo=doc["resetodo"]; + String copytoodo=doc["copytoodo"]; + String direction1=doc["dir1"]; + String direction2=doc["dir2"]; + String toggle=doc["toggle"]; + String ctotrip=doc["ctotrip"]; + if (resetodo!="null"){ + if (isDecimal(resetodo)){ + if(resetodo=="1"){ + Serial.print("resetodo=");Serial.println(resetodo); + count1 = 0; + backcount1 = 0; + time1 = VSSCount; + } else if(resetodo=="2"){ + Serial.print("resetodo=");Serial.println(resetodo); + count2 = 0; + backcount2 = 0; + time2 = VSSCount; + } + } + } + if (copytoodo!="null"){ + if (isDecimal(copytoodo)){ + if(copytoodo=="2"){ + Serial.print("copytoodo=");Serial.println(copytoodo); + count2 = count1; //no yet UNDO next update can UNDO + backcount2 = 0; + } else if(copytoodo=="1"){ + Serial.print("copytoodo=");Serial.println(copytoodo); + count1 = count2; //no yet UNDO next update can UNDO + backcount1 = 0; + } + } + } + if (direction1!="null"){ + if (isDecimal(direction1)){ + if(direction1.toInt()>=0 && direction1.toInt()<=3){ + Serial.print("direction1=");Serial.println(direction1); + dircount1=direction1.toInt(); + } + } + } + if (direction2!="null"){ + if (isDecimal(direction2)){ + if(direction2.toInt()>=0 && direction2.toInt()<=3){ + Serial.print("direction2=");Serial.println(direction2); + dircount2=direction2.toInt(); + } + } + } + if (toggle!="null"){ + if (isDecimal(toggle)){ + if(toggle=="1"){ + Serial.print("toggle=");Serial.println(toggle); + showTIME = !showTIME; + } else if(toggle=="2"){ + Serial.print("toggle=");Serial.println(toggle); + showTIME = !showTIME; + } + } + } + if (ctotrip!="null"){ + int temptrip; + temptrip = (int)ctotrip.charAt(0); + if (temptrip>=65 && temptripremoteIP()); + client->text(getCalibJson); + } else if(type == WS_EVT_DISCONNECT){ + globalClientCalib--; + Serial.println("wscal Client disconnected"); + Serial.print("Calib Client=");Serial.println(globalClientCalib); + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + } else if(type == WS_EVT_DATA){ + Serial.print("wscal IPAdd client:"); Serial.println(client->remoteIP()); + Serial.printf("[%u] get Text: %s\n", len, data); + String message = String((char*)( data)); + Serial.println(message); + + DynamicJsonDocument doc(200); + // Deserialize the data + DeserializationError error = deserializeJson(doc, message); + // parse the parameters we expect to receive (TO-DO: error handling) + // test if parsing succeeds + if (error){ + Serial.print("wscal deserialiseJson() failed: "); + Serial.println(error.c_str()); + client->text(error.c_str()); + return; + } + String setcaldis=doc["setcaldis"]; + String setcaldisman=doc["setcaldisman"]; //set calibation distance manual + String calstart=doc["calstart"]; + Serial.print("setcaldis=");Serial.println(setcaldis); + Serial.print("setcaldisman=");Serial.println(setcaldisman); + Serial.print("calstart=");Serial.println(calstart); + if (setcaldis!="null"){ + if (isFloat(setcaldis)){ + Serial.print("setcaldis=");Serial.println(setcaldis.toInt()); + calibrationDistance=setcaldis.toInt(); + } + } + if (setcaldisman!="null"){ + if (isDecimal(setcaldisman)){ + Serial.print("setcaldisman=");Serial.println(setcaldisman.toInt()); + Calibration = setcaldisman.toInt(); + mem.writeLong(896, Calibration); + } + } + if (calstart!="null"){ + if (isDecimal(calstart)){ + if(calstart=="1"){ + Serial.print("calstart=");Serial.println("START"); + Calibrationcount = 0; + startCalibration = VSSCount; + Calibrationtime = startCalibration; + calibrationON=true; + } else if(calstart=="0"){ + Calibration = (VSSCount-startCalibration)/(float)calibrationDistance; + mem.writeLong(896, Calibration); //Save Calibration to memory + oneMeter=(millis()-startCalibration)/(1000*(float)calibrationDistance);//*calibrationDistance); + oneMeter=((float)VSSCount-startCalibration)/(1000*(float)calibrationDistance);//*calibrationDistance); + oneMeter=(float)(Calibration)/1000*(float)calibrationDistance; + calibrationON=false; + } + Serial.print("calstart=");Serial.println("STOP"); + } + } + } +} + +// void configModeCallback (WiFiManager *myWiFiManager) { +// Serial.println("Entered config mode"); +// Serial.println(WiFi.softAPIP()); + +// Serial.println(myWiFiManager->getConfigPortalSSID()); +// } + + + +////// VSSRALLYMODULE +// +// +// +// +// +// +// +// +// + +void printUPchar() +{ + byte thumb1[8] = {B00100,B01110,B11111,B00100,B00100,B00100,B00100,B00100}; + lcd.createChar(1, thumb1); + //lcd.write(1); +} +void printDOWNchar() +{ + byte thumb1[8] = {B00100,B00100,B00100,B00100,B00100,B11111,B01110,B00100}; + lcd.createChar(2, thumb1); + //lcd.write(2); +} +unsigned long memretrieveLong(int startaddress, byte rrpointersize, unsigned long &seq ) +{ + //Serial.print(seq);Serial.print(";R ");Serial.print(rrpointer[0]);Serial.print("; SizeofArr=");Serial.println(rrpointersize); + unsigned long largestcountpointer=0; + int lastpointer = 0; + unsigned long seqnumber = 0; + int pointeradd = 0; + for (int i = 0; i");Serial.println(mem.readLong(pointer+(i*32))); + } +} +*/ + +void memretrieveTrip(int pointer, int startaddress) +{ + //Serial.print (pointer); Serial.println(startaddress); + int pointeradd; + Trip[pointer].speed = mem.readFloat(startaddress); + pointeradd = (startaddress + 6); + Trip[pointer].startHour = mem.read(pointeradd); + pointeradd = (startaddress + 5); + Trip[pointer].startMin = mem.read(pointeradd); + pointeradd = (startaddress + 4); + Trip[pointer].startSec = mem.read(pointeradd); + if (Trip[pointer].startHour >= 24) Trip[pointer].startHour = 23; + if (Trip[pointer].startMin >= 60) Trip[pointer].startMin = 59; + if (Trip[pointer].startSec >= 60) Trip[pointer].startSec = 59; +} + +void constantatodigit() +{ + digit1=(int)(constanta/10); + digit2=(int)constanta%10; + digit3=(int)((constanta - (int)constanta)*10); + digit4=(int)((constanta*10 - (int)(constanta*10))*10); + digit5=(int)((constanta*100 - (int)(constanta*100))*10); + digit6=(int)((constanta*1000 - (int)(constanta*1000))*10); + //digit6=(int)((constanta*10000 - (int)(constanta*10000))*10); +} + +void setMemSpeedInConstanta(float constanta, uint8_t setmemcurTrip){ + int pointeradd = ((TRIPADDRESS+setmemcurTrip)*32); + mem.writeFloat(pointeradd, constanta); + Trip[setmemcurTrip].speed = constanta; +} +float getMemSpeedInConstanta(uint8_t getmemSpeedcurTrip){ + int pointeradd = ((TRIPADDRESS+getmemSpeedcurTrip)*32); + float x=mem.readFloat(pointeradd); + if(isnan(x)) { + delayMicroseconds(10); + x=mem.readFloat(pointeradd); + } + return x; +} +void setMemStime(unsigned long valuesettime, uint8_t setmemssTimecurTrip){ + int pointeradd = ((TRIPADDRESS+setmemssTimecurTrip)*32+4); + mem.writeLong(pointeradd, valuesettime); + Trip[setmemssTimecurTrip].startHour = (valuesettime/65536); //starttracthour; + Trip[setmemssTimecurTrip].startMin = (valuesettime/256)-Trip[setmemssTimecurTrip].startHour*256; // starttractmin; + Trip[setmemssTimecurTrip].startSec = valuesettime-((Trip[setmemssTimecurTrip].startHour*256 + Trip[curTrip].startMin)*256);//starttractsec; + Serial.print(Trip[setmemssTimecurTrip].startHour);Serial.print(";"); + Serial.print(Trip[setmemssTimecurTrip].startMin);Serial.print(";"); + Serial.println(Trip[setmemssTimecurTrip].startSec); +} +unsigned long getMemStime(uint8_t getmemsTimecurTrip){ + int pointeradd = ((TRIPADDRESS+getmemsTimecurTrip)*32+4); + return mem.readLong(pointeradd); +} + +void blink() { +// #ifndef ATMEGA328 + ledstate = !ledstate; +// #else +// PORTB ^= B00100000; +// #endif + VSSCount++; +} + + + + +#ifdef DEBUG +long prevtimemicros=micros(); //************************************************************************** +#endif +unsigned long rallyEditTime=micros(); +byte rallyEditRpt = 0; +boolean rallyEdit =false; +boolean savedCount = true; +unsigned long intervalsavemillis = 3000; + + +void printMOVEchar() +{ + byte Movechar3[8] = {B00000,B00000,B00000,B00000,B00000,B00000,B00000,B11111}; + lcd.createChar(3, Movechar3); + byte Movechar4[8] = {B00000,B00000,B00000,B00000,B00000,B00000,B11111,B11111}; + lcd.createChar(4, Movechar4); + byte Movechar5[8] = {B00000,B00000,B00000,B00000,B00000,B11111,B11111,B11111}; + lcd.createChar(5, Movechar5); +} + + +void lcdprint2digit(byte val) +{ + if (val<10) lcd.print("0"); + lcd.print(val); +} +void setTheTime(char *cmd) +{ + // ssmmhhWDDMMYYYY set time + + t.sec = inp2toi(cmd, 0); + t.min = inp2toi(cmd, 2); + t.hour = inp2toi(cmd, 4); + t.wday = inp2toi(cmd, 6); + t.mday = inp2toi(cmd, 7); + t.mon = inp2toi(cmd, 9); + t.year = inp2toi(cmd, 11) * 100 + inp2toi(cmd, 13); + DS3231_set(t); +#ifdef DEBUG + Serial.println("OK setTheTime()"); +#endif +} + +void printMonth(int month) +{ + switch(month) + { + case 1: lcd.print(" January ");break; + case 2: lcd.print(" February ");break; + case 3: lcd.print(" March ");break; + case 4: lcd.print(" April ");break; + case 5: lcd.print(" May ");break; + case 6: lcd.print(" June ");break; + case 7: lcd.print(" July ");break; + case 8: lcd.print(" August ");break; + case 9: lcd.print(" September ");break; + case 10: lcd.print(" October ");break; + case 11: lcd.print(" November ");break; + case 12: lcd.print(" December ");break; + default: lcd.print(" Error ");break; + } +} + +void mainMenu() +{ + MENU = MAIN; + lcd.clear(); + lcd.print("1. Rally TSD"); + lcd.setCursor(0,1); + lcd.print("2. Set Main Time"); + lcd.setCursor(0,2); + lcd.print("3. Input Constanta"); + lcd.setCursor(0,3); + lcd.print("4. Calibration ODO"); + //lcd.home(); + x=2; + y=0; + lcd.cursor(); + lcd.setCursor(x,y); + PREVMENU = MENU; +} + +void runningtime(byte x1,byte y1) +{ + lcd.setCursor(x1,y1); //Go to second line of the LCD Screen + if(t.hour<10) + { + lcd.print("0"); + } + lcd.print(t.hour); + lcd.print(":"); + if(t.min<10) + { + lcd.print("0"); + } + lcd.print(t.min); + lcd.print(":"); + if(t.sec<10) + { + lcd.print("0"); + } + lcd.print(t.sec); +} + +String runningtimeforESP32(byte x1,byte y1) +{ + String runningTIME; + // lcd.setCursor(x1,y1); //Go to second line of the LCD Screen + if(t.hour<10) + { + // lcd.print("0"); + runningTIME="0"; + } + // lcd.print(t.hour); + // lcd.print(":"); + runningTIME+=t.hour; + runningTIME+=":"; + if(t.min<10) + { + // lcd.print("0"); + runningTIME+="0"; + } + // lcd.print(t.min); + // lcd.print(":"); + runningTIME+=t.min; + runningTIME+=":"; + if(t.sec<10) + { + // lcd.print("0"); + runningTIME+="0"; + } + // lcd.print(t.sec); + runningTIME+=t.sec; + // Serial.print("t.hour:");Serial.println(t.hour); + // Serial.print("runningtimeforesp:");Serial.println(runningTIME); + return runningTIME; +} + +void settimeMenu() +{ + lcd.setCursor(0,0); + lcd.print(t.mday); + printMonth(t.mon); + lcd.print(t.year); + + runningtime(0,1); + + lcd.setCursor(x,y); + prevsec = t.sec; + PREVMENU = MENU; +} + + +void calibrationMenu() +{ + MENU = CALIBRATION; + lcd.clear(); + lcd.setCursor(0,0); + lcd.print("Calibration Back"); + lcd.setCursor(0,1); + lcd.print("Set Distance(Km): "); + lcd.print(calibrationDistance); + lcd.setCursor(0,2); + lcd.print("Start 00.000Km"); + lcd.setCursor(0,3); + lcd.print("1m="); + lcd.print(((float)Calibration/1000),3); + char Calibrationstr[6]; + sprintf(Calibrationstr, "%06lu", Calibration); + lcd.setCursor(14,3); + lcd.print(Calibrationstr); + lcd.setCursor(0,0); + lcd.print("Calibration Back"); + //lcd.setCursor(0,0); + //lcd.print(Calibration); + //lcd.home(); + x=18; + y=0; + lcd.setCursor(x,y); + lcd.cursor(); + //lcd.blink(); + //blinkON=true; + PREVMENU = MENU; + Serial.print(Calibrationstr);Serial.println("end"); +} + +void constantaMenu() +{ + MENU = CONSTANTA; + lcd.clear(); + lcd.print("Constanta Back"); + lcd.setCursor(0,1); + lcd.print("Sub Trip:"); + lcd.setCursor(14,1); + lcd.print(Trip[curTrip].sub); + lcd.setCursor(0,2); + lcd.print("Set Speed:"); + lcd.setCursor(13,2); + if (constanta<10) lcd.print("0"); + lcd.print(constanta,4); + //lcd.print( + lcd.setCursor(0,3); + lcd.print("Start Time:"); + //DS3231_get(&t); //Get time + lcd.setCursor(12,3); //Go to second line of the LCD Screen + if(starttracthour<10) + { + lcd.print("0"); + } + lcd.print(starttracthour); + lcd.print(":"); + if(starttractmin<10) + { + lcd.print("0"); + } + lcd.print(starttractmin); + lcd.print(":"); + if(starttractsec<10) + { + lcd.print("0"); + } + lcd.print(starttractsec); + lcd.print(""); + //x=14; + //y=0; + lcd.setCursor(x,y); + lcd.cursor(); + //lcd.blink(); + //blinkON=true; + PREVMENU = MENU; + +} +void updateCount() +{ + if (dircount1 == FORWARD) { + count1 = count1 + (VSSCount-time1); + } + else if (dircount1 == BACKWARD) { + count1 = count1 - (VSSCount-time1); + } + + if (dircount2 == FORWARD) { + count2 = count2 + (VSSCount-time2); + } + else if (dircount2 == BACKWARD) { + count2 = count2 - (VSSCount-time2); + } + time1 = VSSCount; + time2 = VSSCount; +} +void saveCount() +{ + if (count1 != prevcount1) { + count1Seq++; + memwritingLong(count1Address, RRcountSIZE, count1Seq, count1);//(int startaddress, byte RRsize, unsigned long seq, unsigned long Data) + prevcount1 = count1; + } + + if ((count1-count2) != count1count2diff) { +#ifdef DEBUG + Serial.print("count1=");Serial.print(count1);Serial.print(";count2=");Serial.print(count2);Serial.print("countdiff=");Serial.println(count1count2diff); +#endif + count1count2diff = count1-count2; + int pointer = count1count2diffAddress*32; + mem.writeLong(pointer,count1count2diff); +#ifdef DEBUG + Serial.println("save count1count2diff"); +#endif + } +} + + +void secondrallyMenu() +{ + + char heading2[6]; + char heading4[6]; + lcd.setCursor(9,1); + //sprintf(heading2, "%s", (dirfwdcount1?"Fw":"Bw")); + sprintf(heading2, "%s", dircount[dircount1]); + lcd.print(heading2); + + lcd.setCursor(9,3); + //sprintf(heading4, "%s", (dirfwdcount2?"Fw":"Bw")); + sprintf(heading4, "%s", dircount[dircount2]); + lcd.print(heading4); + +#ifdef DEBUG + Serial.println("secondrallyMenu"); +#endif +} + +void rallyMenu() +{ + MENU = RALLY; + + //lcd.clear(); + lcd.setCursor(15,0); + if (showTIME) lcd.print("Time "); + else lcd.print("TDiff"); + + secondrallyMenu(); + PREVMENU = MENU; +// #ifdef DEBUG + Serial.println("rallyMenu"); +// #endif +} + +unsigned long startspeed=0; +float startdistance=0; + +void redrawcalibrationMenu() +{ +// bool test=false; + + float distance; + Calibrationcount = Calibrationcount + (VSSCount-Calibrationtime); + distance = (float)Calibrationcount/((float)Calibration); + char cur_distance_str[9]; + byte xtemp=13; + if (distance<100) { + sprintf(cur_distance_str, "%02d.%03dKm", (int)distance, (int)((distance - (int)distance)*1000)); + xtemp = 12; + } + else if (distance<1000) { + sprintf(cur_distance_str, "%02d.%02dKm", (int)distance, (int)((distance - (int)distance)*100)); + } + else { + sprintf(cur_distance_str, "%03d.%01dKm", (int)distance, (int)((distance - (int)distance)*10)); + } +// if(test){ + Calibrationtime = VSSCount; + lcd.setCursor(xtemp,2); + lcd.print(cur_distance_str); +// } +} + +void redrawcalibrationMenuForESP32() +{ + DynamicJsonDocument getCalib(512); + deserializeJson(getCalib, getCalibJson); + float distance; + Calibrationcount = Calibrationcount + (VSSCount-Calibrationtime); + distance = (float)Calibrationcount/((float)Calibration); + // char cur_distance_str[8]; + + Calibrationtime = VSSCount; + // lcd.setCursor(xtemp,2); + // lcd.print(cur_distance_str); + getCalib["counter"]=VSSCount; ///// + getCalib["curTrip"]=String(Trip[curTrip].sub); ///// + getCalib["curTripSpeed"]=String(Trip[curTrip].speed); ///// + String curTime = runningtimeforESP32(6,0); + getCalib["curTime"]=curTime; + + getCalib["caldist"]=calibrationDistance; + getCalib["calman"]= Calibration; + // Serial.println(cur_distance_str); + if (calibrationON){ + getCalib["calkm"]= String(distance,3); + Calibrationcountbackup=Calibrationcount; + } else { + distance = (float)Calibrationcountbackup/((float)Calibration); + getCalib["calkm"]= String(distance, 3); + } + getCalib["calmeter"]=String(float(Calibration)/1000,3); + getCalib["calval"]= Calibration; + + getCalibJson = ""; + serializeJson(getCalib, getCalibJson); +} + +void redrawrallyMenu() +{ + // Serial.println("redrawRM"); + DS3231_get(&t); //Get time + //runningtime(6,0); + //float distance, distance1, distance2; + + //Serial.print(tempcount1);Serial.print(";"); Serial.print(time1);Serial.print("; ");Serial.print(Calibration); Serial.print(";"); Serial.println(count1); + updateCount(); + + //distance = (float)count1/((float)Calibration); + distance1 = (float)count1/((float)Calibration); // * 1); + distance2 = (float)count2/((float)Calibration); + float speed1=0; + + if ((distance1 - startdistance) > 0) { + speed1 = (distance1-startdistance)/(millis()-startspeed)*3600000; + } + + startdistance = distance1; + startspeed = millis(); //startspeed is only one no startspeed2 +// Serial.println("redrawRM 1"); + if ((millis()-startsavemillis)>0) { + + if (distance1 != prevdistance1) { + mem.writeFloat(832,distance1); + prevdistance1 = distance1; + } + if (distance2 != prevdistance2) { + mem.writeFloat(864,distance2); + prevdistance2 = distance2; + } + saveCount(); + startsavemillis=millis()+2500; + } + //Serial.print(tempcount1);Serial.print(";"); Serial.print(time1);Serial.print("; ");Serial.print(Calibration); Serial.print(";"); Serial.println(count1); + + //Serial.print(millis());Serial.print(";");Serial.println(distance1,3); + //Serial.print(starttracthour); Serial.print(":"); Serial.print(starttractmin); Serial.print(":"); Serial.println(starttractsec); + //Serial.println(distance2,3); + + lcd.setCursor(4,0); + lcd.print(Trip[curTrip].sub); + lcd.setCursor(0,2); + + lcd.print(Trip[curTrip].speed); + lcd.print("Km/H"); + + runningtime(6,0); + + lcd.setCursor(11,2); + char cur_speed_str[9]; + int speedtemp=(int)speed1; + int speedtemp2=(int)((speed1 - (int)speed1)*10); + + sprintf(cur_speed_str, "%3d.%01dKm/h", speedtemp , speedtemp2 ); +// Serial.print(count1); Serial.print(";");Serial.print(Calibration); Serial.print(";");Serial.print(speed1); Serial.print(";");Serial.println(cur_speed_str); +// Serial.print(distance1); Serial.print(";");Serial.print(startdistance); Serial.print(";");Serial.print(startspeed); Serial.println(";"); + lcd.print(cur_speed_str); + char cur_distance1_str[8]; + char cur_distance2_str[8]; + lcd.setCursor(0,1); +// Serial.print(";redrawRM 2;"); + if (distance1<100) { + sprintf(cur_distance1_str, "%02d.%03dKm", (int)distance1, (int)((distance1 - (int)distance1)*1000)); + } + else if (distance1<1000) { + sprintf(cur_distance1_str, "%02d.%02dKm", (int)distance1, (int)((distance1 - (int)distance1)*100)); + } + else { + sprintf(cur_distance1_str, "%03d.%01dKm", (int)distance1, (int)((distance1 - (int)distance1)*10)); + } + //lcd.print(distance1,3); + lcd.print(cur_distance1_str); + + lcd.setCursor(0,3); + if (distance2<100) { + sprintf(cur_distance2_str, "%02d.%03dKm", (int)distance2, (int)((distance2 - (int)distance2)*1000)); + } + else if (distance2<1000) { + sprintf(cur_distance2_str, "%02d.%02dKm", (int)distance2, (int)((distance2 - (int)distance2)*100)); + } + else { + sprintf(cur_distance2_str, "%03d.%01dKm", (int)distance2, (int)((distance2 - (int)distance2)*10)); + } + //lcd.print(distance2,3); + lcd.print(cur_distance2_str); + + // Serial.print(";redrawRM 3;"); + float distancetime1 = distance1 * 60 / constanta; + float distancetime2 = distance2 * 60 / constanta; + +//Calculating all about TIME,TDiff(including passing 23:59:59) + lcd.setCursor(9,1); + int secs1, mins1, hours1; + + secs1 = (distancetime1-(int)distancetime1)*60; + mins1 = (int)distancetime1 % 60; + hours1 = (int)distancetime1 / 60; + unsigned long totcurrentsecs = t.sec + (t.min*60) + ((long)t.hour*3600); + unsigned long totsecs1 = secs1 + (mins1*60) + ((long)hours1*3600); + unsigned long totstarttractsecs = starttractsec + (starttractmin*60) + ((long)starttracthour*3600); + unsigned long tottime1 = totsecs1 + totstarttractsecs; + boolean negatifsign = false; +// Serial.print(";redrawRM 4;"); +//Serial.print((long)starttracthour*3600); Serial.print(";"); Serial.print(starttractmin*60); Serial.println(";"); +//Serial.print(totsecs1); Serial.print(";"); Serial.print(totstarttractsecs); Serial.print(";"); +//Serial.print(tottime1);Serial.print(";");Serial.println(totcurrentsecs); + if (totcurrentsecs=0) { //positif means we are too fast, slow down please. + if (tottime1 >= totcurrentsecs) { //positif means we are too fast, slow down please. + // Serial.println("pos"); + negatifsign = false; + tottime1 = tottime1 - totcurrentsecs; + } + else { //negatif means we need to hurry, its late + // Serial.println("neg"); + negatifsign = true; + tottime1 = totcurrentsecs - tottime1; + } + } + //Serial.print(negatifsign);Serial.print(";"); Serial.println(tottime1); + hours1 = ((int)(tottime1 / 3600))%24; + mins1 = (int)((tottime1 % 3600)/60); + secs1 = (tottime1 % 60); + + char cur_time1_str[12]; + if (showTIME) { + sprintf(cur_time1_str, "%s %02d:%02d:%02d", dircount[dircount1], hours1, mins1, secs1); + } + else { + if (hours1 < 10) sprintf(cur_time1_str, "%s %s%01d:%02d:%02d", dircount[dircount1], (negatifsign?"-":" "), hours1, mins1, secs1); + else sprintf(cur_time1_str, "%s%s%02d:%02d:%02d", dircount[dircount1], (negatifsign?"-":" "), hours1, mins1, secs1); + + } + lcd.print(cur_time1_str); +// Serial.print(";redrawRM 5;"); +// Print Second TIME + lcd.setCursor(9,3); + int secs2, mins2, hours2; + + secs2 = (distancetime2-(int)distancetime2)*60; + mins2 = (int)distancetime2 % 60; + hours2 = (int)distancetime2 / 60; + + unsigned long totsecs2 = secs2 + (mins2*60) + ((long)hours2*3600); + unsigned long tottime2 = totsecs2 + totstarttractsecs; +//Serial.println(tottime2); + + if (!showTIME) { + if (tottime2 >= totcurrentsecs) { //positif means we are too fast, slow down please. + negatifsign = false; + tottime2 = tottime2 - totcurrentsecs; + } + else { //negatif means we need to hurry, its late + negatifsign = true; + tottime2 = totcurrentsecs - tottime2 ; + } + } +// Serial.print(";redrawRM 6;"); + hours2 = ((int)(tottime2 / 3600))%24; + mins2 = (int)((tottime2 % 3600)/60); + secs2 = (tottime2 % 60); + char cur_time2_str[12]; + if (showTIME) { + sprintf(cur_time2_str, "%s %02d:%02d:%02d", dircount[dircount2], hours2, mins2, secs2); + } + else { + if (hours2<10) sprintf(cur_time2_str, "%s %s%01d:%02d:%02d", dircount[dircount2], (negatifsign?"-":" "), hours2, mins2, secs2); + else sprintf(cur_time2_str, "%s%s%02d:%02d:%02d", dircount[dircount2], (negatifsign?"-":" "), hours2, mins2, secs2); + } + //sprintf(cur_time2_str, "%s%02d:%02d:%02d", (dirfwdcount2?"Fw":"Bw"), hours2, mins2, secs2); + //sprintf(cur_time2_str, "%s %02d:%02d:%02d", dircount[dircount2], hours2, mins2, secs2); + lcd.print(cur_time2_str); +/* //may be needed to refresh if Km more than 10000Km + lcd.setCursor(8,3); + lcd.write(1); //UP Arrow + + lcd.setCursor(8,1); + lcd.write(2); //DOWN Arrow +*/ + lcd.setCursor(x,y); + // Serial.println("END redrawRM"); +} + +void calculationRally() //calculation only ESP32 +{ + DynamicJsonDocument getRally(1024); + deserializeJson(getRally, getRallyJson); + DS3231_get(&t); //Get time + // Serial.println("startCRal"); + updateCount(); + + distance1 = (float)count1/((float)Calibration); // * 1); + distance2 = (float)count2/((float)Calibration); + float speed1=0; + + if ((distance1 - startdistance) > 0) { + speed1 = (distance1-startdistance)/(millis()-startspeed)*3600000; + } + + startdistance = distance1; + startspeed = millis(); //startspeed is only one no startspeed2 + + if ((millis()-startsavemillis)>0) { + + if (distance1 != prevdistance1) { + mem.writeFloat(832,distance1); + prevdistance1 = distance1; + } + if (distance2 != prevdistance2) { + mem.writeFloat(864,distance2); + prevdistance2 = distance2; + } + saveCount(); + startsavemillis=millis()+2500; + } + + // lcd.setCursor(4,0); + // lcd.print(Trip[curTrip].sub); + // lcd.setCursor(0,2); + + // lcd.print(Trip[curTrip].speed); + // lcd.print("Km/H"); + getRally["Trip"]=String(Trip[curTrip].sub); ///// + getRally["TSpeed"]=String(Trip[curTrip].speed); ///// + char sTime[9]; + sprintf(sTime, "%02u:%02u:%02u", Trip[curTrip].startHour, Trip[curTrip].startMin, Trip[curTrip].startSec); + getRally["TsTime"]=sTime; ///// + getRally["TTime"]=String(Trip[curTrip].subTime); ///// + getRally["TDist"]=String(Trip[curTrip].distance); ///// + + // Serial.print(Trip[curTrip].sub);Serial.print(Trip[curTrip].speed);Serial.print(";");Serial.println(Trip[curTrip].startHour); + + String curTime = runningtimeforESP32(6,0); + getRally["Time"]=curTime; + // lcd.setCursor(11,2); + char cur_speed_str[7]; + sprintf(cur_speed_str, "%3d.%01d", (int)speed1, (int)((speed1 - (int)speed1)*10)); + // lcd.print(cur_speed_str); + getRally["curSpeed"]=cur_speed_str; ///// + // char cur_distance1_str[8]; + // char cur_distance2_str[8]; + char cur_distance1_plain[7]; + char cur_distance2_plain[7]; + // lcd.setCursor(0,1); + + if (distance1<100) { + sprintf(cur_distance1_plain, "%02d.%03d", (int)distance1, (int)((distance1 - (int)distance1)*1000)); + } + else if (distance1<1000) { + sprintf(cur_distance1_plain, "%02d.%02d", (int)distance1, (int)((distance1 - (int)distance1)*100)); + } + else { + sprintf(cur_distance1_plain, "%03d.%01d", (int)distance1, (int)((distance1 - (int)distance1)*10)); + } + + // lcd.print(cur_distance1_str); + getRally["curDist1"]=String(cur_distance1_plain); + // lcd.setCursor(0,3); + + if (distance2<100) { + sprintf(cur_distance2_plain, "%02d.%03d", (int)distance2, (int)((distance2 - (int)distance2)*1000)); + } + else if (distance2<1000) { + sprintf(cur_distance2_plain, "%02d.%02d", (int)distance2, (int)((distance2 - (int)distance2)*100)); + } + else { + sprintf(cur_distance2_plain, "%03d.%01d", (int)distance2, (int)((distance2 - (int)distance2)*10)); + } + + // lcd.print(cur_distance2_str); + getRally["curDist2"]=cur_distance2_plain; + + float distancetime1 = distance1 * 60 / constanta; + float distancetime2 = distance2 * 60 / constanta; + +//Calculating all about TIME,TDiff(including passing 23:59:59) + // lcd.setCursor(9,1); + int secs1, mins1, hours1; + + secs1 = (distancetime1-(int)distancetime1)*60; + mins1 = (int)distancetime1 % 60; + hours1 = (int)distancetime1 / 60; + unsigned long totcurrentsecs = t.sec + (t.min*60) + ((long)t.hour*3600); + unsigned long totsecs1 = secs1 + (mins1*60) + ((long)hours1*3600); + unsigned long totstarttractsecs = starttractsec + (starttractmin*60) + ((long)starttracthour*3600); + unsigned long tottime1 = totsecs1 + totstarttractsecs; + boolean negatifsign = false; + + if (totcurrentsecs=0) { //positif means we are too fast, slow down please. + if (tottime1 >= totcurrentsecs) { //positif means we are too fast, slow down please. + // Serial.println("pos"); + negatifsign = false; + tottime1 = tottime1 - totcurrentsecs; + } + else { //negatif means we need to hurry, its late + // Serial.println("neg"); + negatifsign = true; + tottime1 = totcurrentsecs - tottime1; + } + } + //Serial.print(negatifsign);Serial.print(";"); Serial.println(tottime1); + hours1 = ((int)(tottime1 / 3600))%24; + mins1 = (int)((tottime1 % 3600)/60); + secs1 = (tottime1 % 60); + + // char cur_time1_str[12]; + char cur_time1_plain[10]; + + if (showTIME) { + sprintf(cur_time1_plain, "%02d:%02d:%02d", hours1, mins1, secs1); + } + else { + if (hours1<10) sprintf(cur_time1_plain, "%s%01d:%02d:%02d", (negatifsign?"-":" "), hours1, mins1, secs1); + else sprintf(cur_time1_plain, "%s%02d:%02d:%02d", (negatifsign?"-":" "), hours1, mins1, secs1); + } + // lcd.print(cur_time1_str); + getRally["time1"]=cur_time1_plain; + getRally["dir1"]=dircount[dircount1]; + +// Print Second TIME + // lcd.setCursor(9,3); + int secs2, mins2, hours2; + + secs2 = (distancetime2-(int)distancetime2)*60; + mins2 = (int)distancetime2 % 60; + hours2 = (int)distancetime2 / 60; + + unsigned long totsecs2 = secs2 + (mins2*60) + ((long)hours2*3600); + unsigned long tottime2 = totsecs2 + totstarttractsecs; +//Serial.println(tottime2); + + if (!showTIME) { + if (tottime2 >= totcurrentsecs) { //positif means we are too fast, slow down please. + negatifsign = false; + tottime2 = tottime2 - totcurrentsecs; + } + else { //negatif means we need to hurry, its late + negatifsign = true; + tottime2 = totcurrentsecs - tottime2 ; + } + } + + // Serial.println("MidCRal"); + + hours2 = ((int)(tottime2 / 3600))%24; + mins2 = (int)((tottime2 % 3600)/60); + secs2 = (tottime2 % 60); + char cur_time2_str[12]; + char cur_time2_plain[9]; + if (showTIME) { + sprintf(cur_time2_str, "%s %02d:%02d:%02d", dircount[dircount2], hours2, mins2, secs2); + } + else { + if (hours2<10) sprintf(cur_time2_str, "%s %s%01d:%02d:%02d", dircount[dircount2], (negatifsign?"-":" "), hours2, mins2, secs2); + else sprintf(cur_time2_str, "%s%s%02d:%02d:%02d", dircount[dircount2], (negatifsign?"-":" "), hours2, mins2, secs2); + } + + if (showTIME) { + sprintf(cur_time2_plain, "%02d:%02d:%02d", hours2, mins2, secs2); + } + else { + if (hours2<10) sprintf(cur_time2_plain, "%s%01d:%02d:%02d", (negatifsign?"-":" "), hours2, mins2, secs2); + else sprintf(cur_time2_plain, "%s%02d:%02d:%02d", (negatifsign?"-":" "), hours2, mins2, secs2); + } + + // lcd.print(cur_time2_str); + getRally["time2"]=cur_time2_plain; + getRally["dir2"]=dircount[dircount2]; + + // lcd.setCursor(x,y); + getRally["counter"]=VSSCount; + getRallyJson=""; + serializeJson(getRally, getRallyJson); + // Serial.println("ENDCRal"); +} ///// calculation only for esp32 + +void set_cursor_pos(int new_pos) +{ + /* + Cursor Positon map: + ---------------------- + |Count1 TIME AvgSp| + |1 35 |7 9 | + |Count2 KmH| + |2 46 |8 10| + ---------------------- + */ + + //Need to clear the previous cursor position + //int x, y; + switch(CURSOR_POS) + { + case 1: + x = 0; + y = 1; + break; + case 2: + x = 0; + y = 3; + break; + case 3: + x = 8; //Km is 7,1 + y = 1; + break; + case 4: + x = 8; //Km is 7,3 + y = 3; + break; + case 5: + x = 9; + y = 1; + break; + case 6: + x = 9; + y = 3; + break; + case 7: + x = 13; + y = 1; + break; + case 8: + x = 13; + y = 3; + break; + case 9: + x = 18; + y = 1; + break; + case 10: + x = 18; + y = 3; + break; + } + lcd.print(" "); + lcd.blink(); + lcd.setCursor(8,3); + lcd.write(1); //UP Arrow + + lcd.setCursor(8,1); + lcd.write(2); //DOWN Arrow + + lcd.setCursor(x,y); + +/* + switch(new_pos) + { + case 1: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_RIGHT); + break; + case 2: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_RIGHT); + break; + case 3: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 4: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 5: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 6: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 7: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_LEFT); + break; + case 8: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_LEFT); + break; + } +*/ + + CURSOR_POS = new_pos; +#ifdef DEBUG + Serial.print("SetCursorPosition:"); + Serial.println(CURSOR_POS); +#endif +} + + +void IRAM_ATTR isr() { //esp32 only + VSSCount++; + ledstate=!ledstate; +} + +void convertJsonTripToTripStruct(uint8_t iTrip, const char* strJson){ + // Serial.print(iTrip); Serial.print(";");Serial.println(strJson); + DynamicJsonDocument doc(256); + deserializeJson(doc, strJson); + Trip[iTrip].distance = doc["dist"]; + Trip[iTrip].subTime = doc["time"]; +} +void fillTripArray(){ + char tempTrip[7]="/tripZ"; + // Serial.println(tempTrip); + String tempReadFile; + tempReadFile.reserve(100); + for (uint8_t i=0; isend_P(200, "text/html", HTML_CALIBRATION, processor); + // isloadingConst=true; + howLongInMillis=millis(); + int pageZise; + int pageZiseConstRow; + pageZise=strlen_P(HTML_CONSTHEADER) + strlen_P(HTML_CONSTROW)*TRIPSIZE + strlen_P(HTML_CONSTEND); + String PAGE; + PAGE.reserve(pageZise); + pageZiseConstRow = strlen_P(HTML_CONSTROW); + String PAGEROW; + PAGEROW.reserve(pageZiseConstRow); + + PAGE = FPSTR(HTML_CONSTHEADER); + for (uint8_t i=65; i<(TRIPSIZE+65); i++){ + PAGEROW = FPSTR(HTML_CONSTROW); + PAGEROW.replace("%A%", String(char(i))); + PAGEROW.replace("%speed%", "speed"+String(char(i))); + PAGEROW.replace("%dist%", "dist"+String(char(i))); + PAGEROW.replace("%time%", "time"+String(char(i))); + PAGEROW.replace("%stime%", "stime"+String(char(i))); + // Serial.println(PAGEROW); + PAGE += PAGEROW; + } + PAGE += FPSTR(HTML_CONSTEND); + // Serial.println(PAGE); + Serial.print(pageZise); + Serial.print("PAGE Size:"); + Serial.println(PAGE.length()); + request->send(200, "text/html", PAGE); + // request->send(SPIFFS, "/constanta.html", String(), false, procConst); // read from spiif straight away + // isloadingConst=false; +} +void handlesetConst(AsyncWebServerRequest *request, JsonVariant &json){ + isloadingConst=true; + // JsonObject& jsonObj = json.as(); + if (not json.is()) { + Serial.println("Not JSONG object"); + request->send(400, "text/plain", "Not an object"); + return; + } + auto&& data = json.as(); + String hasil; + hasil.reserve(100); + boolean canSave = true; + const char* datatrip = data["trip"]; + char trip = datatrip[0]; + int iTrip = ((int) trip)-65; + uint8_t constCurTrip= (int)trip; + Serial.println(trip);Serial.println(iTrip);Serial.println(constCurTrip); + if (constCurTrip >= 65 && constCurTrip < (TRIPSIZE+65)){ + constCurTrip = constCurTrip-65; + } else { + canSave = false; + } + + // const char* speed = data["speed"].as(); + float speed = data["speed"].as(); + float dist = data["dist"].as(); + const char* time = data["time"].as();//.as(); + // if (!isNumeric(speed)){ + // canSave = false; + // } + float constconstanta = speed; //.toFloat(); + // String constdist = data["dist"].as(); + // String consttime = data["time"].as(); + const char* stime = data["stime"].as();//.as(); + unsigned long constvaluesettime; + if(!isShortTime(stime)){ + canSave = false; + } + constvaluesettime = getValueSetTime(stime); + Serial.println(dist); + if (constvaluesettime==-1){ + canSave = false; + } + + Serial.print(constconstanta,3); Serial.print(";"); Serial.println(constCurTrip); + Serial.print(constvaluesettime); Serial.print(";"); Serial.println(speed); + AsyncResponseStream *response = request->beginResponseStream("application/json"); + if (canSave){ + // String filename = String("/trip"+trip); + char filename[7] = "/tripZ"; + // Serial.println(filename); + // Serial.println(filename); + filename[5]=trip; + Serial.println(filename); + // if (speed != "" && speed !="null" && stime!= "" && stime !="null") { + // if (stime!= "" && stime !="null") { + bool wfile; + serializeJson(data, hasil); + wfile = writeFile(SPIFFS, filename, hasil.c_str()); + if (wfile){ + setMemSpeedInConstanta(constconstanta, constCurTrip); + setMemStime(constvaluesettime, constCurTrip); + convertJsonTripToTripStruct(iTrip, hasil.c_str()); + data["ok"]=1; + } + // } + + Serial.println(hasil); + // Serial.print("isi ");Serial.print(filename);Serial.println(readFile(SPIFFS, filename)); + } + // request->send(200, "text/plain", hasil); // handle data and respond + serializeJson(data, *response); + request->send(response); + + // request->send(200, "text/plain", hasil); + isloadingConst=false; +} + + +void handleloadConst(AsyncWebServerRequest *request, JsonVariant &json) { + isloadingConst=true; + // while(iscalculatingRally) { + // yield(); + // } + String constTrip; + String tempTrip; + tempTrip.reserve(100); + String tripload; + + tripload = "{\"alltrip\":"; + tripload+="["; + uint8_t maxI=81; + DynamicJsonDocument doc(256); + float speedinconstanta; + // unsigned long sTimeinconstanta; + String tempSpeed; + tempSpeed.reserve(10); + String tempsTime; + tempsTime.reserve(10); + for(uint8_t i=65; ibeginResponseStream("application/json"); + // DynamicJsonDocument doc(1024); + // deserializeJson(doc, tripload); + // doc["ok"]=1; + // serializeJson(doc, *response); + request->send(200, "text/plain", tripload); // handle data and respond + // request->send(tripload); + isloadingConst=false; + Serial.print("constLoadTime=");Serial.println(millis()-howLongInMillis); + } + +void setup() { +getCalibJson.reserve(512); +getRallyJson.reserve(512); +// +// +// +// +//#ifdef DEBUG + Serial.begin(115200); + Serial.println("Starting Rally"); +//#endif + // pinMode(ledPin, OUTPUT); + pinMode(simulatorPWMPin,OUTPUT); + pinMode(LED_BUILTIN, OUTPUT); + pinMode(interruptPin, INPUT); //Pull down using resistor to ground + attachInterrupt(digitalPinToInterrupt(interruptPin), blink, FALLING); + // attachInterrupt(digitalPinToInterrupt(interruptPin), blink, FALLING); + // attachInterrupt(interruptPin, isr, FALLING); + Wire.begin(I2C_SDA, I2C_SCL); //for lolin32lite sda=15; scl=13 + // pinMode(UP_pin, INPUT_PULLUP); /// + // pinMode(DOWN_pin, INPUT_PULLUP); /// + // pinMode(LEFT_pin, INPUT_PULLUP); /// + // pinMode(RIGHT_pin, INPUT_PULLUP); /// + // pinMode(OK_pin, INPUT_PULLUP); /// + + btnUP.begin(); /// using JC_BUTTON harus ada begin + btnDN.begin(); + btnLF.begin(); + btnRF.begin(); + btnOK.begin(); + btnESC.begin(); + //DS3231_init(DS3231_INTCN); + DS3231_init(DS3231_CONTROL_INTCN); + //memset(recv, 0, BUFF_MAX); +#ifdef DEBUG + Serial.println("GET time"); +#endif +/* +Trip[0].sub = "A"; +Trip[0].speed = 24.275; +Trip[0].startHour = 25; +//Trip[0].distance = 12.898; +Trip[9].sub = "A"; +Trip[9].speed = 90.2751; +Trip[9].startHour = 22; +Trip[9].startMin = 59; +Trip[9].startSec = 58; +*/ +//Trip[9].distance = 12.898; +//Serial.println(Trip[0].sub);Serial.println(Trip[0].speed);Serial.println(Trip[0].startHour);Serial.println(Trip[0].startMin);Serial.println(Trip[0].startSec); +//Serial.println(Trip[0].distance); +//Serial.println(Trip[0].subTime); + + + + //**************************LCD Setup******************************** + + // lcd.begin (20,4); // initialize the lcd + // lcd.init(); + lcd.begin(); + // Switch on the backlight +/// lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE); + lcd.backlight(); +/// lcd.setBacklight(LED_ON); + + //***************************END LCD Setup******************************** +#ifdef DEBUG + Serial.println("Setting time"); +#endif + //char a[]="304022129022016"; + + DS3231_get(&t); //Get time + + blinkON=false; + sec60=t.sec; + min60=t.min; + hour24=t.hour; + + delay(100); // delay for reading mem.read + //mainMenu(); + printUPchar(); + printDOWNchar(); + count1 = memretrieveLong(count1Address, RRcountSIZE, count1Seq); //(int startaddress, byte RRsize, unsigned long seq) + Serial.println(count1Seq); + int countaddresspointer = count1count2diffAddress*32; + Serial.print(countaddresspointer); + count1count2diff = mem.readLong(countaddresspointer); + //count1count2diff = mem.readLong((count1count2diffAddress*32)); + count2 = count1 - count1count2diff; + //printmemLong(0,20); //startaddress, size + Serial.print("count1=");Serial.print(count1);Serial.print(";count2=");Serial.print(count2);Serial.print("countdiff=");Serial.println(count1count2diff); + +//TESTING MEM AT24cx EEPROM check the address in the library #define ..... 0x57 + // Serial.println("Write 42 to address 12"); + // mem.write(12, 42); + // Serial.println("Read byte from address 12 ..."); + // byte b = mem.read(12); + // Serial.print("... read: "); + // Serial.println(b, DEC); + // Serial.println(); + + //count1Seq = 4294967290; +/* + for (int i=0; i<25 ; i++){ + count1Seq++; + //Serial.println(count1Seq); + //memwritingLong(rrcountpointer1, count1Seq, count1+1, RRcountSIZE ); + memwritingLong(count1Address, RRcountSIZE, count1Seq, count1);//(int startaddress, byte RRsize, unsigned long seq, unsigned long Data) + } + */ + //mem.writeLong(896, 110025); to reset CALIBRATION value to CRV + /* + starttracthour=mem.read(770); + starttractmin=mem.read(769); + starttractsec=mem.read(768); + */ +// for (int i = 0; i23) starttracthour = 23; + if (starttractmin>59) starttractmin = 59; + if (starttractsec>59) starttractsec = 59; + //constanta=mem.readFloat(800); + constanta = Trip[curTrip].speed; + if ((constanta > 150) || (constanta < 0)) constanta = 60; /// aslinya if ((constanta > 150) || (constanta < 0)) constanta = 60; + long m = mem.readLong(896); //read calibration value; + if (m > 0) { + Calibration = m; + } else Calibration = 110025; + // Calibration = 100000; + +//#ifdef DEBUG + Serial.println("calibration and constanta"); + Serial.println(m); + Serial.println(Calibration); + Serial.println(constanta); +//#endif + constantatodigit(); + +// Serial.print(digit1);Serial.print(digit2); Serial.print(digit3); Serial.print(digit4);Serial.print(digit5);Serial.println(digit6); +// Serial.println(constanta,5); + //Serial.print(digitalRead(UP_pin));Serial.print(digitalRead(DOWN_pin));Serial.print(digitalRead(LEFT_pin));Serial.print(digitalRead(RIGHT_pin));Serial.println(digitalRead(OK_pin)); + + prevcount1 = count1; + prevcount2 = count2; + + prevcalibrationtime+=calibrationtimeinterval; + prevtempint+=tempinterval; + prevtemprally+=tempintervalrally; + prevsettime += intervalsettime; + startmillis+=1000; + + + mainMenu(); + + +// +// +// +// + + + //Serial.begin(115200); + //DynamicJsonDocument doc(512); + // Initialize SPIFFS + #ifdef ESP32 + if(!SPIFFS.begin(true)){ + Serial.println("An Error has occurred while mounting SPIFFS"); + return; + } + #else + if(!SPIFFS.begin()){ + Serial.println("An Error has occurred while mounting SPIFFS"); + return; + } + #endif + // wifiManager.setAPCallback(configModeCallback); + // wifiManager.autoConnect(soft_ap_ssid); + fillTripArray(); + WiFi.onEvent(OnWiFiEvent); + //WiFi.mode(WIFI_STA); + WiFi.mode(WIFI_MODE_APSTA); + + WiFi.softAP(soft_ap_ssid, soft_ap_password); + + String yourSSIDString = readFile(SPIFFS, "/ssidString.txt"); + Serial.print("*** Your ssidString: "); + Serial.println(yourSSIDString); + Serial.println(ssid); + if (yourSSIDString != ""){ + strncpy(ssid, yourSSIDString.c_str() , (sizeof ssid)-1); + // strncpy(ssid, yourSSIDString.c_str() , (sizeof yourSSIDString)-1); + } + + Serial.println(ssid); + String yourInputPwd = readFile(SPIFFS, "/inputPwd.txt"); + Serial.print("*** Your inputPwd: "); + Serial.println(yourInputPwd); + if (yourInputPwd != ""){ + strncpy(password, yourInputPwd.c_str() , (sizeof password)-1); + // strncpy(password, yourInputPwd.c_str() , (sizeof yourInputPwd)-1); + } +Serial.print("try to connect to ssid:");Serial.print(ssid);Serial.print("; with pwd:");Serial.println(password); + WiFi.begin(ssid, password); + if (WiFi.waitForConnectResult() != WL_CONNECTED) { + Serial.println("WiFi Failed!"); + //return; + } + + Serial.print("ESP32 IP as soft AP: "); + Serial.println(WiFi.softAPIP()); + + Serial.println(); + Serial.print("IP Address: "); + Serial.println(WiFi.localIP()); + +// //settingup MDNS +// if(!MDNS.begin("esp32")) { +// Serial.println("Error starting mDNS"); +// return; +// } +// Serial.println(“MDNS started.”); +// MDNS.addService(“http”, “tcp”, 80); +// // Init and get the time + configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); + printLocalTime(); + + // Send web page with input fields to client + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ + if (ON_STA_FILTER(request)) { + //request->send(200, "text/plain", "Hello from STA"); + request->send_P(200, "text/html", main_menu, processor); + return; + + } else if (ON_AP_FILTER(request)) { + //request->send(200, "text/plain", "Hello from AP"); + Serial.println("on apfilter /"); + request->send_P(200, "text/html", wifi_html, processor); + return; + } + + }); + + server.on("/wifi", HTTP_GET, [](AsyncWebServerRequest * request) { + + if (ON_STA_FILTER(request)) { + //request->send(200, "text/plain", "Hello from STA"); + request->send_P(200, "text/html", wifi_html, processor); + return; + + } else if (ON_AP_FILTER(request)) { + //request->send(200, "text/plain", "Hello from AP"); + Serial.println("on apfilter /wifi"); + request->send_P(200, "text/html", wifi_html, processor); + return; + } + + request->send(200, "text/plain", "Hello from undefined"); +}); + + + + // Send a GET request to /get?inputString= + server.on("/setwifi", HTTP_POST, [] (AsyncWebServerRequest *request) { + String inputMessage; + boolean bolrestart=false; + boolean POST=true; + Serial.println("ini masuk /setwifi"); + // GET inputString value on /get?inputString= + if (request->hasParam(PARAM_SSID, POST)) { + inputMessage = request->getParam(PARAM_SSID, POST )->value(); + if (inputMessage!=""){ + writeFile(SPIFFS, "/ssidString.txt", inputMessage.c_str()); + delay(50); + bolrestart=true; + //ESP.restart(); + } + } + // GET inputPwd value on /wifi/get?inputPwd= + if (request->hasParam(PARAM_PWD, POST)) { + inputMessage = request->getParam(PARAM_PWD, POST)->value(); + if (inputMessage!=""){ + writeFile(SPIFFS, "/inputPwd.txt", inputMessage.c_str()); + delay(50); + bolrestart=true; + //ESP.restart(); + } + } + else { + inputMessage = "No message sent"; + } + if (bolrestart) { + ESP.restart(); + } + Serial.println("ini /setwifi aja");Serial.println(inputMessage); + request->send(200, "text/text", inputMessage); + }); + + // // Send a GET request to /wifi/get?ssidString= + // server.on("/wifi/get", HTTP_GET, [] (AsyncWebServerRequest *request) { + // String inputMessage; + // // GET ssidString value on /wifi/get?ssidString= + // Serial.println("ini masuk wifi get"); + // Serial.println(request->params()); + // if (request->hasParam(PARAM_SSID)) { + // inputMessage = request->getParam(PARAM_SSID)->value(); + // writeFile(SPIFFS, "/ssidString.txt", inputMessage.c_str()); + // delay(100); + // ESP.restart(); + // } + // // GET inputPwd value on /wifi/get?inputPwd= + // else if (request->hasParam(PARAM_PWD)) { + // inputMessage = request->getParam(PARAM_PWD)->value(); + // writeFile(SPIFFS, "/inputPwd.txt", inputMessage.c_str()); + // delay(100); + // ESP.restart(); + // } + // else { + // inputMessage = "No message sent"; + // } + // Serial.println("/wifi/get value:"); Serial.println(inputMessage); + // request->send(200, "text/text", inputMessage); + // }); + + server.on("/menu", HTTP_GET, [] (AsyncWebServerRequest *request) { + //String s = MAIN_page; //Read HTML contents + //request->send_P(200, "text/html", s); //Send web page + request->send_P(200, "text/html", main_menu); + }); + + server.on("/startrally", HTTP_GET, [] (AsyncWebServerRequest *request) { + //String s = MAIN_page; //Read HTML contents + //request->send_P(200, "text/html", s); //Send web page + String PAGE; + PAGE += FPSTR(HTML_PAGEHEADER); + PAGE.replace("%serveripaddress%", WiFi.localIP().toString()); + PAGE += FPSTR(HTML_DIVSTARTRALLY); + //PAGE += FPSTR(HTML_SCRIPTSETINTERVAL); + //PAGE += FPSTR(HTML_SCRIPTGETDATA); + PAGE += FPSTR(HTML_END); + //Serial.println(PAGE); + Serial.print("PAGE Size:"); + Serial.println(PAGE.length()); + request->send(200, "text/html", PAGE); + }); + + server.on("/startrally1", HTTP_GET, [] (AsyncWebServerRequest *request) { + request->send_P(200, "text/html", HTML_startrally1, processor); + }); + + server.on("/resetodo1", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("ODORESET 1"); + request->redirect("/startrally1"); + }); + + server.on("/resetodo2", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("ODORESET 22222"); + request->redirect("/startrally1"); + }); + + server.on("/copytoodo2", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("COPY ODO 1 to 2"); + request->redirect("/startrally1"); + }); + + server.on("/copytoodo1", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("COPY ODO 2 to 1"); + request->redirect("/startrally1"); + }); + server.on("/DIR", HTTP_GET, [] (AsyncWebServerRequest *request) { + String inputMessage; + String inputParam; + if (request->hasParam("DIR1")){ + inputMessage=request->getParam("DIR1")->value(); + Serial.print("DIR 1->");Serial.println(inputMessage); + switch(inputMessage[0]){ + case 'F': + Serial.println("FW1"); + break; + case 'S': + Serial.println("ST1"); + break; + case 'B': + Serial.println("BACK1"); + break; + default: + Serial.println("Default VAL1"); + } + } + else if (request->hasParam("DIR2")){ + inputMessage=request->getParam("DIR2")->value(); + Serial.print("DIR 2->");Serial.println(inputMessage); + switch(inputMessage[0]){ + case 'F': + Serial.println("FW2"); + break; + case 'S': + Serial.println("ST2"); + break; + case 'B': + Serial.println("BACK2"); + break; + default: + Serial.println("Default VAL2"); + } + } + request->redirect("/startrally1"); + }); + + + server.on("/TG1", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("TOGGLE 1"); + request->redirect("/startrally1"); + }); + + server.on("/TG2", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("TOGGLE 2"); + request->redirect("/startrally1"); + }); +// //server.on("/adc", HTTP_GET); //This is display page +// server.on("/readADC", HTTP_GET, [] (AsyncWebServerRequest *request) { +// // int a = analogRead(A0); +// // String adcValue = String(millis()); +// String adcValue = getPin(); +// Serial.println(adcValue); +// request->send_P(200, "text/plain", adcValue.c_str()); //Send ADC value only to client ajax request +// }); + + server.on("/calibration", HTTP_GET, [] (AsyncWebServerRequest *request) { + int params = request->params(); //showing all params + for(int i=0;igetParam(i); + if(p->isFile()){ //p->isPost() is also true + Serial.printf("FILE[%s]: %s, size: %u\n", p->name().c_str(), p->value().c_str(), p->size()); + } else if(p->isPost()){ + Serial.printf("POST[%s]: %s\n", p->name().c_str(), p->value().c_str()); + } else { + Serial.printf("GET[%s]: %s\n", p->name().c_str(), p->value().c_str()); + } + } + //PAGE.replace("%serveripaddress%", WiFi.localIP().toString()); + request->send_P(200, "text/html", HTML_CALIBRATION, processor); + }); + server.on("/constanta", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("start /const"); + for (uint8_t i=0; i(); + + }); + server.addHandler(setconst); + server.addHandler(loadconst); + +Serial.println("before onevent"); + ws.onEvent(onWsEvent); //add ws event + wscal.onEvent(onWsEvent2); //add ws event + server.addHandler(&ws); + server.addHandler(&wscal); +Serial.println("after onevent"); + server.onNotFound(notFound); + Serial.println("onnotfound"); + + server.begin(); + Serial.println("server begin"); +} + +unsigned long testLoadTime; + +void loop() //loop from VSS RALLY V2 +{ +#ifdef DEBUG + prevtimemicros = micros(); +#endif +// #ifndef ATMEGA328 + //digitalWrite(ledPin, ledstate); + digitalWrite(LED_BUILTIN, ledstate); +// #endif + +// Serial.print("start loop; "); + char tempF[6]; + unsigned long now1 = millis(); + + btnUP.read(); //read the buttons + btnDN.read(); + btnLF.read(); //read the buttons + btnRF.read(); + btnOK.read(); + btnESC.read(); +// Serial.print("read button; "); + if (millis()-rallyEditTime >1500) rallyEditRpt = 0; + switch (STATE) { + case WAIT: //wait for a button event + if (btnUP.wasPressed()) + STATE = UP; + else if (btnDN.wasPressed()) + STATE = DOWN; + else if (btnLF.wasPressed()) + STATE = LEFT; + else if (btnRF.wasPressed()) + STATE = RIGHT; + else if (btnUP.wasReleased()) //reset the long press interval + rpt = REPEAT_FIRST; + else if (btnDN.wasReleased()) + rpt = REPEAT_FIRST; + else if (btnLF.wasReleased()) //reset the long press interval + rpt = REPEAT_FIRST; + else if (btnRF.wasReleased()) + rpt = REPEAT_FIRST; + else if (btnUP.pressedFor(rpt)) { //check for long press + rpt += REPEAT_INCR; //increment the long press interval + STATE = UP; + } + else if (btnDN.pressedFor(rpt)) { + rpt += REPEAT_INCR; + STATE = DOWN; + } + else if (btnLF.pressedFor(rpt)) { //check for long press + rpt += REPEAT_INCR; //increment the long press interval + STATE = LEFT; + } + else if (btnRF.pressedFor(1000)) { + rpt += REPEAT_INCR; + STATE = RIGHT; + } + else if (btnOK.wasPressed() && (MENU != RALLY)) { + STATE = OKAY; + } + else if (btnOK.wasPressed() && (CURSOR_POS > 4)) { + STATE = OKAY; + } + else if (btnOK.wasPressed() && (CURSOR_POS <= 2)) { + //STATE = OKAY; + if (!rallyEditRpt) { + rallyEditTime = millis(); + rallyEditRpt++; + //Serial.println("!rallyEditRpt"); + //Serial.println(rallyEditRpt); + } + else if (millis()-rallyEditTime > 1500) { + rallyEditRpt = 0; + //Serial.println("rallyEditRpt = 0"); + //Serial.println(rallyEditRpt); + } + else if (rallyEditRpt == 2) { + //Serial.println("rallyEditRpt = ");Serial.println(rallyEditRpt); + STATE = RALLYEDIT; + rallyEditRpt = 0; + } + else { + rallyEditRpt++; + //Serial.println("rallyEditRpt++"); + //Serial.println(rallyEditRpt); + } + } + else if (btnOK.pressedFor(rpt) && (CURSOR_POS <= 4)) { + STATE = OKAY; + } + else if (btnESC.wasPressed()){ + STATE = ESC; + //Serial.println("ESC pressed"); + } + break; + + case DOWN: //increment the counter + switch (MENU) { + case MAIN: + y = min(y+1, MAX_ROW); //but not more than the specified maximum + break; + + case RALLY: + if (blinkON) { + if (y == 1) { + if (x == 0 || x == 1) { + dist1digit1 = max(dist1digit1-1, 0); + lcd.setCursor(0,y); + if (dist1digit1 <10) lcd.print("0"); + lcd.print(dist1digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist1digit2 = max(dist1digit2-1, 0); + lcd.setCursor(3,y); + if (dist1digit2 <10) { + lcd.print("00"); + }else if (dist1digit2 <100) lcd.print("0"); + lcd.print(dist1digit2); + } + } + else if (y ==3) { + if (x == 0 || x == 1) { + dist2digit1 = max(dist2digit1-1, 0); + lcd.setCursor(0,y); + if (dist2digit1 <10) lcd.print("0"); + lcd.print(dist2digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist2digit2 = max(dist2digit2-1, 0); + lcd.setCursor(3,y); + if (dist2digit2 <10) { + lcd.print("00"); + }else if (dist2digit2 <100) lcd.print("0"); + lcd.print(dist2digit2); + } + + } + + } + else { + CURSOR_POS=min(CURSOR_POS+1,10); + set_cursor_pos(CURSOR_POS); + } + + break; + + case CALIBRATION: + if (!blinkON) y = min(y+1, MAX_ROW ); //but not more than the specified maximum + else if (blinkON && y==1) { + //calibrationDistance=max(calibrationDistance-1, 1); + tempcalibdist=max(tempcalibdist-1, 1); + lcd.print(tempcalibdist); + } + else if (blinkON && y==3 && (x==18||x==19)) { + calibdigit3 = max(calibdigit3-1,0); + lcd.setCursor(18,3); + if (calibdigit3<10) lcd.print("0"); + lcd.print(calibdigit3); + } + else if (blinkON && y==3 && (x==16||x==17)) { + calibdigit2 = max(calibdigit2-1,0); + lcd.setCursor(16,3); + if (calibdigit2<10) lcd.print("0"); + lcd.print(calibdigit2); + } + else if (blinkON && y==3 && (x==14||x==15)) { + calibdigit1 = max(calibdigit1-1,0); + lcd.setCursor(14,3); + if (calibdigit1<10) lcd.print("0"); + lcd.print(calibdigit1); + } + break; + + case CONSTANTA: + if (!blinkON) { + y = min(y+1, 3); //but not less than the specified minimum + if (y==1) x=15; + } + else if (y==1) { + prevTrip = min(prevTrip+1,TRIPSIZE-1); + //curTrip = min(curTrip+1,TRIPSIZE-1); + lcd.setCursor(14,y); + lcd.print(Trip[prevTrip].sub); + } + else if (x==13 && y==2) { + digit1 = max(digit1-1, MIN_COUNT); + lcd.print(digit1); + } + else if (x==14 && y==2) { + digit2 = max(digit2-1, MIN_COUNT); + lcd.print(digit2); + } + else if (x==16 && y==2) { + digit3 = max(digit3-1, MIN_COUNT); + lcd.print(digit3); + } + else if (x==17 && y==2) { + digit4 = max(digit4-1, MIN_COUNT); + lcd.print(digit4); + } + else if (x==18 && y==2) { + digit5 = max(digit5-1, MIN_COUNT); + lcd.print(digit5); + } + else if (x==19 && y==2) { + digit6 = max(digit6-1, MIN_COUNT); + lcd.print(digit6); + } + else if ((x==12 || x==13) && y==3) { //******SET CONSTANTA TIME ******* + hour24=max(hour24-1, MIN_COUNT); + lcd.setCursor(12,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==15 || x==16) && y==3) { + min60=max(min60-1, MIN_COUNT); + lcd.setCursor(15,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==18 || x==19) && y==3) { + sec60=max(sec60-1, MIN_COUNT); + lcd.setCursor(18,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + + case SETTIME: + if (!blinkON) { + y = min(y+1, MAX_ROW); //but not more than the specified maximum + lcd.setCursor(x,y); + } + else if ((x==0 || x==1) && y==3) { + hour24=max(hour24-1, MIN_COUNT); + lcd.setCursor(0,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==3 || x==4) && y==3) { + min60=max(min60-1, MIN_COUNT); + lcd.setCursor(3,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==6 || x==7) && y==3) { + sec60=max(sec60-1, MIN_COUNT); + lcd.setCursor(6,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case UP: //decrement the counter + switch(MENU) { + case MAIN: + y = max(y-1, MIN_COUNT); //but not less than the specified minimum + break; + + case CALIBRATION: + if (!blinkON) { + y = max(y-1, MIN_COUNT); //but not less than the specified minimum + x = 18; + } + else if (blinkON && y==1) { + //calibrationDistance=min(calibrationDistance+1, 9); + tempcalibdist=min(tempcalibdist+1, 9); + lcd.print(tempcalibdist); + } + else if (blinkON && y==3 && (x==18||x==19)) { + calibdigit3 = min(calibdigit3+1,99); + lcd.setCursor(18,3); + if (calibdigit3<10) lcd.print("0"); + lcd.print(calibdigit3); + } + else if (blinkON && y==3 && (x==16||x==17)) { + calibdigit2 = min(calibdigit2+1,99); + lcd.setCursor(16,3); + if (calibdigit2<10) lcd.print("0"); + lcd.print(calibdigit2); + } + else if (blinkON && y==3 && (x==14||x==15)) { + calibdigit1 = min(calibdigit1+1,50); + lcd.setCursor(14,3); + if (calibdigit1<10) lcd.print("0"); + lcd.print(calibdigit1); + } + break; + + case RALLY: + if (blinkON) { + if (y == 1) { + if (x == 0 || x == 1) { + dist1digit1 = min(dist1digit1+1, 999); + lcd.setCursor(0,y); + if (dist1digit1 <10) lcd.print("0"); + lcd.print(dist1digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist1digit2 = min(dist1digit2+1, 999); + lcd.setCursor(3,y); + if (dist1digit2 <10) { + lcd.print("00"); + }else if (dist1digit2 <100) lcd.print("0"); + lcd.print(dist1digit2); + } + } + else if (y == 3) { + if (x == 0 || x == 1) { + dist2digit1 = min(dist2digit1+1, 99); + lcd.setCursor(0,y); + if (dist2digit1 <10) lcd.print("0"); + lcd.print(dist2digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist2digit2 = min(dist2digit2+1, 999); + lcd.setCursor(3,y); + if (dist2digit2 <10) { + lcd.print("00"); + }else if (dist2digit2 <100) lcd.print("0"); + lcd.print(dist2digit2); + } + } + + } + else { + CURSOR_POS=max(CURSOR_POS-1,1); + set_cursor_pos(CURSOR_POS); + } + break; + + case CONSTANTA: + if (!blinkON) { + y = max(y-1, MIN_COUNT); //but not less than the specified minimum + if (y==0) x=16; + else if (y==1) x=15; + } + else if (y==1) { + prevTrip = max(prevTrip-1, MIN_COUNT); + //curTrip = max(curTrip-1, MIN_COUNT); + lcd.setCursor(14,y); + lcd.print(Trip[prevTrip].sub); + } + else if (x==13 && y==2) { + digit1=min(digit1+1, 9); + lcd.print(digit1); + } + else if (x==14 && y==2) { + digit2=min(digit2+1, 9); + lcd.print(digit2); + } + else if (x==16 && y==2) { + digit3=min(digit3+1, 9); + lcd.print(digit3); + } + else if (x==17 && y==2) { + digit4=min(digit4+1, 9); + lcd.print(digit4); + } + else if (x==18 && y==2) { + digit5=min(digit5+1, 9); + lcd.print(digit5); + } + else if (x==19 && y==2) { + digit6=min(digit6+1, 9); + lcd.print(digit6); + } + else if ((x==12 || x==13) && y==3) { //******SET CONSTANTA TIME ******* + hour24=min(hour24+1, 23); + lcd.setCursor(12,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==15 || x==16) && y==3) { + min60=min(min60+1, 59); + lcd.setCursor(15,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==18 || x==19) && y==3) { + sec60=min(sec60+1, 59); + lcd.setCursor(18,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + + case SETTIME: + if (!blinkON) { + y = max(y-1, MIN_COUNT); //but not less than the specified minimum + //Serial.print(x); Serial.print(","); Serial.println(y); + //lcd.setCursor(x,y); + } + else if ((x==0 || x==1) && y==3) { + hour24=min(hour24+1, 23); + lcd.setCursor(0,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==3 || x==4) && y==3) { + min60=min(min60+1, 59); + lcd.setCursor(3,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==6 || x==7) && y==3) { + sec60=min(sec60+1, 59); + lcd.setCursor(6,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case RIGHT: //increment the counter + switch (MENU) { + case SETTIME: + x = min(x+1, MAX_COL); //MAX_COUNT); //but not more than the specified maximum + //STATE = WAIT; + //Serial.print(x); Serial.print(","); Serial.println(y); + //lcd.setCursor(x,y); + break; + + case RALLY: + if (blinkON) { + + x = min(x+1, 5); + //Serial.println(x); + } + else if (CURSOR_POS % 2 ==0) CURSOR_POS=min(CURSOR_POS+2,10); + else CURSOR_POS=min(CURSOR_POS+2,9); + if (!blinkON) set_cursor_pos(CURSOR_POS); + break; + + case CONSTANTA: + if (y==2 || y==3) { + x = min(x+1, MAX_COL); //MAX_COUNT); + } + break; + + case CALIBRATION: + if (y==3) { + x = min(x+1,MAX_COL); + } + else x = 18; + break; + + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case LEFT: //decrement the counter + switch (MENU) { + case SETTIME: + x = max(x-1, MIN_COUNT); //but not less than the specified minimum + //STATE = WAIT; + //Serial.print(x); Serial.print(","); Serial.println(y); + //lcd.setCursor(x,y); + break; + + case RALLY: + if (blinkON) { + x = max(x-1, MIN_COUNT); + } + else if (CURSOR_POS % 2 == 0) CURSOR_POS=max(CURSOR_POS-2,2); + else CURSOR_POS=max(CURSOR_POS-2,1); + if (!blinkON) set_cursor_pos(CURSOR_POS); + break; + + case CONSTANTA: + if (y==2 || y==3){ + x = max(x-1, 12); + } + break; + + case CALIBRATION: + if (y==3) { + x = max(x-1, 14); + } + else x = 18; + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case OKAY: + switch (MENU) { + case MAIN: + if (y==1) { + MENU = SETTIME; + //prevsettime += millis(); + //prevtempint+=millis(); + } + else if (y==0) { + MENU = RALLY; + //prevtemprally=millis(); + } + else if (y==2) MENU = CONSTANTA; + else if (y==3) { + MENU = CALIBRATION; + //prevcalibrationtime+=millis(); + } + break; + + case CONSTANTA: + if (y==0) MENU = MAIN; + //else if (!blinkON && y==1) { + + // } + else if (!blinkON && y==2) { + constantatodigit(); + lcd.blink(); + blinkON=!blinkON; + } + else if (!blinkON && y==3) { + sec60 = starttractsec; + min60 = starttractmin; + hour24 = starttracthour; + lcd.blink(); + blinkON=!blinkON; + } + else if (!blinkON && y==1) { + prevTrip = curTrip; + lcd.blink(); + blinkON = !blinkON; + } + else if (blinkON && y==1) { + curTrip = prevTrip; + constanta = Trip[curTrip].speed; + starttractsec = Trip[curTrip].startSec; + starttractmin = Trip[curTrip].startMin; + starttracthour = Trip[curTrip].startHour; + lcd.noBlink(); + blinkON=!blinkON; + constantaMenu(); + } + else if (blinkON && y==2) { + lcd.noBlink(); + blinkON=!blinkON; + constanta = (digit1*10)+digit2+(float)digit3/10+(float)digit4/100+(float)digit5/1000+(float)digit6/10000; //+(float)digit6/100000; + //mem.writeFloat(800, constanta); + + setMemSpeedInConstanta(constanta, curTrip); + // int pointeradd = ((TRIPADDRESS+curTrip)*32); + // mem.writeFloat(pointeradd, constanta); + // Trip[curTrip].speed = constanta; +#ifdef DEBUG + Serial.println(pointeradd); Serial.print(";");Serial.println(constanta,5); +#endif + } + else if (blinkON && y==3) { + starttractsec=sec60; + starttractmin=min60; + starttracthour=hour24; + unsigned long valuesettime = starttracthour; + valuesettime = valuesettime * 256 + starttractmin; // effectively shift the first byte 8 bit positions + valuesettime = valuesettime * 256 + starttractsec; + //mem.writeLong(768,valuesettime); + + setMemStime(valuesettime, curTrip); ///added for esp32 + // int pointeradd = ((TRIPADDRESS+curTrip)*32+4); + // mem.writeLong(pointeradd, valuesettime); + // Trip[curTrip].startHour = starttracthour; + // Trip[curTrip].startMin = starttractmin; + // Trip[curTrip].startSec = starttractsec; + lcd.noBlink(); + blinkON=!blinkON; +#ifdef DEBUG + Serial.println(pointeradd); Serial.println(valuesettime); +#endif + } + else {// if (y==3) { + lcd.blink(); + blinkON=!blinkON; + } + break; + + case RALLY: +#ifdef DEBUG + Serial.println("OKRALLY"); +#endif + switch(CURSOR_POS) + { + case 1: + count1 = 0; + backcount1 = 0; + time1 = VSSCount; + //Serial.println("case 1"); + break; + case 2: + count2 = 0; + backcount2 = 0; + time2 = VSSCount; + //Serial.println("case 2"); + break; + case 3: + count2 = count1; //no yet UNDO next update can UNDO + backcount2 = 0; + //time2 = VSSCount; + //Serial.println("case 3"); + break; + case 4: + count1 = count2; //no yet UNDO next update can UNDO + backcount1 = 0; + //time1 = VSSCount; + //Serial.println("case 4"); + break; + case 5: + //dirfwdcount1 = !dirfwdcount1; + switch (dircount1) + { + case FORWARD: + dircount1 = FREEZE; + break; + case FREEZE: + dircount1 = BACKWARD; + break; + case BACKWARD: + dircount1 = FORWARD; + break; + default: + dircount1 = FORWARD; + break; + } + secondrallyMenu(); + //Serial.println("case 5"); + break; + case 6: + //dirfwdcount2 = !dirfwdcount2; + switch (dircount2) + { + case FORWARD: + dircount2 = FREEZE; + break; + case FREEZE: + dircount2 = BACKWARD; + break; + case BACKWARD: + dircount2 = FORWARD; + break; + default: + dircount2 = FORWARD; + break; + } + secondrallyMenu(); + //Serial.println("case 6"); + break; + case 7: + showTIME = !showTIME; + rallyMenu(); + break; + case 8: + showTIME = !showTIME; + rallyMenu(); + break; + case 9: + //Serial.println("case 9"); + MENU = MAIN; + lcd.noBlink(); + break; + case 10: + //Serial.println("case 10"); + MENU = MAIN; + lcd.noBlink(); + break; + + } + break; + + case CALIBRATION: + if (blinkON && y==1) { + lcd.noBlink(); + blinkON=!blinkON; + calibrationDistance = tempcalibdist; + } + else if (!blinkON && y==1) { + lcd.blink(); + blinkON=!blinkON; + tempcalibdist = calibrationDistance; + } + else if (!blinkON && y==2) { + //startCalibration = millis(); + Calibrationcount = 0; + startCalibration = VSSCount; + Calibrationtime = startCalibration; + blinkON=!blinkON; + lcd.blink(); + calibrationON=true; + lcd.setCursor(0,2); + lcd.print("Calibrating 00.000Km"); + } + else if (blinkON && y==2) { + Calibration = (VSSCount-startCalibration)/(float)calibrationDistance; + mem.writeLong(896, Calibration); //Save Calibration to memory + oneMeter=(millis()-startCalibration)/(1000*(float)calibrationDistance);//*calibrationDistance); + oneMeter=((float)VSSCount-startCalibration)/(1000*(float)calibrationDistance);//*calibrationDistance); + oneMeter=(float)(Calibration)/1000*(float)calibrationDistance; + blinkON=!blinkON; + lcd.noBlink(); + calibrationON=false; + lcd.setCursor(0,2); + lcd.print("Start "); + lcd.setCursor(0,3); + lcd.print("1m="); + //Serial.print(startCalibration);Serial.print(";");Serial.print((millis()-startCalibration)/1000);Serial.print(";"); +#ifdef DEBUG + Serial.println(oneMeter,5); +#endif + lcd.print(oneMeter,3); + lcd.print(";"); + } + else if (!blinkON && y==3) { //not yet implemented + lcd.blink(); + blinkON=!blinkON; + calibdigit1 = (byte)(Calibration/10000); + calibdigit2 = (byte)((Calibration % 10000)/100); + calibdigit3 = Calibration % 100; + //Serial.println(calibdigit1);Serial.println(calibdigit2);Serial.println(calibdigit3); + } + else if (blinkON && y==3) { + lcd.noBlink(); + blinkON=!blinkON; + //Serial.println(calibdigit1);Serial.println(calibdigit2);Serial.println(calibdigit3); + Calibration = ((long)calibdigit1*10000) + ((long)calibdigit2*100) + (calibdigit3); + //Serial.println(Calibration); + mem.writeLong(896, Calibration); + } + else if (y==0) MENU = MAIN; + break; + + case SETTIME: + if (blinkON && y==3) { + t.sec=sec60; + t.min=min60; + t.hour=hour24; + DS3231_set(t); + lcd.noBlink(); + blinkON=!blinkON; + //Serial.println("OKAY"); + } + else if (y==3) { + lcd.blink(); + blinkON=!blinkON; + } + else {//(blinkON) { + MENU = MAIN; + lcd.noBlink(); + } + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case RALLYEDIT: + if ((CURSOR_POS == 1 || CURSOR_POS == 2) && !blinkON) { + rallyEdit = true; + blinkON = true; + lcd.blink(); + //if (distance<100) { + dist1digit1=((int)distance1%1000); + dist1digit2=(int)((distance1 - (int)distance1)*1000); + dist2digit1=((int)distance2%1000); + dist2digit2=(int)((distance2 - (int)distance2)*1000); + //} + /* + Serial.print(dist1digit1);Serial.println(dist1digit2); //Serial.print(dist1digit3); Serial.print(dist1digit4);Serial.println(dist1digit5);//Serial.println(digit6); + Serial.println(distance1,3); + Serial.print(dist2digit1);Serial.println(dist2digit2); //Serial.print(dist1digit3); Serial.print(dist1digit4);Serial.println(dist1digit5);//Serial.println(digit6); + Serial.println(distance2,3); + */ + } + else if (blinkON) { //set the new distance to count + blinkON = false; + rallyEdit = false; + /* + Serial.println(count1); + Serial.println(distance1,5); + Serial.println(""); + */ + if (CURSOR_POS == 1) { + distance1 = dist1digit1 + (float)dist1digit2/1000; + count1 = (unsigned long)(distance1 * Calibration) + 5; + //distance1 = (float)count1/((float)Calibration); + }else if (CURSOR_POS == 2) { + distance2 = dist2digit1 + (float)dist2digit2/1000; + count2 = (unsigned long)(distance2 * Calibration) + 5; + //distance2 = (float)count2/((float)Calibration); + } + /* + Serial.println(count1); + Serial.println(distance1,3); + */ + set_cursor_pos(CURSOR_POS); + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case ESC: + switch (MENU) + { + case RALLY: + lcd.noBlink(); + MENU=MAIN; + if (rallyEdit) { + rallyEdit = false; + lcd.blink(); + MENU = RALLY; + set_cursor_pos(CURSOR_POS); + } + blinkON=false; + + break; + case SETTIME: + lcd.noBlink(); + if (!blinkON) MENU = MAIN; + blinkON=false; + //MENU=MAIN; + break; + case CONSTANTA: + //MENU=MAIN; + if (!blinkON) MENU = MAIN; + else constantaMenu(); + lcd.noBlink(); + blinkON=false; + break; + case CALIBRATION: + lcd.noBlink(); + if (!blinkON) MENU = MAIN; + blinkON=false; + calibrationON=false; + //MENU=MAIN; + break; + + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + } + +//***************************************************************** +//*************************************** M E N U ***************** +// +// +// +//*************************************** M E N U ***************** +//***************************************************************** + + if (PREVMENU!=MENU) + { + switch (MENU) + { + case (MAIN): + mainMenu(); + break; + + case (RALLY): + lcd.clear(); + rallyMenu(); + rallyON=true; + //lcd.blink(); + CURSOR_POS=10; + set_cursor_pos(CURSOR_POS); + break; + + case (SETTIME): + lcd.clear(); + settimeMenu(); + sec60=t.sec; + min60=t.min; + hour24=t.hour; + lcd.setCursor(0,3); + lcdprint2digit(hour24); + lcd.print(":"); + lcdprint2digit(min60); + lcd.print(":"); + lcdprint2digit(sec60); + x=0; + y=2; + lcd.setCursor(x,y); + break; + + case (CALIBRATION): + calibrationMenu(); + break; + + case CONSTANTA: + sec60=starttractsec; + min60=starttractmin; + hour24=starttracthour; + x = 16; + y = 0; + constantaMenu(); + break; + + case (INPUTSUBTRAYEK): + break; + } + } + + if (MENU==RALLY) { + if (((now1 - prevtemprally) >= tempintervalrally) && !isloadingConst) { + //if ((long)(now1 - prevtemprally) >= 0) { + // testLoadTime=millis(); + //rallyMenu(); + if (!rallyEdit) { + iscalculatingRally=true; + redrawrallyMenu(); //Distance is edited? + iscalculatingRally=false; + } + // Serial.println(millis()-testLoadTime); + prevtemprally=now1; + //prevtemprally+=tempintervalrally; + } + } + + if (MENU==SETTIME) { + //if ((long)(now1 - prevtempint) >=0 ){ + if ((now1 - prevtempint) >=tempinterval ){ + temperature = DS3231_get_treg(); //Get temperature + dtostrf(temperature, 5, 1, tempF); + lcd.setCursor(9,1); + lcd.print(tempF); + lcd.print((char)223); + lcd.print("C "); + //prevtempint+=tempinterval; + prevtempint=now1; + lcd.setCursor(x,y); + //lcd.setCursor(15,0); + //lcd.print(now); + } + //if ((long)(now1- prevsettime) >=0 ){ //show SET TIME MENU + if ((now1 - prevsettime) >=intervalsettime ){ //show SET TIME MENU + DS3231_get(&t); //Get time + if (prevsec!=t.sec) { //will update the LCD every sec(as long as the t.sec is different) eventhough intervalseetime is 250ms + settimeMenu(); + prevsettime = now1; + //prevsettime += intervalsettime; + } + } + } + + if (MENU==CALIBRATION) { + if (calibrationON) { + if ((now1 - prevcalibrationtime) >= calibrationtimeinterval ) { + //if ((long)(now1 - prevcalibrationtime) >=0 ) { + redrawcalibrationMenu(); + char Calibrationstr[6]; + unsigned long calibtemp = VSSCount - startCalibration; + sprintf(Calibrationstr, "%06lu", calibtemp); + lcd.setCursor(14,3); + lcd.print(Calibrationstr); + lcd.setCursor(x,y); + prevcalibrationtime=now1; + //prevcalibrationtime+=calibrationtimeinterval; + } + } + } + + //if (((long)(millis()-startmillis)>=0) && MENU!=CALIBRATION) { + if ((now1-startmillis)>=500) { //&& MENU!=CALIBRATION && MENU!=MAIN) { + unsigned long VSSCountDiff = VSSCount - startVSSCount; + startVSSCount=VSSCount; + if ((VSSCountDiff == 0) && savedCount) { + intervalsavemillis = 4000000; + } + else if ((VSSCountDiff == 0) && !savedCount) { + saveCount(); + savedCount = !savedCount; + intervalsavemillis = 2000000; + } + else if (VSSCountDiff < 15) intervalsavemillis = 3000; + else if (VSSCountDiff < 70) intervalsavemillis = 60000; + else intervalsavemillis = 4000000; + if (VSSCountDiff > 0) savedCount = false; + if (MENU!=CALIBRATION && MENU!=MAIN && MENU!=CONSTANTA) { + lcd.setCursor(0,0); + if (VSSCountDiff==0) lcd.print("0"); + else if (VSSCountDiff <= 10) lcd.print("1"); + else if (VSSCountDiff <= 50) lcd.print("2"); + else if (VSSCountDiff <= 150) lcd.print("3"); + else if (VSSCountDiff <= 250) lcd.print("4"); + else if (VSSCountDiff <= 400) lcd.print("5"); + else if (VSSCountDiff <= 600) lcd.print("6"); + else if (VSSCountDiff <= 900) lcd.print("7"); + else if (VSSCountDiff <= 1200) lcd.print("8"); + else if (VSSCountDiff > 1200) lcd.print("9"); + + //lcd.print(VSSCountDiff); + //lcd.print(" "); + lcd.setCursor(x,y); + } + //startmillis+=400; + startmillis=now1; + + } + +/* + if (((millis() % 100)==0) && MENU!=CALIBRATION) { + lcd.setCursor(0,2); + lcd.print(VSSCount); + lcd.print(" "); + lcd.setCursor(x,y); + } +*/ + if ((millis()-updatecounttime)>=250) { + // if ((millis()-updatecounttime)>=250) { + updateCount(); + updatecounttime = millis(); + digitalWrite(simulatorPWMPin, !simstate); + simstate = !simstate; + // Serial.print(ledstate); Serial.print(";");Serial.println(simstate); + } + + if ((millis()-startsavemillis) > intervalsavemillis) { + saveCount(); + //startsavemillis += 3000; + startsavemillis = millis(); + } + + if ((millis()-broadcastwebsocket) > 333 && !isloadingConst && globalClientRally) { + broadcastwebsocket = millis(); + iscalculatingRally=true; + calculationRally(); + iscalculatingRally=false; + // Serial.println(getRallyJson); + // Serial.println(millis()-broadcastwebsocket); + ws.textAll(getRallyJson); + // char pingPong[] = "{\"ping\":1}"; + // ws.textAll(pingPong); + } + + if ((millis()-broadcastwebsocketcalib) > 499 && !isloadingConst && globalClientCalib) { + broadcastwebsocketcalib = millis(); + //calculationRally(); + redrawcalibrationMenuForESP32(); + // Serial.println(getCalibJson); + + wscal.textAll(getCalibJson); + + + // Serial.print("VSSCount="); Serial.println(VSSCount); + // Serial.print(ledstate); Serial.print(";");Serial.println(simstate); + } + if(!isloadingConst){ + for (int i=(REQUESTCOUNT-1); i>=0; i--){ + // for (int i=0; i + Rally TerraTrip v1 + + + + + + +)rawliteral"; + +const char HTML_STYLECARD[] PROGMEM = R"rawliteral( +)rawliteral"; + +const char HTML_DIVSTARTRALLY[] PROGMEM = R"rawliteral( +
+
+

12345

+

TRACK A

+

Time: 00:00:00

+

123.4Km/h

+
+
+ +
+
OD 1->
+

123.4567 km

+
+

DIRECT

+

00:00:00

+
+
+

+ +

+
+

+ + +

+
+

+
+ +

+
+
+
+ +
+

OD 2->123.456 km

+

DIRECT

+

00:00:00

+
+
+
+ +
+
+
+ + +
+
+

+
+ +
+

+
+ +
+ + + +)rawliteral"; + +const char HTML_SCRIPTSETINTERVAL[] PROGMEM = R"rawliteral( + +)rawliteral"; + +const char HTML_SCRIPTGETDATA[] PROGMEM = R"rawliteral( +)rawliteral"; + +const char HTML_END[] PROGMEM = R"rawliteral( + )rawliteral"; + +// HTML web page to handle 3 input fields (inputString, inputInt, inputFloat) +const char index_html[] PROGMEM = R"rawliteral( + + ESP Input Form + +

+
+ inputString (current value %inputString%): + +

+
+ inputInt (current value %inputInt%): + +

+
+ inputFloat (current value %inputFloat%): + +
+

+)rawliteral"; + +const char wifi_html[] PROGMEM = R"rawliteral( + + ESP WIFI Station + + +

Your Local IP is: %localip%
+
+ Wifi SSID (current value %ssidString%): + Password (current value %inputPwd%): + +

+ +

+ +)rawliteral"; + + + + +const char main_menu[] PROGMEM = R"rawliteral( + + Rally TerraTrip v1 + + + + + + +
+
+
+

MENU1

+
+
+
+
+
+
+
+
+
+
+
+ +
+ +
+
+
+
+
+ +
+ +
+
+
MENU
+
+ + + + + Wifi +
+
+ +
+ +)rawliteral"; + +const char main_menu1[] PROGMEM = R"rawliteral( + + Rally TerraTrip v1 + + + + + + +
+
+
MENU
+
+ + + + + Wifi +
+
+
+ +)rawliteral"; \ No newline at end of file diff --git a/test/README b/test/README new file mode 100644 index 0000000..b94d089 --- /dev/null +++ b/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PlatformIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PlatformIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html