#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET -1
Adafruit_SSD1306 display(128, 64, &Wire, OLED_RESET);
#define BTN_INC 0
#define BTN_DEC 4
#define BTN_SET 5
#define BTN_OK 16
#define MOTOR_PWM 13
int rpm = 1000;
unsigned long setTime = 0;
int settingStep = 0;
bool isRunning = false;
unsigned long startTime = 0;
void adjustTime(int step, int delta) {
unsigned long h = setTime / 3600;
unsigned long m = (setTime % 3600) / 60;
unsigned long s = setTime % 60;
if (step == 1) h = constrain(h + delta, 0, 23);
if (step == 2) m = constrain(m + delta, 0, 59);
if (step == 3) s = constrain(s + delta, 0, 59);
setTime = h * 3600 + m * 60 + s;
}
void updateDisplay() {
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print("RPM: "); display.println(rpm);
display.setCursor(0, 10);
display.print("TIME: ");
int h = setTime / 3600;
int m = (setTime % 3600) / 60;
int s = setTime % 60;
display.printf("%02d:%02d:%02d\n", h, m, s);
display.setCursor(0, 30);
display.print("Battery: ");
float voltage = analogRead(A0) * (3.3 / 1023.0) * (4.2 / 3.3);
display.print(voltage); display.println("V");
display.setCursor(0, 45);
if (isRunning) display.print("Running...");
else display.print("Ready!");
display.display();
}
void handleButtons() {
static bool lastOk = HIGH, lastInc = HIGH, lastDec = HIGH, lastSet = HIGH;
bool nowInc = digitalRead(BTN_INC);
bool nowDec = digitalRead(BTN_DEC);
bool nowSet = digitalRead(BTN_SET);
bool nowOk = digitalRead(BTN_OK);
if (lastInc == HIGH && nowInc == LOW) {
if (settingStep == 0) rpm += 100;
else adjustTime(settingStep, +1);
}
if (lastDec == HIGH && nowDec == LOW) {
if (settingStep == 0) rpm = max(100, rpm - 100);
else adjustTime(settingStep, -1);
}
if (lastSet == HIGH && nowSet == LOW) {
settingStep = (settingStep + 1) % 4;
}
if (lastOk == HIGH && nowOk == LOW) {
analogWrite(MOTOR_PWM, map(rpm, 0, 5000, 0, 1023));
startTime = millis();
isRunning = true;
}
lastInc = nowInc;
lastDec = nowDec;
lastSet = nowSet;
lastOk = nowOk;
}
void setup() {
Wire.begin(14, 12);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
pinMode(BTN_INC, INPUT_PULLUP);
pinMode(BTN_DEC, INPUT_PULLUP);
pinMode(BTN_SET, INPUT_PULLUP);
pinMode(BTN_OK, INPUT_PULLUP);
pinMode(MOTOR_PWM, OUTPUT);
analogWrite(1023);
analogWrite(1000);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.display();
}
void loop() {
handleButtons();
updateDisplay();
if (isRunning) {
if (millis() - startTime >= setTime * 1000) {
analogWrite(MOTOR_PWM, 0);
isRunning = false;
}
}
}