Hardware Reference
In-Depth Information
Figure 6-4. Pulses of a dual-output encoder
It is up to the reader/controller to keep track of the pulses to determine if a full rotation or swing has been
achieved. The code for the reader also has to determine the direction the gray code is shifting. For the sensor reader,
Dr. Ayars wrote an article on how to read a rotary encoder (SparkFun part number COM-09117). In this example, the
code increments/decrements a variable depending on the direction the encoder was traveling when the detent was
reached, but not the number of rotations preformed. More information on reading this type of sensor is available on
Dr. Ayars' blog, at http://hacks.ayars.org/2009/12/using-quadrature-encoder-rotary-switch.html .
The technique used in Listing 6-4 is one method of reading gray code and is excellent for reading two output encoders.
A more advanced method is needed for three or more pin encoders to achieve the error correction of positioning and count.
The following code needs to be loaded on the Arduino to be used as the reader for the first half of this example.
Listing 6-4. Dr. Ayars' Code with Reworked Comments
byte Blinker = 13;
int Delay = 250;
byte A = 2;// 1st sensor Out pin
byte B = 3;// 2nd sensor Out pin
volatile int Rotor = 0; // sensor click count
void setup() {
pinMode(Blinker, OUTPUT);
pinMode(A, INPUT);
pinMode(B, INPUT);
digitalWrite(A, HIGH); // Turn on pull-up resistors
digitalWrite(B, HIGH);
attachInterrupt(0, UpdateRotation, FALLING);// use interrupt on pin A
Serial.begin(9600);
}// end setup()
void loop() {
digitalWrite(Blinker, HIGH); // Blink LED
delay(Delay); // any code can run here. the sensor will be
digitalWrite(Blinker, LOW); // updated upon interrupt on pin 2.
delay(Delay);
} // end loop()
 
Search WWH ::




Custom Search