Week 9 – Light Switch and Dimmer

For this weeks homework I decided to continue my work from class and make use of the switch for the digital sensor and the light sensor for the analog one.

I decided to do quite a simple light attached to the switch, when the switch is on the light is on, when you are no longer pressing the switch, the light goes off.

Here is the simple code:

// read the input on digital pin 2:
int buttonState = digitalRead(pushButton);

// if switch is on, turn LED on
if(buttonState==1) {
  digitalWrite(8, HIGH);
}
// if switch is off, turn LED off
else {
  digitalWrite(8, LOW);
}

For the analog sensor, I wanted to do a light dimmer where the dimness corresponds to the dimness that the sensor catches. This required a bit of math and a few if statements, because it is hard to achieve very low values with a light sensor, and unless the values are very low, the LED is quite bright.

Here is the code for that below:

// read the input on analog pin A2:
float sensorValue = analogRead(A2);

// exponential value for analogLEDValue
int analogLEDValue = 25.5*pow(10,(sensorValue/950));

// some more tweaking to get a more drastic change in output
if(analogLEDValue<200) {
  analogLEDValue=analogLEDValue/2-50;
}
else if(analogLEDValue<150) {
  analogLEDValue=analogLEDValue/4-50;
}
// control so it does not go <0
if(analogLEDValue<0){
  analogLEDValue=0;
}

// output
analogWrite(6, analogLEDValue);

Here is the demo:

Leave a Reply