25 June 2011

Arduino UNO: PhotoCell - sensing light

In this tutorial, we will send the analog readings obtained from a Photo Resistor, also known as a Light Dependent Resistor (LDR), to the computer. We will display the each reading on the monitor using a simple Processing sketch.


Here is what you will need to complete the Arduino side of the project:

Parts Required:

  • PhotoCell (or PhotoResistor)
  • 10K resistor
  • Breadboard
  • Arduino UNO
  • 3-4 wires(to connect it all together)
  • USB cable to upload sketch and for Serial communication with Processing.


Fritzing sketch:



Arduino Sketch


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* ==========================================================
Project : Send Photo resistor values to computer
Author: ScottC
Created: 25th June 2011
Description: This sketch will make the arduino read Photo resistor
             values on analog pin A0. The analog readings will
             be dependent on the amount of light reaching the
             sensor. The Analog readings will be sent to the
             computer via the USB cable using Serial communication.
==============================================================
*/

int photoRPin = 0; 
int minLight;          //Used to calibrate the readings
int maxLight;          //Used to calibrate the readings
int lightLevel;
int adjustedLightLevel;

void setup() {
 Serial.begin(9600);
 
 //Setup the starting light level limits
 lightLevel=analogRead(photoRPin);
 minLight=lightLevel-20;
 maxLight=lightLevel;
}

void loop(){
 //auto-adjust the minimum and maximum limits in real time
 lightLevel=analogRead(photoRPin);
 if(minLight>lightLevel){
 minLight=lightLevel;
 }
 if(maxLight<lightLevel){
 maxLight=lightLevel;
 }
 
 //Adjust the light level to produce a result between 0 and 100.
 adjustedLightLevel = map(lightLevel, minLight, maxLight, 0, 100); 
 
 //Send the adjusted Light level result to Serial port (processing)
 Serial.println(adjustedLightLevel);
 
 //slow down the transmission for effective Serial communication.
 delay(50);
}

Arduino Sketch Explanation:

Serial.begin(9600) : starts the serial communication between the Arduino and Processing
lightLevel=analogRead(photoRPin) : take a reading from the analog pin 0.
minLight and maxLight: automatically adjust the minimum and maximum range of the sensor
adjustedLightLevel: used to map the reading from the PhotoCell to a value between 0-100.

The adjustment of the light level is not necessary, and could be handled in Processing instead.
The delay(50) at the end of the sketch, is only used to slow down the transmission of the Serial messages to Processing. Depending on what you want to do with the sensor data, you may wish to increase or decrease the amount of delay.



 Processing Sketch

Here is a very basic Processing Sketch that will allow you to receive data from the Serial port attached to the Arduino and display the reading on your computer screen. In my case, the Arduino is connected to COM13. You may need to change this if you decide to follow in my footsteps.

The processing sketch will look for the line feed character ' \n' coming from COM13, which will trigger a serialEvent(). You can get processing to look for another character if you want to: just change the character within the bufferUntil() command. The draw() method is made redundant because the screen updating is handled by the serialEvent() in response to serial data communication with the Arduino UNO.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/* ============================================================
Processing Version: 2.2.1
Project: Display Sensor data on computer screen
Author:  ScottC
Created: 25th June 2011
Description: This Processing sketch will allow you to display
             sensor data received from the Arduino via the
             serial COM port (or USB cable).
=============================================================== */
import processing.serial.*;
Serial myPort;
String sensorReading="";
PFont font;


void setup() {
  size(400,200);
  myPort = new Serial(this, "COM13", 9600);
  myPort.bufferUntil('\n');
  font = createFont(PFont.list()[2],32);
  textFont(font);
}

void draw() {
  //The serialEvent controls the display
}  

void serialEvent (Serial myPort){
 sensorReading = myPort.readStringUntil('\n');
  if(sensorReading != null){
    sensorReading=trim(sensorReading);
  }

  writeText("Sensor Reading: " + sensorReading);
}


void writeText(String textToWrite){
  background(255);
  fill(0);
  text(textToWrite, width/20, height/2);   
}

This is how the data will be displayed on the computer screen:

If this tutorial helped you, please support me here:



22 comments:

  1. I want to to connect simulink model of AUV to arduino ,sensors and actuators and want technical details of it

    ReplyDelete
    Replies
    1. Hi Anonymous,
      Sounds like an interesting project, but have never used Simulink, and have never heard of it until I saw your comment. Perhaps try the Arduino Forums and draw from collective intelligence. Sorry I could not help.

      Delete
  2. i want to use a Ledpin in it

    ReplyDelete
    Replies
    1. Have a look at some of my other tutorials. There is one that uses an LED pin.

      Delete
  3. I'm trying to make a light sensing car, can I used what you have produced to do so?

    ReplyDelete
  4. ​I am trying to set up multiple light sensors that will trigger sound. I'm using both arduino and processing.. Does anyone know what I should put into y code to allow this to happen? The bit that sorta says "if light sensor 1 reads value 0, trigger sound1'. I've tried this multiple times but doing it with more than one sensor doesn't seem to work. Hope someone can help or direct me where else to look!

    ReplyDelete
    Replies
    1. Hi Jennifer,
      Without knowing exactly what "doesn't seem to work", it is very hard to help you.
      If you post your code to the ArduinoBasics Forum, I can have a look and will do my best to make recommendations. Make sure to click the "Help me with my project" link before adding a new topic to the forum.

      Delete
  5. Hey Scott,

    My serial port is COM3, so I changed the sketch to: myPort = new Serial(this, "COM3", 9600); but I keep receiving an error of 'variable or field 'serialEvent' declared void. Any suggestions?

    ReplyDelete
    Replies
    1. Please post your code to the ArduinoBasics Forum
      and I will have a look

      Delete
    2. Do the first and the second set of codes have to be together or they work separately? i just did a copy paste for a fast try and changed the port to COM1. something in the second set of codes do not work.

      Delete
    3. The first set of code is entered into the Arduino IDE and uploaded to your Arduino Board. This code can work independently of the Processing sketch. You just have to open the Serial monitor to have a look at the data being sent by the Arduino.

      The second set of code is a Processing sketch. You need to enter this sketch into the Processing IDE which is compiled and run on your computer (not uploaded onto the Arduino). The processing sketch allows you to view the sensor reading as displayed in the picture above.

      Delete
    4. There is also a possibility that the processing code may not work with the latest version of Processing... but should work with version 2.2.1
      Some modification may be required to work with the latest version of Processing, but I have not used the latest version to test this out. This tutorial was created back in 2011.

      Delete
    5. thank you, i will continue trying.

      Delete
  6. Hi I want to make a model which will start rotating once any one wave hand in front of it (using proximity sensor ) and the motor would stop at the point where the light sensor will detect black color and as soon as the motor stops a video start playing on the other side and again as the video stops the motor starts rotating

    ReplyDelete
  7. How can I update the Processing code for this to work in 3.0.1? Anybody have any ideas?

    ReplyDelete
  8. hi, I am trying to use photocell conductor to detect different color light. do someone has an idea about it?

    ReplyDelete
    Replies
    1. I don't think it will detect different colours (if you are talking about the common photocells - like the one in this tutorial).
      You can however, use an LED to detect a specific wavelength of light, but that is a bit different... I have a couple of tutorials which show how this is done, but they are quite old now, and there are probably much better ways of doing this now.

      Delete
    2. Hi Scott, where might I find your tutorials of using LED as detectors?

      Delete
    3. Hi Mike:

      I have a number of tutorials based around this concept.
      The tutorials are quite old - so I hope they still work with the current version of Processing and Arduino IDE.

      Here are some links:
      Arduino Uno LED sensor Part 1

      Arduino UNO - LED sensor Part 2<



      And then I have a more complicated tutorial which involves the use of a Neural Network to detect colour using LEDs as detectors.
      Colour Detection - the concept
      And you can follow that to get to the Neural network tutorials.

      Hope that helps.

      Delete

Feel free to leave a comment about this tutorial below.
Any questions about your particular project should be asked in the ArduinoBasics forum.

Comments are moderated due to large amount of spam.