Created
September 3, 2012 10:43
-
-
Save soffer/3608479 to your computer and use it in GitHub Desktop.
Stepper motor position control by optical encider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <AccelStepper.h> | |
//encoder/motor/driver setup | |
int easyDriverMicroSteps = 1; | |
int rotaryEncoderSteps = 75; //setps per rev on your encoder | |
int motorStepsPerRev = 200; //steps per rev on the motor | |
int MinPulseWidth = 50; //too low and the motor will stall, too high and it will slow it down | |
//these pins can not be changed 2/3 are special pins | |
int encoderPin1 = 2; | |
int encoderPin2 = 3; | |
int easyDriverStepPin = 4; | |
int easyDriverDirPin = 5; | |
volatile int lastEncoded = 0; | |
volatile long encoderValue = 0; | |
long lastencoderValue = 0; | |
int lastMSB = 0; | |
int lastLSB = 0; | |
//1 means we are using a motor driver with the library | |
AccelStepper stepper(1, easyDriverStepPin, easyDriverDirPin); | |
void setup(){ | |
Serial.begin(115200); | |
stepper.setMinPulseWidth(MinPulseWidth); | |
stepper.setMaxSpeed(50000); | |
stepper.setAcceleration(1000000000); | |
stepper.setSpeed(50000); | |
pinMode(encoderPin1, INPUT); | |
pinMode(encoderPin2, INPUT); | |
digitalWrite(encoderPin1, HIGH); //turn pullup resistor on | |
digitalWrite(encoderPin2, HIGH); //turn pullup resistor on | |
//call updateEncoder() when any high/low changed seen | |
//on interrupt 0 (pin 2), or interrupt 1 (pin 3) | |
attachInterrupt(0, updateEncoder, CHANGE); | |
attachInterrupt(1, updateEncoder, CHANGE); | |
} | |
void loop(){ | |
//go to where the encoder was turned to. | |
int stepsPerRotaryStep = (motorStepsPerRev * easyDriverMicroSteps) / rotaryEncoderSteps; | |
stepper.moveTo(encoderValue * stepsPerRotaryStep); | |
stepper.run(); | |
if(encoderValue != lastencoderValue){ | |
lastencoderValue = encoderValue; | |
Serial.println(encoderValue); | |
} | |
} | |
void updateEncoder(){ | |
int MSB = digitalRead(encoderPin1); //MSB = most significant bit | |
int LSB = digitalRead(encoderPin2); //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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment