我正在创建轮速传感器的代码,作为更大组项目的一部分。该代码将使用霍尔效应传感器和附着在车轮上的磁铁来测量和显示自主陆地游艇的行驶速度和行驶距离。我已经编写了代码,并且它自己的工作非常好。但是,当我尝试将其添加到完整的项目代码时,它似乎根本无法工作。唯一的区别是在void loop()
里面还有其他一些事情发生。我已经检查了所有的引脚和所有的代码并且进行了双重检查,我根本无法解决这个问题。它有时会产生对车轮的一个旋,然后似乎有点退出循环莫名其妙因为一旦车轮已经停止并再次启动速度则总是读0m/s
,无法弄清楚为什么这个Arduino代码不起作用?
这是对自己的代码:
int sensorPin1 = 2; // hall effect
float revs;
float rpm;
volatile byte rpmcount;
long fin_time;
long current_time;
long stop_time;
float distance;
const float circumference = 0.31416;
float groundspeed;
const float Pi = 3.14159;
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 13);
void setup()
{
Serial.begin(9600);
pinMode(sensorPin1, INPUT);
attachInterrupt(0, RPM, RISING);
}
void RPM()
{
rpmcount++;
revs++;
}
void loop()
{
lcd.clear();
lcd.begin(16,2);
lcd.setCursor(0,0);
lcd.print("GS=");
lcd.setCursor(3,0);
lcd.print(groundspeed,1);
lcd.print("m/s");
lcd.setCursor(10,0);
lcd.print("D=");
lcd.print(distance,0);
lcd.print("m");
if(rpmcount == 1)
{
current_time = time - fin_time;
rpm = ((60000)/current_time);
groundspeed = ((rpm * circumference)/60);
distance = revs*circumference;
rpmcount = 0;
fin_time = millis();
}
stop_time = millis() - fin_time;
if(stop_time >= 2000)
{
rpm = 0;
groundspeed = 0;
delay(20);
}
}
主体工程中的代码占用的确切结构相同,唯一的区别是,void setup()
和void loop()
有一堆其他的东西在他们一边对所有船舶上的其他传感器。我已经检查过代码,并且我的代码中的主算法不包含在任何其他if
循环或除if (rpmcount == 1)
以外的任何其他代码中。
有没有人有想法?
我可以上传完整的项目代码,但它是数百行,这个问题已经够长了。
是否有可能在主项目的循环内的其他代码中有条件返回? – isick
感谢您的快速响应。主项目代码中没有任何回报。只需在一个主循环内计算数据并将其显示在LCD上即可。 @isick –
当'rpmcount'大于1时会发生什么?也许你可以试试'if(rpmcount> 0)...' – Amadeus