今天我向您提出一个关于我的项目的程序问题,该项目使用光作为墙上伺服系统的输入。光线进入房间,阴影就会下降,而在没有光线的情况下,阴影就会退去。我想在arduino代码中的void循环中设置两个条件仅适用一次,除非条件发生变化。我这么说的意思是,我希望这个空循环不断运行,其中我有两个条件。如果连续两次满足相同的条件(即传感器读数在 800 到 10000 之间,例如 5000,然后在 6032),则不会运行任何内容。如果满足一个条件,然后再满足另一个条件,那就可以了。这是我的代码,以及有关我应该使用哪些参考命令或我的下一步行动的任何帮助,我们将不胜感激。
// Reports the frequency from the TSL230, higher number means brighter
// Part: http://www.sparkfun.com/products/8940
// Article: http://bildr.org/2011/08/tsl230r-arduino/
#include <Servo.h>
Servo myservo1;
int TSL230_Pin = 4; //TSL230 output
int TSL230_s0 = 3; //TSL230 sensitivity setting 1
int TSL230_s1 = 2; //TSL230 sensitivity setting 2
int TSL230_samples = 30; //higher = slower but more stable and accurate
void setup(){
Serial.begin(9600);
setupTSL230();
pinMode(5,OUTPUT);
}
void loop(){
float lightLevel = readTSL230(TSL230_samples);
Serial.println(lightLevel);
if(lightLevel>800 && lightLevel<1000)
{
myservo1.attach(5);
myservo1.writeMicroseconds(1300);delay(1000);
myservo1.writeMicroseconds(1500);delay(5000000);
}
else if(lightLevel<800)
{
myservo1.attach(5);
myservo1.writeMicroseconds(1700);delay(5000);
myservo1.writeMicroseconds(1500);delay(5000000);
}
}
void setupTSL230(){
pinMode(TSL230_s0, OUTPUT);
pinMode(TSL230_s1, OUTPUT);
//configure sensitivity - Can set to
//S1 LOW | S0 HIGH: low
//S1 HIGH | S0 LOW: med
//S1 HIGH | S0 HIGH: high
digitalWrite(TSL230_s1, LOW);
digitalWrite(TSL230_s0, HIGH);
}
float readTSL230(int samples){
//sample light, return reading in frequency
//higher number means brighter
float start = micros();
int readings = 0;
while(readings < samples){
pulseIn(TSL230_Pin, HIGH);
readings ++;
}
float length = micros() - start;
float freq = (1000000 / (length / samples)) * 10;
return freq;
}
首先将其添加到您的设置中...
void setup(){
Serial.begin(9600);
setupTSL230();
pinMode(5,OUTPUT);
myservo1.attach(5);
}
然后创建一个新变量并将其添加到 if 语句中
Boolean once; // declare this with your other int variables
if(lightLevel > 800 && lightLevel < 1000 && once==True)
{
myservo1.writeMicroseconds(1300);delay(1000);
myservo1.writeMicroseconds(1500);delay(1000);
once = False;
}
else if(lightLevel<800 && once == False)
{
myservo1.writeMicroseconds(1700);delay(5000);
myservo1.writeMicroseconds(1500);delay(1000);
once = True;
}