Quote:
Originally Posted by SeanPerez
do i have to divide the rpm by 360 since my encoder has 360 positions in 1 rotation?
|
Actually, I just modified my code. I realized I had a mistake:
Code:
// Controlling a servo position using a potentiometer (variable resistor)
// by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>
#include <Servo.h>
Servo motor1; // create servo object to control a motor
Servo motor2; // ditto
int potpin = 0; // analog pin used to connect the potentiometer
int val; // variable to read the value from the analog pin
float dt;
volatile byte rpmcount;
float rpm;
unsigned long timeold;
void setup()
{
motor1.attach(9); // attaches motor 1 on pin 9 to the servo object
motor2.attach(10); // ditto
attachInterrupt(0, rpm_fun, RISING);
rpmcount = 0;
rpm = 0;
timeold = 0;
digitalWrite(2, HIGH);
Serial.begin(9600);
}
void loop()
{
val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023)
val = map(val, 0, 1023, 0, 179); // scale it to use it with the motor (value between 0 and 180)
if (rpmcount >= 20) {
dt = (float)(millis() - timeold)/1000;
Serial.print(dt);
rpm = rpmcount/dt*60;
timeold = millis();
rpmcount = 0;
Serial.print(" RPM: ");
Serial.print(rpm);
Serial.print(" Pot: ");
Serial.print(val);
Serial.print("\n");
}
motor1.write(val); // sets the motor speed according to the scaled value
motor2.write(val);
}
void rpm_fun()
{
rpmcount++;
}
At any rate, when used as an interrupt, it only counts once per revolution.