Hi all
I am using an Arduino Uno. I have built a circuit with one LED and one photo resistor and would like to write the code for the two to work together so that the LED oscillates between bright and dim. I don't want the LED to simply switch between a digital HIGH and LOW value, but rather to fade and brighten.
I know I can cut the photoresistor out of the equation completely and just use a for loop (or two, as in my example code) to run the brightness of the LED down and then back up, but I thought it would be cool if the LED actually switched "itself" on and off.
The problem that I am having is that the LED does go dim and then bright for the first few iterations of the loop but then gradually levels off somewhere in the middle and then stays at that level.
Any help would be much appreciated.
I've attached a photo of the circuit and below is my code:
int sensorValue;
int sensorLow;
int sensorHigh;
int brightness;
const int calPin = 13;
const int ledPin = 11;
const int sensorPin = A0;
void setup()
{
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(calPin, OUTPUT);
digitalWrite(calPin, HIGH);
digitalWrite(ledPin, HIGH);
while (millis() < 1000) {
sensorHigh = analogRead(A0);
}
digitalWrite(ledPin, LOW);
while (millis() < 2000) {
sensorLow = analogRead(A0);
}
// digitalWrite(calPin, LOW);
digitalWrite(ledPin, HIGH);
}
void loop()
{
sensorValue = sensorHigh;
while (sensorValue >= sensorLow) {
sensorValue = analogRead(A0) - 1;
delay(1000);
brightness =
map(sensorValue, sensorLow, sensorHigh, 0, 255);
analogWrite(ledPin, brightness);
Serial.print(sensorValue);
Serial.print("\n");
}
sensorValue = sensorLow;
while (sensorValue <= sensorHigh) {
sensorValue = analogRead(A0) + 1;
delay(1000);
brightness =
map(sensorValue, sensorLow, sensorHigh, 0, 255);
analogWrite(ledPin, brightness);
Serial.print(sensorValue);
Serial.print("\n");
}
}