The code's purpose is to change from one led to another if the LDR detects a certain level of light for a given time. Currently, since I cannot wait 5 minutes to complete one circuit, each LED should be on for 1000 ms. At one stage in the code, there are no LEDs on. The LEDs should not turn on until the LDR has sensed no light and then light levels necessary for the code to restart.
Here is the code;
const int buzzer=3;
const int ldr = A4;
void setup () {
Serial.begin(9600);
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
pinMode(buzzer, OUTPUT);
pinMode(ldr, INPUT);
}
void loop() {
int ldrStatus = analogRead(ldr);
if (ldrStatus >= 300) {
digitalWrite(13, HIGH);
delay(1000);
} else {
noTone(buzzer);
digitalWrite(13, LOW);
digitalWrite(12, LOW);
}
if (ldrStatus >= 300) {
digitalWrite(13, LOW);
digitalWrite(12, HIGH);
tone(buzzer, 100, 30);
delay(1000);
tone(buzzer, 100);
digitalWrite(12, LOW);
digitalWrite(13, LOW);
} else {
noTone(buzzer);
digitalWrite(13, LOW);
digitalWrite(12, LOW);
}
}
I have realised that the purpose of my code is unclear. What happens is one LED turns on when the LDR senses light. If the light continues, then the buzzer will sound once and the LED will change to a different colour LED. If the LDR continues to detect light, then all LEDs will turn off and the buzzer will sound continuously. The only problem is that the code doesn't stop until the LDR has sensed a high enough decrease in light levels.
1 Answer 1
You have a couple of issues in your code.
Analog inputs are versatile and (most) can be used as digital inputs (ie. on/off). For this application you are after the analog value of the LDR, however this is not how you have implemented it. You are declaring the LDR pin as a digital pin by pinmode(ldr, INPUT)
. Delete this line altogether. For reference, see the analog read documentation.
Secondly you have two if
statements that are the same.
if (ldrStatus>=300) {
digitalWrite(13, HIGH);
and
if (ldrStatus>=300) {
digitalWrite(13, LOW);
I suspect that one of them is supposed to be a less than <
sign.
Both LEDS are off beause it is executing this section of code:
}else{
noTone (buzzer);
digitalWrite (13, LOW);
digitalWrite (12, LOW);
}
I suggest you add Serial.println()
lines (documentation here) to your code for debugging. Particularly helpful would be to add it in the if
and else
statements as well as adding Serial.println(ldrStatus)
as follows:
int ldrStatus=analogRead(ldr);
Serial.println(ldrStatus);
if (ldrStatus>=300) {
Refer to this document on how to open your Serial Monitor in the Arduino Software (IDE).
Bonus Hint:
You can auto-format your code by using ctrl + T
. See this article for more info.
Zoe Melck
and you edited the question asZoe
.... please click theFlag
button at bottom of your question and clickmoderator intervention
and request to merge your accounts