/* Read Encoder Direction * by DojoCorp <http://www.0j0.org> * * Demonstrates how to detect the direction * towards which a motor spins through using * a two lines encoder. The testing procedure * is to: * - press pushbutton 1 on the board to start the test * - make the encoder spin by hand * - press pushbutton 1 on the board to stop the test * - read the result on the serial port configured at 9600 * * - by the end of the test, button 2 will restart * * Description of the pinout used by the motor control board: * - digital pin 39 reads pushbutton 1 * - digital pin 38 reads pushbutton 2 * - digital pin 0 reads encoder's input A (we just need one encoder line) * - digital pin 1 reads encoder's cross by zero (not used) * - digital pin 4 reads encoder's input B (not used) * * Created 25 March 2005 */ int encoderA = 0; // pin 0 is the encoder's line A int encoderCross = 1; // pin 1 is the encoder's cross by zero int encoderB = 4; // pin 4 is the encoder's line B int inB = 38; // reads the pin 38 as a pushbutton (pushbutt 2) int inA = 39; // reads the pin 39 as a pushbutton (pushbutt 1) boolean testing = false; // memorize if we are in the testing process int ledpin = 48; // show the status on while testing, off otherwise int lastState = LOW; // monitor last state of the measuring pin int state = LOW; // monitor current state of the measuring pin
void setup() {
pinMode(inA, INPUT);
pinMode(inB, INPUT);
pinMode(encoderA, INPUT);
pinMode(encoderCross, INPUT);
pinMode(encoderB, INPUT);
pinMode(ledpin, OUTPUT);
beginSerial(9600);
printMode(SERIAL);
print("Start Program \n\r");
print("Verbose Active \n\r");
}
void loop() {
// Waits until button 1 pressed to start the test
while (!testing) {
if (digitalRead(inA) == HIGH) {
testing = true;
}
delay(100);
}
// Test starts, counting steps in the encoder
print("Start Test \n\r");
digitalWrite(ledpin, HIGH);
while (testing) {
state = digitalRead(encoderA);
if ((state == HIGH) && (lastState == LOW)) {
// only if there is a transition from low to high
if (digitalRead(encoderB) == HIGH) {
print("Rotating in direction 1");
} else {
print("Rotating in direction 2");
}
}
lastState = state;
if (digitalRead(inA) == HIGH) {
testing = false;
}
delay(50); // this time value is our temporal resolution
}
// Final info
print("Test if finished \n\r");
digitalWrite(ledpin, LOW);
print("Press button 2 to repeat \n\r");
while (digitalRead(inB) == LOW) {
delay(100);
} }
|