ArduinoGeneral

Beep and blink

userHead Account cancelled 2019-10-09 06:40:16 1008 Views1 Replies
So, actually the code is working, but not the way i want and i believe i shoud add or replace something.I tried for hours to figure out what, but i couldnt.

Actually, the green LED is continuously light up,when the light gets brighter The green LED stops and The red LED is blinking and the buzzer produces sound for 10 seconds,otherwise they are turned off and the alarm should trigger every time the light is more than the usual if it gets normal after 10 seconds stop, but the red LED dont follow the statement and it is blinking non stop.
The main code without anything added
Code: Select all
const int ledPin =  4;// the number of the LED pin
const int buzzerPin = 3;
const int LDR_IN = A2;
const int LIGHT_THRESHOLD = 82;
// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated
unsigned long toneStartMillis = 0;

// constants won't change:
const unsigned long blinkInterval = 1000;           // interval at which to blink (milliseconds)
const unsigned long toneInterval = 10000;

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, ledState);
}

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= blinkInterval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }
    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
  int brightness = analogRead(LDR_IN);
  if (brightness > LIGHT_THRESHOLD) {
    tone(buzzerPin, 440);
    toneStartMillis = currentMillis;
  }

  if ( currentMillis - toneStartMillis >= toneInterval ) {
    noTone(buzzerPin);
  }
}