我有一个利用伺服库和外部中断例程的程序。据我了解,伺服库使用 Timer1 中断向伺服发送脉冲以保持位置。我想知道对 micros() 计数有什么影响,因为它在中断期间不会增加。
我的代码中的外部中断例程用于转速计。它使用 micros() 确定脉冲之间的时间。我担心 Servo 库会导致 millis() 和 micros() 计数器的漂移并使速度不准确。转速计可能必须感应 10,000 RPM 的速度,因此大约为 167 Hz。最终我将使用伺服和转速计实现 PID 控制。
volatile unsigned long period;
unsigned long microseconds;
void setup(){
Serial.begin(9600);
pinMode(tachometerPin, INPUT);
pinMode(led, OUTPUT);
attachInterrupt(0, tachometer, RISING); // set external interrupt
throttle.attach(throttlePin); // attach servo objects to pins
fuel.attach(fuelPin);
throttle.writeMicroseconds(throttle_idle); // set servo positions
fuel.writeMicroseconds(fuel_neutral);
}
void loop(){
Serial.println(calculateSpeed());
}
float calculateSpeed(){
/* Calculate speed of engine in RPM */
float s = 60.0/(period*0.000001);
return(s);
}
void tachometer() {
/* Determine time between rotations of engine (pulses from tachometer) */
period = micros() - microseconds;
microseconds = micros();
}