hey ! i have been given a school project where i have to run a motor on user input speed (accomplished ! ) and also try and verify this speed using a TACHOMETER . i used an H - bridge for motor control . my motor runs on the speed i want it to run at, ( maximum of 271 RPM on 12 V input) but my tachometer gives wrong readings and sometimes even negative values in the serial monitor . I don't understand what the problem is. Here is the code
int motor1Pin = 9; // H-bridge leg 1
int motor2Pin = 8; // H-bridge leg 2
int speedPin = 5; // H-bridge enable pin
int ledPin = 13;
int speed1 = 0;
int RPM = 0;
float value=0;
int percent;
float rev=0;
int rpm;
int oldtime=50;
int time;
void isr()
{
rev++;
}
void setup() {
Serial.begin (115200);
pinMode(motor1Pin, OUTPUT);
pinMode(motor2Pin, OUTPUT);
pinMode(speedPin, OUTPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(speedPin, HIGH);
attachInterrupt(0,isr,RISING);
digitalWrite(motor1Pin, HIGH);
digitalWrite(motor2Pin, LOW);
}
void loop()
{
Serial.println("Enter RPM");
while (Serial.available()<= 0)
{}
if (Serial.available() > 0)
{
RPM = Serial.parseInt();
if ((RPM >= 0) || (RPM < 272))
{Serial.print("speed is ");
Serial.print(RPM);
Serial.println(" RPM");
speed1 = map (RPM , 0 , 271, 0 , 255);
Serial.print("PWM value is ");
Serial.println(speed1);
Serial.println();
analogWrite (speedPin, speed1);
detachInterrupt(0);
time=millis()-oldtime;
rpm=(rev/time)*60000;
oldtime=millis();
rev=0;
Serial.println(rpm);
Serial.println(" ");
attachInterrupt(0,isr,RISING);
}
else
{ Serial.println("not possible! ");
return;
}
}
}