#include <Servo.h>
unsigned long interval = 0;
unsigned long lastReadTime = 0;
// ---------- Servos ----------
const int NUM_WHEELS = 2;
const int WHEEL_PINS[NUM_WHEELS] = {D3, D5};
Servo wheels[NUM_WHEELS];
// ---------- Joystick ----------
#define VERT_PIN A0
#define HORIZ_PIN A1
const int JOY_MIN = 0;
const int JOY_MAX = 1023;
const int JOY_CENTER = 512;
const int DEADZONE = 30;
int lastAngle = 90;
// ---------- Slide potentiometer ----------
#define SLIDE_PIN A2
// ---------- Stepper drivers (A4988) ----------
const int STEP1_PIN = D4; // driver 1 STEP
const int DIR1_PIN = D7; // driver 1 DIR
const int STEP2_PIN = D8; // driver 2 STEP
const int DIR2_PIN = D9; // driver 2 DIR (matches wiring file)
// Speed tuning
const int SLIDE_DEADBAND = 30; // below this, steppers stay stopped
const unsigned long SLOWEST_INTERVAL_US = 4000; // time between steps at lowest speed
const unsigned long FASTEST_INTERVAL_US = 5; // time between steps at full slide
unsigned long lastStepTime = 0;
unsigned long lastPrintTime = 0;
void setAllWheels(int angle) {
for (int i = 0; i < NUM_WHEELS; i++) {
wheels[i].write(angle);
}
}
// One step on BOTH motors: pulse STEP high then low
void stepBothMotors() {
digitalWrite(STEP1_PIN, HIGH);
digitalWrite(STEP2_PIN, HIGH);
delayMicroseconds(5); // A4988 needs at least 1 microsecond
digitalWrite(STEP1_PIN, LOW);
digitalWrite(STEP2_PIN, LOW);
}
void setup() {
Serial.begin(115200);
pinMode(VERT_PIN, INPUT);
pinMode(HORIZ_PIN, INPUT);
pinMode(SLIDE_PIN, INPUT);
pinMode(STEP1_PIN, OUTPUT);
pinMode(DIR1_PIN, OUTPUT);
pinMode(STEP2_PIN, OUTPUT);
pinMode(DIR2_PIN, OUTPUT);
digitalWrite(DIR1_PIN, HIGH); // HIGH = one direction, LOW = the other
digitalWrite(DIR2_PIN, HIGH); // flip one to LOW if a wheel spins backwards
for (int i = 0; i < NUM_WHEELS; i++) {
wheels[i].attach(WHEEL_PINS[i]);
}
setAllWheels(lastAngle);
}
void loop() {
// ----- Read inputs + servos only every 20 ms -----
if (millis() - lastReadTime >= 20) {
lastReadTime = millis();
int horiz = analogRead(HORIZ_PIN);
int slide = analogRead(SLIDE_PIN);
int angle = map(horiz, JOY_MIN, JOY_MAX, 180, 0);
angle = constrain(angle, 0, 180);
if (abs(horiz - JOY_CENTER) < DEADZONE) angle = 90;
if (angle != lastAngle) {
setAllWheels(angle);
lastAngle = angle;
}
if (slide > SLIDE_DEADBAND) {
interval = map(slide, SLIDE_DEADBAND, 1023,
SLOWEST_INTERVAL_US, FASTEST_INTERVAL_US);
} else {
interval = 0;
}
}
// ----- Step as fast as the timer allows -----
if (interval > 0) {
unsigned long now = micros();
if (now - lastStepTime >= interval) {
stepBothMotors();
lastStepTime = now;
}
}
}
//We have 4 PB8, PB0, for our 4 oled screens, 4 SDA is splintered into PB8, 4 SCL splintered into PB9Loading
st-nucleo-c031c6
st-nucleo-c031c6
TOP
5v (Motors, controls)
Bottom
3v (Screens)
Wheel / servo 1
Wheel / servo 2
Wheel / servo 3
Wheel / servo 4