#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);
// ===== TP6600 Pins =====
#define STEP_PIN 5
#define DIR_PIN 6
#define EN_PIN 7
// ===== Buttons =====
#define BTN_CCW 4
#define BTN_STOP 3
#define BTN_CW 2
// ===== Potentiometer =====
#define POT_PIN A0
// ===== Variables =====
int speedPercent = 0;
int direction = 0; // -1=CCW, 0=STOP, 1=CW
unsigned long lastStepTime = 0;
unsigned long lastDisplayTime = 0;
int currentDelay = 1000; // smooth running delay
int targetDelay = 1000; // pot based delay
// ===== OLED Display Function =====
void drawDisplay() {
display.setRotation(2);
display.clearDisplay();
display.setTextColor(SSD1306_WHITE);
// Top Menu
display.setTextSize(direction == -1 ? 2 : 1);
display.setCursor(0, 0);
display.print("CCW");
display.setTextSize(direction == 0 ? 2 : 1);
display.setCursor(45, 0);
display.print("STOP");
display.setTextSize(direction == 1 ? 2 : 1);
display.setCursor(95, 0);
display.print("CW");
// Speed Text
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();
}
// ===== Setup =====
void setup() {
Serial.begin(9600);
pinMode(STEP_PIN, OUTPUT);
pinMode(DIR_PIN, OUTPUT);
pinMode(EN_PIN, OUTPUT);
pinMode(BTN_CCW, INPUT_PULLUP);
pinMode(BTN_STOP, INPUT_PULLUP);
pinMode(BTN_CW, INPUT_PULLUP);
pinMode(POT_PIN, INPUT);
digitalWrite(EN_PIN, LOW); // Enable driver
// OLED init
if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
Serial.println("OLED failed");
while (1);
}
}
// ===== Main Loop =====
void loop() {
// ===== Read Potentiometer =====
int potValue = analogRead(POT_PIN);
targetDelay = map(potValue, 0, 1023, 2000, 300);
targetDelay = constrain(targetDelay, 300, 2000);
speedPercent = map(potValue, 0, 1023, 0, 100);
// ===== Smooth Acceleration =====
if (currentDelay < targetDelay) currentDelay += 5;
if (currentDelay > targetDelay) currentDelay -= 5;
// ===== Read Buttons =====
if (digitalRead(BTN_CW) == LOW) direction = 1;
if (digitalRead(BTN_CCW) == LOW) direction = -1;
if (digitalRead(BTN_STOP) == LOW) direction = 0;
// ===== Stepper Motor Control =====
if (direction != 0) {
digitalWrite(DIR_PIN, direction == 1 ? HIGH : LOW);
if (micros() - lastStepTime >= currentDelay) {
lastStepTime = micros();
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(5); // clean pulse
digitalWrite(STEP_PIN, LOW);
}
}
// ===== OLED Update (Slow Refresh) =====
if (millis() - lastDisplayTime > 200) {
lastDisplayTime = millis();
drawDisplay();
}
// ===== Debug =====
Serial.print("Dir: ");
Serial.print(direction);
Serial.print(" Speed: ");
Serial.println(speedPercent);
}