Circuit example

In this example the sensor is connected to the power (5V) and to a pull down resistor to ground. Then the point between the pulldown resistor and the LDR is connected to the analog input of a microcontroller.
The analog voltage reading is used to determine if the LED is on or off. The darker it is, the LED will be on, if it is light the led will be off. The LED has to be connected to a ouput pin, port PB0 of the ATmega328.In the example the ATMega328 board is used. The circuit can be build on a breadboard.

LDR sch


Program Example

This is a simple program that switch a led on or off depending the amount of light falling on the LDR. The program is written in WinAVR C-code.

M328 LDR LED WinAVR C-Code

program name: M328 LCD
date: 22-03-2015
purpose: reads the value of an LDR and switch a led on when it is dark and off when light falls on the LDR
target device: M328

#include <avr/io.h>
#include <util/delay.h>
#define F_CPU 16000000UL
#define LEDs PORTB
#define ON 0b00000001
#define OFF 0b00000000

unsigned char adc_data,level;

// this function read the value of ADC channel 0
unsigned char read_adc(void)
ADCSRA |= 1<<ADSC; //start conversion;
while (ADCSRA&(1<<ADSC)); //wait conversion end
return ADCH;

// main program
int main (void)
//adc init
ADMUX = 0b00100000; // set ADC0
ADCSRA = 0b10000111; //set ADEN, precale by 128
DDRB = 0xFF; //portb for output
adc_data = read_adc();
if (adc_data <(2*255)/5)
else if (adc_data >(2*255)/5)


return 1;