Circuit example

In this example the LDR-sensor is connected to the power (5V) and to a pull down resistor to ground. Then the junction between the pulldown resistor and the LDR is connected to the analog input PORTC1 of the microcontroller.
The analog voltage reading is used to determine if a row of 8 LED is on or off. The darker it is, the more LED's will be on, if the light is bright the LED's will be off. The LED's have to be connected to PORTD of the ATmega328. In the example the ATMega328 board is used. The circuit can be build on a breadboard.

adc ldr sch


adc ldr pic1

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: ADC_LDR.c
* target device: ATMega328P
* Created: 15-7-2017 20:13:21
* Author :

#define F_CPU 1600000UL
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

const unsigned char level[9] = {0b00000000,0b10000000,0b11000000,0b11100000,0b11110000,0b11111000,0b11111100,0b11111110,0b11111111};

void ADC_init(void)
ADMUX |= (1<<MUX0) | (1<<ADLAR); // set ADC1, set ADC Left Adjust Result
ADCSRA |= (1<<ADEN) | (1<<ADPS2) | (1<<ADPS0); //enable ADC, set prescaler to 32

unsigned char ADC_raw(void)
ADCSRA |= 1<<ADSC; //start conversion;
while (ADCSRA&(1<<ADSC)); //wait conversion end
return ADCH;

int main(void)
DDRD = 0xFF;
unsigned int adc_data;
while (1)
adc_data = ADC_raw();
adc_data = adc_data/31;
PORTD = level[adc_data];