25 June 2011

Arduino UNO: PhotoCell - sensing light

Now that we have a Processing sketch (here) that can display sensor data, I thought it would be good to test it out with a simple Arduino PhotoCell sketch.


Here is what you will need to complete the Arduino side of the project:
  • 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.




The Fritzing sketch:















The Arduino Code:

 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
int photoRPin = 0; 
int minLight;
int maxLight;
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);
}


The Processing Sketch:  can be found here.
And this will allow you to display the value of the "adjustedLightLevel" on your computer screen, as seen below.














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.

4 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

Feel free to leave a comment :