如何在Arduino中只在循环分支下循环一段代码?

时间:2018-01-15 14:49:33

标签: loops arduino

我最近一直在努力解决一些问题。就像我在我的问题中提到的那样,我想只在loop()块下循环一段代码。我做了我的研究,并且意识到这两种常见的方法。一种是将我想在setup()块中运行一次的代码放在第二位,而第二种是在while(1)块中使用loop()语句。不幸的是,这两种方式都不适合我的代码。第一个原因是我的代码必须位于loop()部分。我无法使用第二个选项作为 all loop()块下的代码最终运行一次。就像我之前说的那样,我只希望loop()块中的部分代码运行一次。

为了您的信息,此代码的目的是在液晶显示屏上显示用户饮用以保证健康饮水量的毫升数量。例如,一个人每天最少饮用1800毫升,以保持适当的水分。如果用户饮用123ml水,则应显示LCD(1800-123)。

 //Adds the liquid crystal library 
 #include <LiquidCrystal.h>

//defines lcd pin numbers
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

// defines ultra sonic sensor pin numbers
const int trigPin = 8;
const int echoPin = 7;

// defines variables
long duration;
long volume;
long interval = 3600000; //1 hour
unsigned long stime = millis();
double pdist = 0;
double cdist = 0; 
double mcons = 4.5; //128ml;

void setup() {
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
Serial.begin(9600); // Starts the serial communication 
lcd.begin(16, 2); // Starts the lcd communication 
}

void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);

// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);

//Converting the distance to cm
double cdist = duration / 29 / 2;

//Finding volume of the water
double volume_of_rem_height = 3.14*3*3*(cdist);
Serial.println(1800-volume_of_rem_height);

//I WANT ONLY THE BELOW STATEMENT TO BE RUN ONCE. REST ALL SHOULD CONTINUE 
//TO LOOP.
lcd.print(1800-volume_of_rem_height);    

1 个答案:

答案 0 :(得分:0)

Arduino规则很简单:

  1. 当Arduino开启时,您想要完成的所有事情都需要进入rollback
  2. 其他所有内容都需要进入init(至少进入loop的callchain。)
  3. 如果你想在loop的每次迭代中想要未完成,请通过明确检查来停止Arduino这样做
  4. loop中初始化两个变量值:

    init

    currentValue = lastValue = 0; 中,检查上次迭代是否有变化,如果是,则进行显示更新:

    loop

    只有currentValue = 1800 - volume_of_rem_height if (currentValue != lastValue) { lastValue = currentValue; lcd.print (currentValue) } 从上一次迭代中真正改变后才会进行打印。