A while ago I put a video up on YouTube of using an encoder to control a stepper motor.
After numerous requests for code and modifications I'm posting it here as it is no longer hosted on my old works website and this is a good forum to discuss etc.
Video:
Code:
//Arduino code for controlling stepper motor from encoder
//video at https://www.youtube.com/watch?v=2dh6TIkN6jE
//reconstructed code from 5+ years ago
//untested in current form
#define encoder_a 2 //encoder a = arduino pin 2
#define encoder_b 3 //encoder b = arduino pin 3
#define motor_step 4 //motor step = arduino pin 4
#define motor_direction 5 //motor direction = arduino pin 5
volatile long motor_position, encoder;
void setup ()
{
//set up the various outputs
pinMode(motor_step, OUTPUT);
pinMode(motor_direction, OUTPUT);
// then the encoder inputs
pinMode(encoder_a, INPUT);
pinMode(encoder_b, INPUT);
digitalWrite(encoder_a, HIGH);
digitalWrite(encoder_b, HIGH);
// encoder pin on interrupt 0 (pin 2)
attachInterrupt(0, encoderPinChangeA, CHANGE);
// encoder pin on interrupt 1 (pin 3)
attachInterrupt(1, encoderPinChangeB, CHANGE);
encoder = 0;
}
void encoderPinChangeA()
{
if (digitalRead(encoder_a) == digitalRead(encoder_b))
{
encoder--;
}
else
{
encoder++;
}
}
void encoderPinChangeB()
{
if (digitalRead(encoder_a) != digitalRead(encoder_b))
{
encoder--;
}
else
{
encoder++;
}
}
void loop()
{
//do stuff dependent on encoder position here
//such as move a stepper motor to match encoder position
//if you want to make it 1:1 ensure the encoder res matches the motor res by dividing/multiplying
if (encoder > 0)
{
digitalWrite(motor_direction, HIGH);
digitalWrite(motor_step, HIGH);
digitalWrite(motor_step, LOW);
_delay_us(200);
motor_position++;
encoder = 0;
}
else if (encoder < 0)
{
digitalWrite(motor_direction, LOW);
digitalWrite(motor_step, HIGH);
digitalWrite(motor_step, LOW);
_delay_us(200);
motor_position--;
encoder = 0;
}
}