Hello
I am trying to record RPM as soon as I get new pulse from encoder
For one revolution, I found out that the number of pulses is 42000.
As the motor spins, I timed once and as the new pulse came out, I timed again to calculate the difference of time.
so I got the equation of RPM
rpm = ((float)incre_temp/42000.0)/((float)incre_time/(1000.0*60.0));
incre_temp is the differnce of pulse
incre_time is the difference of pulse as pulse changes.
I could not get the correct RPM
Please look at my code and correct me if you see the problem.
#define DIR_PIN 8
#define STEP_PIN 9
#define motorenable 10
int encoder0PinA = 2;
int encoder0PinB = 3;
volatile long encoder0Pos = 0;
volatile int encoder0PinALast = LOW;
volatile int n = LOW;
volatile int m = LOW;
int valNew = 0;
int valOld = 0;
long temp;
long incre_temp;
float rpm;
long incre_time;
long finish;
void setup()
{
pinMode(DIR_PIN, OUTPUT);
pinMode(STEP_PIN, OUTPUT);
pinMode(motorenable, OUTPUT);
pinMode (encoder0PinA,INPUT);
pinMode (encoder0PinB,INPUT);
Serial.begin (115200);
attachInterrupt(1, CountA, CHANGE);
attachInterrupt(0, StateB, FALLING);
}
void loop()
{
long pulse = 42000;
double motor_speed = 1;
int dir = (pulse < 0)? HIGH:LOW;
digitalWrite(motorenable, HIGH);
long start = millis();
digitalWrite(DIR_PIN,dir);
digitalWrite(STEP_PIN, motor_speed);
if(temp >= pulse)
{
digitalWrite(motorenable, LOW);
delay(100000);
}
Serial.print("Position: ");
Serial.println(temp);
incre_temp = abs(temp-encoder0Pos);
incre_time = finish - start;
rpm = ((float)incre_temp/42000.0)/((float)incre_time/(1000.0*60.0));
Serial.print("RPM: ");
Serial.println(rpm);
}
void CountA()
{
n = digitalRead(encoder0PinA);
if ((encoder0PinALast == LOW) && (n == HIGH))
{
if (m == LOW)
{
temp = encoder0Pos--;
finish = millis();
}
else
{
temp = encoder0Pos++;
finish = millis();
}
}
}
void StateB()
{
m = digitalRead(encoder0PinB);
}