Hi all,
I have a problem when an encoder is connected to the Mega board together with a stepper motor. the motor doesn't rotate fluently but brakes and accelerates if the encoder is rotated.
In brief: the goal of my project is :
First I set the zero angle of a rotary encoder, and then I rotate the motor connected to the encoder and I acquire the angle and print the rpm.
My components are: stepper motor NEMA 17, controller A4988, rotary encoder with 600 pulses/rev, arduino mega.
At the beginning of the code the motor doesn't rotate. Then I can position the motor and the encoder connected to it to a certain position, click the button to set the zero angle of the encoder and then the motor starts rotating. I adjust the speed with a potentiometer and print the speed in rpm.
Everything works, except that the motor doesn't rotate smoothly when also the encoder is rotating. For example, if I separate the encoder from the motor and rotate it quickly, the motor almost stops for a while, and then runs again.
do you have any idea for how to solve this problem?
Thank you!!
-Code-
#include <Rotary.h>
Rotary rotary = Rotary(2, 3);
int EncoderPin=2;
int EncoderPin_1=3;
int pushButton = 6;
int buttonState, speedVar, counter, startTime, endTime, x, delayInMillis;
int stepPin = 5;
int dirPin = 4;
int speedPin = A0;
int enablePin = 7; // Za demagnetizacijo
float razlika;
void setup() {
// put your setup code here, to run once:
pinMode(pushButton, INPUT);
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(speedPin, INPUT);
pinMode(enablePin, OUTPUT);
digitalWrite(enablePin, HIGH);
digitalWrite(dirPin,HIGH);
attachInterrupt(digitalPinToInterrupt(EncoderPin,rotate, CHANGE);
attachInterrupt(digitalPinToInterrupt(EncoderPin_1, rotate, CHANGE);
Serial.begin(2000000);
}
void loop() {
if(digitalRead(pushButton) == 1){
counter = 0;
buttonState = 1;
digitalWrite(enablePin, LOW);
}
while (buttonState == 1){
for(x = 0; x < 200; x++) {
speedVar = map(analogRead(speedPin), 0, 1023, 700, 1600);
if (x == 0) {
startTime = millis();
}
digitalWrite(stepPin,HIGH);
delayMicroseconds(speedVar);
digitalWrite(stepPin,LOW);
delayMicroseconds(speedVar);
if (x == 199){
endTime = millis();
razlika = endTime - startTime;
float seconds = razlika / 1000;
float minutes = seconds / 60;
long int rpm = 1/minutes;
Serial.println(rpm);
}
}
}
}
void rotate() {
unsigned char result = rotary.process();
if (result == DIR_CW) {
counter++;
//Serial.println(counter);
} else if (result == DIR_CCW) {
counter--;
//Serial.println(counter);
}
if (counter == 600){
counter = 0;
}
}