Quantcast
Channel: Arduino Forum - Latest topics
Viewing all articles
Browse latest Browse all 15514

Controlling Optical Encoders Without Using Interrupt Pins

$
0
0

Hello, I am currently trying to use these optical encoders for a feedback loop to control some DC motors. I am just trying to move each motor a certain amount in a specific order Ex. rotate 1st motor 100 steps, 2nd motor 200 steps, and 3rd motor 300 steps. The way I am doing this is by using 3 For Loops that will power each motor accordingly until the amount of steps has been reached by each encoder attached to their respective motors. So in my example, the first for loop will rotate the MotorA until the optical encoder attached has rotated 100 steps. The 2nd for loop will rotate the MotorB until it's optical encoder has rotated 200 steps etc... This is why I believe I should be able to use regular input pins rather than interrupt pins as I will have scheduled times to check for rotation of each encoder within the code (I will only be checking the 1st encoder rotating in the 1st for loop, the 2nd encoder in the 2nd loop, and the 3rd encoder in the 3rd). The problem I am encountering is I do not know how to properly program the loops to check for the pulses in the optical encoder.

I know this code works to check pulses in a standard rotary encoder:

#define CLK 3
int counter = 0;
int currentStateCLK;
int lastStateCLK;

void setup() {
  pinMode(CLK,INPUT);
  Serial.begin(9600);
  lastStateCLK = digitalRead(CLK);
}

void loop() {
  currentStateCLK = digitalRead(CLK);
  //not checking for direction, just incrementing
  if (currentStateCLK != lastStateCLK  && currentStateCLK == 1){ 
    counter++;
    Serial.println(counter);
  }
  lastStateCLK = currentStateCLK;
  delay(4); //debouncing
}

And I know this code works to sense rotation in an optical encoder using interrupt pins:

int temp, counter = 0; //This variable will increase or decrease depending on the rotation of encoder
void setup() {
  Serial.begin (9600);
  pinMode(2, INPUT_PULLUP); // internal pullup input pin 2 
  pinMode(3, INPUT_PULLUP); // internal pullup input pin 3
//Setting up interrupt
  attachInterrupt(0, ai0, RISING);   
  attachInterrupt(1, ai1, RISING);
  }  
  void loop() {
    Serial.println(digitalRead(3));
  if( counter != temp ){
  Serial.println (counter);
  temp = counter;
  }
  }
  void ai0() {
  // ai0 is activated if DigitalPin nr 2 is going from LOW to HIGH
  // Check pin 3 to determine the direction
  if(digitalRead(3)==LOW) {
  counter++;
  }else{
  counter--;
  }
  }
  void ai1() {
  // ai0 is activated if DigitalPin nr 3 is going from LOW to HIGH
  // Check with pin 2 to determine the direction
  if(digitalRead(2)==LOW) {
  counter--;
  }else{
  counter++;
  }
  }

So my question is how can I sense optical encoders without using interrupt pins?

9 posts - 5 participants

Read full topic


Viewing all articles
Browse latest Browse all 15514

Trending Articles