int brightness = 0; // our main variable for setting the brightness of the LED int ledPin = 9; // we use pin 9 for PWM int sensorPin = A5; // smoothing const int numReadings = 10; // higher is smoother but less responsive int readings[numReadings]; // the readings from the analog input int readIndex = 0; // the index of the current reading int total = 0; // the running total int average = 0; // the average int ldr; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(ledPin, OUTPUT); pinMode(sensorPin, INPUT); // set all readings to 0 on start for (int thisReading = 0; thisReading < numReadings; thisReading++) { readings[thisReading] = 0; } } void loop() { ldr = analogRead(sensorPin); // brightness = ldr; // don't do this //filtering jitteryness int smoothed = smooth_sensor(ldr); //Serial.println(smoothed); //clamping the range // n.b. the actual values, calibrate! brightness = map(ldr, 0, 1023, 0, 255); Serial.println(brightness); analogWrite(ledPin, brightness); delay(1); } int smooth_sensor(int sensor_value) { // subtract the last reading: total = total - readings[readIndex]; // read from the sensor: readings[readIndex] = sensor_value; // add the reading to the total: total = total + readings[readIndex]; // advance to the next position in the array: readIndex = readIndex + 1; // if we're at the end of the array... if (readIndex >= numReadings) { // ...wrap around to the beginning: readIndex = 0; } // calculate the average: average = total / numReadings; return average; }