0

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);
    }

}
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 に答える