我正在創建輪速傳感器的代碼,作爲更大組項目的一部分。該代碼將使用霍爾效應傳感器和附着在車輪上的磁鐵來測量和顯示自主陸地遊艇的行駛速度和行駛距離。我已經編寫了代碼,並且它自己的工作非常好。但是,當我嘗試將其添加到完整的項目代碼時,它似乎根本無法工作。唯一的區別是在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