Sketch 1
//PhotoResistor Pin
int lightPin = 0; //the analog pin the photoresistor is connected to the
//photoresistor is not calibrated to any units so
//this is simply a raw sensor value (relative light)
int ledPin = 9; //the pin the LED is connected to we are controlling brightness so
//we use one of the PWM (pulse width modulation pins)
void setup()
{
pinMode(ledPin, OUTPUT); //sets the led pin to output
}
void loop()
{
int lightLevel = analogRead(lightPin); //Read the lightlevel
lightLevel = map(lightLevel, 0, 900, 0, 255);
//adjust the value 0 to 900 to span 0 to 255
lightLevel = constrain(lightLevel, 0, 255);//make sure the value is between
//0 and 255
analogWrite(ledPin, lightLevel); //write the value
}
Sketch 2
const int NbrLEDs = 8;
const int ledPins[] = { 5, 6, 7, 8, 9, 10, 11, 12};
const int photocellPin = A0;
const int wait = 30;
// Swap values of the following two constants if cathodes are connected to Gnd
const boolean LED_ON = HIGH;
const boolean LED_OFF = LOW;
int sensorValue = 0; // value read from the sensor
int ledLevel = 0; // sensor value converted into LED 'bars'
void setup() {
for (int led = 0; led < NbrLEDs; led++)
{
pinMode(ledPins[led], OUTPUT); // make all the LED pins outputs
}
pinMode(13, OUTPUT);
}
void loop() {
//sensorValue = analogRead(analogInPin); // read the analog in value
sensorValue = analogRead(photocellPin);
ledLevel = map(sensorValue, 300, 1023, 0, NbrLEDs); // map to the number of LEDs
for (int led = 0; led < NbrLEDs; led++)
{
if (led < ledLevel ) {
digitalWrite(ledPins[led], LED_ON); // turn on pins less than the level
}
else {
digitalWrite(ledPins[led], LED_OFF); // turn off pins higher than
// the level
}
}
if (ledLevel < 3) {
digitalWrite(13, HIGH);
}
if (ledLevel > 3) {
digitalWrite(13, LOW);
}
}