我有和arduino草圖需要使用TimeAlarms.h庫按照定時計劃執行幾個操作。然而,其中一項操作是通過中斷讀取霍爾傳感器,似乎與TimeAlarms庫的交互性很差。 我使用TimeAlarms庫從這裏:http://www.pjrc.com/teensy/td_libs_TimeAlarms.html 而從這裏適應霍爾傳感器腳本: http://www.seeedstudio.com/wiki/G3/4_Water_Flow_sensorArduino中斷干擾TimeAlarms.h
我可以運行在其上的霍爾傳感器代碼自己的優秀。但是,當我嘗試運行霍爾傳感器代碼以及Alarm.timerRepeat
時,它在進入check_flow
函數後掛起。
運行下面的代碼只輸出enter CF
,然後掛起。如果您嘗試使用DelayAlarm TimeAlarm版本的check_flow_alarm_delay
函數,則會發生同樣的情況。
但是,如果您在設置 和Alarm.delay(0);
環路中註釋掉Alarm.timerRepeat(10, showseconds);
,則霍爾傳感器正常工作。
奇怪的是,如果你在check_flow
函數中註釋掉sei();
和cli();
,那麼腳本工作正常,並且似乎可以用霍爾傳感器正確計數。爲什麼這會工作?我應該擔心我沒有積極設置sei()
和cli()
之間的時間,從而導致傳感器出現可靠性問題?
注意:您應該可以在沒有霍爾傳感器的情況下運行代碼,輸出僅爲0 L/hr。
// reading liquid flow rate using Seeeduino and Water Flow Sensor from Seeedstudio.com
// Code adapted by Charles Gantt from PC Fan RPM code written by Crenn @thebestcasescenario.com
// http:/themakersworkbench.com http://thebestcasescenario.com http://seeedstudio.com
#include <Time.h>
#include <TimeAlarms.h>
#include <Wire.h>
volatile int NbTopsFan; //measuring the rising edges of the signal
int Calc;
int hallsensor = 2; //The pin location of the sensor
void rpm() //This is the function that the interupt calls
{
NbTopsFan++; //This function measures the rising and falling edge of the hall effect sensors signal
}
void setup() //
{
Serial.begin(9600); //This is the setup function where the serial port is initialised,
pinMode(hallsensor, INPUT); //initializes digital pin 2 as an input
attachInterrupt(0, rpm, RISING); //and the interrupt is attached
Alarm.timerRepeat(10, showseconds);
}
void loop()
{
// Serial.println(second());
// stalls at enter CF
// check_flow();
// stalls at enter CF
check_flow_alarm_delay();
Alarm.delay(0);
}
void showseconds()
{
Serial.println(second());
}
void check_flow()
{
Serial.println("enter CF");
int Calc;
NbTopsFan = 0; //Set NbTops to 0 ready for calculations
// sei(); //Enables interrupts
delay(1000); //Wait 1 second
// cli(); //Disable interrupts
Calc = (NbTopsFan * 60/5.5); //(Pulse frequency x 60)/5.5Q, = flow rate in L/hour
Serial.print (Calc, DEC); //Prints the number calculated above
Serial.print (" L/hour\r\n"); //Prints "L/hour" and returns a new line
}
void check_flow_alarm_delay()
{
Serial.println("enter CFAD");
int Calc;
NbTopsFan = 0; //Set NbTops to 0 ready for calculations
// sei(); //Enables interrupts
Alarm.delay(1000); //Wait 1 second
// cli(); //Disable interrupts
Calc = (NbTopsFan * 60/5.5); //(Pulse frequency x 60)/5.5Q, = flow rate in L/hour
Serial.print (Calc, DEC); //Prints the number calculated above
Serial.print (" L/hour\r\n"); //Prints "L/hour" and returns a new line
}
這似乎是你的問題。你可能不得不重寫你的代碼而不使用中斷。在http://stackoverflow.com/questions/36382676/arduino-uno-r3-input-pins-with-gsm-shield/36392173上查看我的回覆(附帶示例代碼) –