0

I have a question with encoder and the rotary motor. When the motor is moving, I can't access the position of the motor. I have run the code separately, it is perfectly fine. But when I combine, these two codes, the motor is able to move but there was no position data.

Any suggestion on how can I get the motor moving and get the encoder position at the same time.

The combined code I have drafted is there:

  #include <Stepper.h>

    const int stepsPerRevolution = 4000;  // 4000 steps for one circle with 10mm increment. 
    const int motorPitchPerCircle = 10;     // 10mm per circle for the linear ball screw guide for motor. 

    int val;
    int encoder0PinA = 3; // Pin 15 of the cable.
    int encoder0PinB = 4; // Pin 13 of the cable. 
    int encoder0Pos = 0;
    int encoder0PinALast = LOW;
    int n = LOW;

    // initialize the stepper library on pins 8 through 11:
    Stepper myStepper(stepsPerRevolution, 9, 8, A3, A5);

    void setup() {
      // set the speed at 60 rpm:
      myStepper.setSpeed(100);
      // initialize the serial port:
      Serial.begin(9600);

      pinMode (encoder0PinA, INPUT);
      pinMode (encoder0PinB, INPUT);
      Serial.begin (9600); 
    }

    void loop() {
      // step one revolution  in one direction:
      myStepper.step(6*stepsPerRevolution);
      delay(2000); 

       n = digitalRead(encoder0PinA);
      if ((encoder0PinALast == LOW) && (n == HIGH)) {
        if (digitalRead(encoder0PinB) == LOW) {
          encoder0Pos--;
        } else {
          encoder0Pos++;
        }
        Serial.print (encoder0Pos);
        Serial.print ("/");
      }
      encoder0PinALast = n;

    }
2

1 Answer 1

1

While your delay() function is running, you won't be able to read any data. Suggestion is to use interrupts, which basically guarantee that whenever your pin state changes (low edge, high edge, or any change, feel free to select it), some action will be performed. This action can be reading your encoder position.

Read about it here https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

I am sure it will answer all your questions, it is quite well documented

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.