Now we can create our nightlight. The code on the right shows how this works. I have created a simple loop which compares the light reading with a constant value and then sets the lights (which are represented by all the bits in PORTB) accordingly. Note that because the reading from the ADC is larger when the light dependent resistor is darker I have to perform my condition appropriately.
I have made the program slightly easier to change by using a #define
value to represent the threshold for the change in the light. You may need to change this value depending on the sensitivity of your sensor and the ambient conditions.
#define THRESHOLD 300
void main ( void )
{
int v;
setup_hardware () ;
while (1) {
v = read_adc0();
if ( v < THRESHOLD ) {
PORTB = 255 ;
}
else {
PORTB = 0 ;
}
}
}
This is the final code, it is very simple. Note that I have the else condition which makes sure the light is turned off when the external light is found again.