Coding 4.0 (with reset button)
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define BUTTON_FRONT 13
#define BUTTON_REAR 14
#define BUTTON_RESET 32
#define MOSFET_FRONT 27
#define MOSFET_REAR 26
#define I2C_SDA 25
#define I2C_SCL 33
int frontCount = 0;
int rearCount = 0;
bool prevFrontState = LOW;
bool prevRearState = LOW;
bool prevResetState = HIGH;
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
pinMode(BUTTON_FRONT, INPUT);
pinMode(BUTTON_REAR, INPUT);
pinMode(BUTTON_RESET, INPUT_PULLUP);
ledcSetup(0, 5000, 8);
ledcAttachPin(MOSFET_FRONT, 0);
ledcSetup(1, 5000, 8);
ledcAttachPin(MOSFET_REAR, 1);
Wire.begin(I2C_SDA, I2C_SCL);
lcd.begin();
lcd.backlight();
updateLCD();
}
void loop() {
bool frontState = digitalRead(BUTTON_FRONT);
bool rearState = digitalRead(BUTTON_REAR);
bool resetState = digitalRead(BUTTON_RESET);
if (frontState == HIGH && prevFrontState == LOW) {
ledcWrite(0, 255);
} else if (frontState == LOW && prevFrontState == HIGH) {
frontCount++;
updateLCD();
ledcWrite(0, 0);
}
prevFrontState = frontState;
if (rearState == HIGH && prevRearState == LOW) {
ledcWrite(1, 255);
} else if (rearState == LOW && prevRearState == HIGH) {
rearCount++;
updateLCD();
ledcWrite(1, 0);
}
prevRearState = rearState;
if (resetState == LOW && prevResetState == HIGH) {
resetCounts();
}
prevResetState = resetState;
delay(10);
}
void updateLCD() {
lcd.setCursor(0, 0);
lcd.print("Front Brake :");
lcd.setCursor(0, 1);
lcd.print("Rear Brake :");
printRightAligned(frontCount, 0); // row 0
printRightAligned(rearCount, 1); // row 1
}
void printRightAligned(int value, int row) {
String strVal = String(value);
int len = strVal.length();
int col;
if (len == 1) {
col = 14; // hanya col 14
} else if (len == 2) {
col = 14; // col 14 & 15
} else {
col = 13; // col 13,14,15
}
// Bersihkan ruang 3 digit terakhir (col 13–15)
lcd.setCursor(13, row);
lcd.print(" ");
lcd.setCursor(col, row);
lcd.print(strVal);
}
void resetCounts() {
frontCount = 0;
rearCount = 0;
updateLCD();
ledcWrite(0, 255);
ledcWrite(1, 255);
for (int i = 0; i < 3; i++) {
lcd.noBacklight();
delay(200);
lcd.backlight();
delay(200);
}
ledcWrite(0, 0);
ledcWrite(1, 0);
}
G D S
Front
Front
Front
USB 5V
GND
G D S
Rear
Rear
Rear
Reset Button