我正在使用LDR告诉我Arduino是否有光。我的代码非常简单,但不是垃圾邮件“灯光灯”,我希望它说“光”一次,然后如果灯熄灭,它就说“不亮”一次。 从“readanalogvoltage”编辑的代码:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
if (voltage > 1.5)
{
Serial.print("Light");
Serial.println();
delay(5000);
}
if (voltage < 1.5)
{
Serial.print("No Light");
Serial.println();
delay(50);
}
}
答案 0 :(得分:4)
保留一个包含最后状态的变量:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
int wasLit = 0;
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
if (!wasLit && voltage > 1.5) {
wasLit = 1;
Serial.print("Light");
Serial.println();
delay(5000);
} else if(wasLit && voltage <= 1.5) {
wasLit = 0;
Serial.print("No Light");
Serial.println();
delay(50);
}
}
答案 1 :(得分:0)
这种测试将受益于使用迟滞。特别是如果你有荧光灯,会有一些闪烁。这将导致传感器读数变化,使得它可能不会以干净的方式从<1.5变为> = 1.5。
boolean bLast = false;
const float vTrip = 1.5;
// you find a good value for this by looking at the noise in readings
// use a scratch program to just read in a loop
// set this value to something much larger than any variation
const float vHyst = 0.1;
float getLight() {
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
return voltage;
}
void setup() {
// establish the initial state of the light
float v = getLight();
bLast = ( v < (vTrip-vHyst) );
}
void loop() {
float v = getLight();
if( bLast ) {
// light was on
// when looking for decreasing light, test the low limit
if( v < (vTrip-vHyst) ) {
bLast = false;
Serial.print("Dark");
}
}
else {
// light was off
// when looking for increasing light, test the high limit
if( v > (vTrip+vHyst) ) {
bLast = true;
Serial.print("Light");
}
}
}