我正在使用arduino来计算轮子的速度。我使用霍尔效应传感器。每一秒我都会用计算出的新转速更新我的速度值。如何在代码中的一秒条件之外发送数据而不影响我的计算
// 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 毫秒更新一些其他值,该怎么做? 谢谢
最佳答案
您可以使用TimeOne.h以与 AttachInterrupt() 类似的方式添加一个在 50ms 发生的 ISR。还有 Timer2 的库。定时器函数通常用于生成 PWM 或硬件引脚函数。这些库将其中断配置为溢出,并将其与相关引脚断开。
注意 Arduino Core 库使用 Timer0 来生成 1ms 中断,以更新 millis() 计数器。 Timer1 和 2 通常免费供一般使用,除非在其他第 2 方库中使用。
关于c - 中断外的Arduino串行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27621271/