#define ANALOG_PIN 1
#define BUTTON_PIN 8
#define LED_PIN 5
#define LED_SCALE 2.6
#define MIN_LED 150
#define LED_OFFSET 300
#define DEBOUNCE_DELAY 10
int lightLevel = 0;
bool ledOn = false;
/**
* Setup the serial communication and pin modes.
*/
void setup()
{
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
// DDRD = (DDRD | B00000100) & B11110111; // e.g. for BUTTON_PIN = 3, LED_PIN = 2
}
/**
* Read and debounce the input from the button.
*/
bool buttonPressed()
{
int button = digitalRead(BUTTON_PIN);
if(button == LOW)
{
while(button == LOW)
{
delay(1);
button = digitalRead(BUTTON_PIN);
}
delay(DEBOUNCE_DELAY);
return true;
}
return false;
}
/**
* Check the light level, make sure the light level is with range,
* set the LED brightness, if the button is pressed toggle the LED.
*/
void loop()
{
if(buttonPressed())
{
ledOn = !ledOn;
Serial.print("LED is now");
Serial.print(ledOn ? " on" : " off");
}
if(ledOn)
{
lightLevel = (analogRead(ANALOG_PIN) - LED_OFFSET)*LED_SCALE; // 10 bits
if(lightLevel > 1023)
lightLevel = 1023;
if(lightLevel < MIN_LED)
lightLevel = MIN_LED;
analogWrite(LED_PIN, lightLevel >> 2); // 8 bits
Serial.println(lightLevel);
}
else
{
digitalWrite(LED_PIN, LOW);
}
delay(100);
}