#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
// Encoder
#define ENC_CLK 9
#define ENC_DT 10
int speedDelay = 1000; // microseconds (LOW = fast, HIGH = slow)
int speedPercent = 0;
int direction = 0; // -1=CCW, 0=STOP, 1=CW
// Encoder variables
int lastCLK;
int currentCLK;
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(ENC_CLK, INPUT);
pinMode(ENC_DT, INPUT);
digitalWrite(EN_PIN, LOW); // Enable driver
lastCLK = digitalRead(ENC_CLK);
// OLED init
if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
Serial.println("OLED failed");
while (1);
}
}
// OLED Display
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
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() {
// ===== Encoder Read =====
currentCLK = digitalRead(ENC_CLK);
if (currentCLK != lastCLK) {
if (digitalRead(ENC_DT) != currentCLK) {
speedDelay -= 50; // faster
} else {
speedDelay += 50; // slower
}
speedDelay = constrain(speedDelay, 200, 3000);
speedPercent = map(speedDelay, 3000, 200, 0, 100);
}
lastCLK = currentCLK;
// ===== Buttons =====
if (digitalRead(BTN_CW) == LOW) direction = 1;
if (digitalRead(BTN_CCW) == LOW) direction = -1;
if (digitalRead(BTN_STOP) == LOW) direction = 0;
// ===== Stepper Control =====
if (direction != 0) {
digitalWrite(DIR_PIN, direction == 1 ? HIGH : LOW);
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(speedDelay);
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(speedDelay);
}
// ===== Display =====
drawDisplay();
// Debug
Serial.print("Dir: ");
Serial.print(direction);
Serial.print(" Speed: ");
Serial.println(speedPercent);
}