/*
RP2040 Simple stepper test
Don't try this wiring at home kids!
(You need a driver for the stepper.)
*/
// pin constants
const int ADC_PIN = 28;
const int BTN_PIN = 2;
// note the stepper phasing!
const int IN1_PIN = 11; // B+
const int IN2_PIN = 10; // B-
const int IN3_PIN = 12; // A+
const int IN4_PIN = 13; // A-
// stepper phase order
const bool PHASES[][4] = {
{LOW, HIGH, LOW, HIGH},
{LOW, HIGH, HIGH, LOW},
{HIGH, LOW, HIGH, LOW},
{HIGH, LOW, LOW, HIGH}
};
bool isCW = true; // initial start direction
bool checkButton() {
static bool lastBtnState = true;
static unsigned long lastTime = 0;
int btnState = digitalRead(BTN_PIN);
unsigned long now = millis();
if (btnState != lastBtnState && now - lastTime >= 20) {
if (!btnState) {
isCW = !isCW;
Serial1.println(isCW ? "CW" : "CCW");
//Serial1.println("Button pressed!");
} else {
//Serial1.println("Button released!");
}
lastTime = now;
lastBtnState = btnState;
}
return isCW;
}
void spinStepper(bool dir, int speed) {
if (dir) {
for (int phase = 0; phase < 4; phase++) {
digitalWrite(IN1_PIN, PHASES[phase][0]);
digitalWrite(IN2_PIN, PHASES[phase][1]);
digitalWrite(IN3_PIN, PHASES[phase][2]);
digitalWrite(IN4_PIN, PHASES[phase][3]);
delay(speed);
}
} else {
for (int phase = 3; phase >= 0; phase--) {
digitalWrite(IN1_PIN, PHASES[phase][0]);
digitalWrite(IN2_PIN, PHASES[phase][1]);
digitalWrite(IN3_PIN, PHASES[phase][2]);
digitalWrite(IN4_PIN, PHASES[phase][3]);
delay(speed);
}
}
}
void setup() {
Serial1.begin(115200);
Serial1.println("Hello, Raspberry Pi Pico!\n");
pinMode(BTN_PIN, INPUT_PULLUP);
pinMode(IN1_PIN, OUTPUT);
pinMode(IN2_PIN, OUTPUT);
pinMode(IN3_PIN, OUTPUT);
pinMode(IN4_PIN, OUTPUT);
Serial1.println(isCW ? "CW" : "CCW");
}
void loop() {
bool direction = checkButton();
int speed = map(analogRead(28), 0, 1023, 50, 5);
spinStepper(direction, speed);
delay(10); // this speeds up the simulation
}
Direction
Speed