ArduinoM0 Photocell and LED Example

Photocell and LED

Let's control an LED using a photoresistor!
We are going to control an LED brightness along with the light that a photoresistor receives.
The more is the light that the photoresistor receives, the more the LED brightness will be.
The Arduino board M0 operates on 3.3V. The maximum voltage that the I/O pins can tolerate is 3.3V. The application of a voltage exceeding 3.3V may damage the board.


  • LDR photocell
  • 10K Ohm
  • 220 Ohm
  • LED


The LED is connected to PIN 8, and between this link there's a resistor.
The photoresistor is connected to 3.3V and Ground respectively. The ground has also a resistor connected to it.
Then link the Ground PIN of the resistor to the Analog Input A0.
The Fritzing circuit here should clarify everything.

In the picture is shown the circuit realized using an Arduino M0 Pro.


The sketch reads the light received by the photoresistor and it converts it to a value usable to light the Led.
The value is converted in order to light the led (from an input between 0-1023 to an output of 0-255)

//Define the photoresistor PIN (A0)
int photocellPin = A0;

//This variable will contain the raw value read from photoresistor
int photocellReading;

//Define the LED PIN 8
int LEDpin = 8;

//This variable contains the brightness of the LED
int LEDbrightness;

void setup(void) {
void loop(void) {
	//Read the value from ptohoresistor
	photocellReading = analogRead(photocellPin);

	//Map the value from 0,1023 to 1023,0
	//in order to increase the LED brightness
	//along the light recevided by the photoresistor
	photocellReading = 1023 - photocellReading;

	//Map the ptohoresistor reading to 0,255
	//to set correctly the LED brightness
	LEDbrightness = map(photocellReading, 0, 1023, 0, 255);
	//Set the LED brightness
	analogWrite(LEDpin, LEDbrightness);