我正在使用arduino来计算车轮的速度。我使用霍尔效应传感器。每一秒我用它计算的新RPM更新我的速度值。如何在代码中的一秒条件之外发送数据而不影响我的计算
// read RPM
volatile int rpmcount = 0;//see http://arduino.cc/en/Reference/Volatile
int rpm = 0;
unsigned long lastmillis = 0;
void setup(){
Serial.begin(9600);
attachInterrupt(0, rpm_fan, FALLING);//interrupt cero (0) is on pin two(2).
}
void loop(){
if (millis() - lastmillis == 1000){ /*Uptade every one second, this will be equal to reading frecuency (Hz).*/
detachInterrupt(0); //Disable interrupt when calculating
rpm = rpmcount * 60; /* Convert frecuency to RPM, note: this works for one interruption per full rotation. For two interrups per full rotation use rpmcount * 30.*/
Serial.print("RPM =\t"); //print the word "RPM" and tab.
Serial.print(rpm); // print the rpm value.
Serial.print("\t Hz=\t"); //print the word "Hz".
Serial.println(rpmcount); /*print revolutions per second or Hz. And print new line or enter.*/
rpmcount = 0; // Restart the RPM counter
lastmillis = millis(); // Uptade lasmillis
attachInterrupt(0, rpm_fan, FALLING); //enable interrupt
}
}
void rpm_fan(){ /* this code will be executed every time the interrupt 0 (pin2) gets low.*/
rpmcount++;
}
我需要每50毫秒更新一些其他值,怎么做? 感谢
答案 0 :(得分:1)
您可以使用TimeOne.h以50ms的速度添加ISR,其方式与attachInterrupt()类似。还有用于Timer2的库。定时器功能通常用于生成PWM或硬件引脚功能。这些库将中断配置为溢出并将它们与相关引脚断开。
注意,Arduino核心库使用Timer0生成1ms中断,以更新millis()计数器。除非在其他第二方库中使用,否则Timer1和2通常免费供一般使用。