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;
 }
asked Oct 22, 2018 at 6:46
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

answered Oct 22, 2018 at 7:44
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.