This circuit is designed to control a bipolar stepper motor using an A4988 stepper motor driver, with an Arduino UNO as the microcontroller. The Arduino UNO reads inputs from a rotary encoder to determine the direction and steps for the stepper motor. A 9V battery provides power to the system.
#define STEP_PIN 3
#define DIR_PIN 2
#define CLK_PIN 5
#define DT_PIN 4
volatile int encoderValue = 0;
volatile int lastEncoded = 0;
void setup() {
pinMode(STEP_PIN, OUTPUT);
pinMode(DIR_PIN, OUTPUT);
pinMode(CLK_PIN, INPUT);
pinMode(DT_PIN, INPUT);
attachInterrupt(digitalPinToInterrupt(CLK_PIN), updateEncoder, CHANGE);
attachInterrupt(digitalPinToInterrupt(DT_PIN), updateEncoder, CHANGE);
}
void loop() {
// Example: Rotate stepper motor based on encoder value
if (encoderValue > 0) {
digitalWrite(DIR_PIN, HIGH); // Set direction
for (int i = 0; i < encoderValue; i++) {
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(1000); // Adjust delay for speed control
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(1000);
}
encoderValue = 0; // Reset encoder value after moving
} else if (encoderValue < 0) {
digitalWrite(DIR_PIN, LOW); // Set direction
for (int i = 0; i < abs(encoderValue); i++) {
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(1000); // Adjust delay for speed control
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(1000);
}
encoderValue = 0; // Reset encoder value after moving
}
}
void updateEncoder() {
int MSB = digitalRead(CLK_PIN); // MSB = most significant bit
int LSB = digitalRead(DT_PIN); // LSB = least significant bit
int encoded = (MSB << 1) | LSB; // Converting the 2 pin value to single number
int sum = (lastEncoded << 2) | encoded; // Adding it to the previous encoded value
if (sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue++;
if (sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue--;
lastEncoded = encoded; // Store this value for next time
}
This code is responsible for controlling the stepper motor based on the input from the rotary encoder. The updateEncoder
function is an interrupt service routine that updates the encoderValue
based on the rotation of the encoder. The loop
function then uses this value to control the direction and number of steps the stepper motor takes.