1

I have two encoders; I connected them to pin 2 and 3 and I want to count the pulses of them to make two DC motors to work until it reaches a specified number of pulses, than stop working. I have finished the code of one encoder, but the other one I can't put in the same code.

byte pin = 2;
volatile float elapsed;
volatile float previous;
float rpm;
volatile int pulses;
volatile bool flag;

void setup() {
  Serial.begin(9600);
  pinMode(pin, INPUT);
  attachInterrupt(0, elapse, RISING); 
  previous = millis();
}

void loop() {
  pulses = 0; // reset pulses counter

  attachInterrupt(0, elapse, RISING); // attach interrupt for rpm counter
  delay(500); 
  detachInterrupt(0); // detach interrupt for rpm counter

  if (flag == true) {
    attachInterrupt(1, count, RISING); // attach interrupt for pulses counter
    delay(elapsed);
    detachInterrupt(1); // detach interrupt for pulses counter
    flag = false; // reset flag
  }

  rpm = 1000 / elapsed * 60;

  Serial.print("elapsed: "); // print resuslts
  Serial.println(elapsed);
  Serial.print("rpm: ");
  Serial.println(rpm);
  Serial.print("pulses: ");
  Serial.println(pulses);
}

void elapse() { 
  elapsed = millis() - previous;
  previous = millis(); 
  flag = true; // set flag to activate pulses counter
} 

void count() {
  pulses++;
}
  • what is preventing you from counting the pulses of both of the encoders? ...... this does not count as a description of a problem .... I can't put in the same code – jsotola Mar 1 at 18:08
  • if you think that you cannot do multiple things in your sketch, then look at the six Serial.print() lines ..... that is "doing multiple things" right there – jsotola Mar 1 at 18:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.