我正在尝试使用霍尔效应传感器和Arduino Uno构建转速计。我正在使用Arduino软件,我编写了以下代码:
#include <LiquidCrystal.h>
int sensorPin = 2; // hall effect
float revs;
float rpm;
volatile byte rpmcount;
long previousmicros = 0;
long interval = 500000;
LiquidCrystal lcd(12, 11, 6, 5, 4, 3);
void setup()
{
// setup serial - diagnostics - port
Serial.begin(115200);
// setup pins
pinMode(sensorPin, INPUT);
// setup interrupt
attachInterrupt(0, RPM, RISING);
}
void RPM()
{
rpmcount++;
}
void loop()
{
unsigned long currentmicros = micros();
int sensorValue = digitalRead(sensorPin); // sensor value is read
if (currentmicros - previousmicros > interval)
{
previousmicros = currentmicros;
detachInterrupt(0);
revs=10.0/rpmcount;
rpm =600.0/revs;
Serial.print("rpmcount : ");
Serial.print(rpmcount);
Serial.print(" rpm : ");
Serial.println(rpm);
lcd.clear();
lcd.begin(16, 2);
lcd.print("RPM = ");
lcd.setCursor(6,0);
lcd.print(rpm,0);
rpmcount=0;
attachInterrupt(0, RPM, RISING);
}
}
这可以正常工作并测量RPM,但是该值始终是60的因数。如何更改此值以便更准确地测量RPM,比如说+ -5 RPM?我尝试使用我的revs
和rpm
公式,但收效甚微。
答案 0 :(得分:0)
现在你有
rpm =60.0*rpmcount;
您必须在较长时间内存储计数并从中计算值(或更改循环的运行频率)
答案 1 :(得分:0)
在ISR中,不计算增加计数,计算自上次ISR起火后经过的时间。
unsigned long someArray[2] = {0,0};
unsigned char rpmindex = 0;
void RPM_isr()
{
rpmindex ^= 1;
someArray[rpmindex] = micros();
}
// And then in the main body
{
// Disable interrupts
// Copy someArray to a localArray
// reEnable interrupts
// Compute the interval between ISR fires
unsigned long interval = abs(localArray[0] - localArray[1]);
// Compute RPM
unsigned int rpm = (60*1000000)/interval;
}
伪代码由您自己承担风险。
编辑:关于RPM计算的错误数学。