#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// OLED Setup
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_ADDR 0x3C
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// BTS7960 Pins
#define RPWM 5
#define LPWM 6
#define R_EN 7
#define L_EN 8
// Buttons
#define BTN_CCW 2
#define BTN_STOP 3
#define BTN_CW 4
// Potentiometer
#define POT A0
int speedValue = 0;
int speedPercent = 0;
int direction = 0; // -1=CCW, 0=STOP, 1=CW
// Button states
bool lastCCW = HIGH;
bool lastSTOP = HIGH;
bool lastCW = HIGH;
void setup() {
Serial.begin(9600);
pinMode(RPWM, OUTPUT);
pinMode(LPWM, OUTPUT);
pinMode(R_EN, OUTPUT);
pinMode(L_EN, OUTPUT);
pinMode(BTN_CCW, INPUT_PULLUP);
pinMode(BTN_STOP, INPUT_PULLUP);
pinMode(BTN_CW, INPUT_PULLUP);
digitalWrite(R_EN, HIGH);
digitalWrite(L_EN, HIGH);
// OLED init
if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
Serial.println("OLED failed");
while (1);
}
display.clearDisplay();
}
// Draw UI
void drawDisplay() {
display.clearDisplay();
// TOP MENU
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
if (direction == -1) display.setTextSize(2);
display.setCursor(0, 0);
display.print("CCW");
display.setTextSize(1);
if (direction == 0) display.setTextSize(2);
display.setCursor(45, 0);
display.print("STOP");
display.setTextSize(1);
if (direction == 1) display.setTextSize(2);
display.setCursor(95, 0);
display.print("CW");
// SPEED TEXT (BIG)
display.setTextSize(2);
display.setCursor(10, 20);
display.print("Speed:");
display.print(speedPercent);
display.print("%");
// PROGRESS BAR
int barWidth = map(speedPercent, 0, 100, 0, 120);
display.drawRect(4, 50, 120, 10, SSD1306_WHITE);
display.fillRect(4, 50, barWidth, 10, SSD1306_WHITE);
display.display();
}
void loop() {
// Potentiometer
int potValue = analogRead(POT);
speedValue = map(potValue, 0, 1023, 0, 255);
speedPercent = map(potValue, 0, 1023, 0, 100);
// Buttons
bool curCCW = digitalRead(BTN_CCW);
bool curSTOP = digitalRead(BTN_STOP);
bool curCW = digitalRead(BTN_CW);
if (lastCCW == HIGH && curCCW == LOW) {
direction = -1;
}
if (lastSTOP == HIGH && curSTOP == LOW) {
direction = 0;
}
if (lastCW == HIGH && curCW == LOW) {
direction = 1;
}
lastCCW = curCCW;
lastSTOP = curSTOP;
lastCW = curCW;
// Motor Control
if (direction == 1) {
analogWrite(RPWM, speedValue);
analogWrite(LPWM, 0);
}
else if (direction == -1) {
analogWrite(RPWM, 0);
analogWrite(LPWM, speedValue);
}
else {
analogWrite(RPWM, 0);
analogWrite(LPWM, 0);
}
// Serial Monitor
Serial.print("Dir: ");
Serial.print(direction);
Serial.print(" | Speed: ");
Serial.println(speedPercent);
// Display Update
drawDisplay();
delay(100);
}