0

我正在使用 LDR 来告诉我 Arduino 是否有光。我的代码非常简单,但不是发送垃圾邮件“light light light”,我希望它说一次“light”,然后如果灯熄灭,让它说一次“No light”。从“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);
    }

}
4

2 回答 2

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);
    }
}
于 2012-12-26T19:19:11.193 回答
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");
        }
    }
}
于 2012-12-30T02:07:05.757 回答