So I am creating a tachometer using black/white detector sensor. Here's the code.
unsigned long WaktuOLD;
unsigned long WaktuNOW;
int Detection = HIGH;
int Counter = HIGH;
float HitungWaktu;
float HitungRPM;
void setup() {
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(3), rpm, RISING);
WaktuNOW = millis();
}
void rpm() {
Detection = digitalRead(3);
if (Detection == HIGH && Counter == LOW) {
WaktuNOW = millis();
HitungWaktu = WaktuNOW - WaktuOLD;
HitungRPM = 60 / (HitungWaktu / 1000);
Counter = HIGH;
} else if (Detection == HIGH && Counter == HIGH) {
Counter = LOW;
WaktuOLD = millis();
}
}
void loop() {
Serial.println(HitungRPM);
delay(5000);
}
The code works well and it can read RPM correctly. And then from the same arduino, I am controlling a servo motor, in this case I am using GWS03N/STD/F, with this code :
#include <Servo.h>
Servo myservo;
int pos = 0;
void setup() {
myservo.attach(9);
}
void loop() {
myservo.write(90);
}
And this code works well too.
But, when I am trying to combine both codes, only the servo code is working well. The tachometer reading is not correct (the reading must be around 1000-1500rpm, but now it reads 3000-30krpm). I am already trying to change my tachometer interrupt to pin 2 or 3, and servo to 3, 5, 6, and 9 but still the same.
So what is wrong in here. Thank you so much.
This is my code when combining both codes.
#include <Servo.h>
Servo myservo;
int pos = 0;
unsigned long WaktuOLD;
unsigned long WaktuNOW;
int Detection = HIGH;
int Counter = HIGH;
float HitungWaktu;
float HitungRPM;
void setup() {
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(3), rpm, RISING);
WaktuNOW = millis();
myservo.attach(9);
}
void rpm() {
Detection = digitalRead(3);
if (Detection == HIGH && Counter == LOW) {
WaktuNOW = millis();
HitungWaktu = WaktuNOW - WaktuOLD;
HitungRPM = 60 / (HitungWaktu / 1000);
Counter = HIGH;
} else if (Detection == HIGH && Counter == HIGH) {
Counter = LOW;
WaktuOLD = millis();
}
}
void loop() {
Serial.println(HitungRPM);
myservo.write(90);
delay(5000);
}