Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
6 years, 9 months ago.
LED and LDR using NUCLEO L073RZ
Hi, I was trying out the following code to make an LED glow in the dark automatically. After the code is run, the LED keeps glowing and the LDR value is some absurd value.
- include "mbed.h"
- define LED_PIN PA_5 SETTING LED PIN TO D13
- define LDR_PIN PB_0 SETTING LDR PIN TO A0
DigitalOut myled(LED_PIN); AnalogIn myldr(LDR_PIN);
int main() {
while(1) { int ldrstatus = myldr; if (myldr >= 3000000000) { myled = 0; printf ("LED IS OFF \n"); } else { myled = 1; printf ("LDR READING = %d \n", myldr); printf ("LDR IS DARK, LED IS ON \n");
}
} }
OUTPUT IS: LDR READING :13244420 LDR IS DARK, LED IS ON
1 Answer
6 years, 8 months ago.
MBED AnalogIn as in your code would be a floating point number from 0 to 1.0
so just reading myldr will return a 0 to 1.0 or using the member function read_u16 i.e. myldr.read_u16(); will return a 16 bit number (normalized but thats another story)
Your code with the <code> tabs as per 'editing tips'
include "mbed.h" define LED_PIN PA_5 SETTING LED PIN TO D13 define LDR_PIN PB_0 SETTING LDR PIN TO A0 DigitalOut myled(LED_PIN); AnalogIn myldr(LDR_PIN); int main() { while(1) { int ldrstatus = myldr; if (myldr >= 3000000000) {myled = 0; printf ("LED IS OFF \n"); } else { myled = 1; printf ("LDR READING = %d \n", myldr); printf ("LDR IS DARK, LED IS ON \n");} } }
edited code
include "mbed.h" define LED_PIN PA_5 SETTING LED PIN TO D13 define LDR_PIN PB_0 SETTING LDR PIN TO A0 DigitalOut myled(LED_PIN); AnalogIn myldr(LDR_PIN); int main() { while(1) { float ldrstatus = myldr;//NB changed int to float if (myldr >= 0.5f)//NB now checking against a floating point value (MID range) change to whatever value you want to activate light { myled = 0; printf ("LED IS OFF \n"); } else { myled = 1; printf ("LDR READING = %4.2f \n", myldr); printf ("LDR IS DARK, LED IS ON \n");}//NB printf data handler is now a float type %4.2f 4 characters to 2 decimal places } }
Hi,
I tried this and now the LED just keeps flickering. The terminal still shows the LDR reading as 0.00 . Is there any additional stuff I need to do to interface an LDR? Does the NUCLEO-L073RZ board not support this?
I am really new to this and would be very grateful if you could help me out.
posted by 02 Apr 2018Check wiring on the LDR please see for an example
https://os.mbed.com/users/4180_1/notebook/using-a-photocell-to-determine-light-levels/
posted by 09 Apr 2018