Because of numerous requests for the code this was bashed together in

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Because of numerous requests for the code this was bashed together in OCT 2012 a couple of years after the project in the video http://www.youtube.com/watch?v=2dh6TIkN6jE
// It is untested in its current state but should work and should be a good example to interface an encoder and stepper to arduino
// It is intended for people with basic knowledge of arduino programming, encoders, stepper motors and drivers
// www.oceancontrols.com.au
// If it doesn't work and you fix it email info@oceancontrols.com.au
// If you need help with compiling or arduino related stuff check out arduino.cc and the forums there
//
#define encoder_a 2 //keep this on and interrupt pin
#define encoder_b 3 //keep this on and interrupt pin
#define motor_step 46 //can be any pin
#define motor_direction 48 //can be any pin
#include <delay.h>
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);
// enable pullup as we are using an open collector encoder
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; //reseet the encoder position to 0
}
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);// move stepper in reverse
digitalWrite(motor_step, HIGH);
digitalWrite(motor_step, LOW);
delayMicroseconds(200); //_delay_us(200); //modify to alter speed
motor_position++;
encoder = 0; //encoder--;
}
else if (encoder < 0) {
digitalWrite (motor_direction, LOW); //move stepper forward
digitalWrite (motor_step, HIGH);
digitalWrite (motor_step, LOW);
delayMicroseconds(200); //_delay_us(200); //modify to alter speed
motor_position--;
encoder = 0; //encoder++;
}
}
void encoderPinChangeA() {
if (digitalRead(encoder_a)==digitalRead(encoder_b)) {
encoder--;
}
else{
encoder++;
}
}
void encoderPinChangeB() {
if (digitalRead(encoder_a) != digitalRead(encoder_b)) {
encoder--;
}
else {
encoder++;
}
}