Hi my friends and i are trying to make a code for a street lamp that increases the number of LEDs that come on as it gets the environment gets darker.
At lowest light LDR reading we have all 6 LEDs on. At brightest LDR reading no lights on, with every integer in between.
We have:
1 LDR
6 LEDs
Our circuit is working fine butwe are struggling with the code.
Any suggestions/code ideas or simplifications would be really appreciated!
This is what we have so far. Is this the easiest way to do it?
Code:
/* This is a street light code where a detected change in an LDR causes a number of LEDs
to turn on/off. As the light get dimmer the brightness emitted by the LEDs increase.
The LDR is connected to pin B4, the LEDs are connected to pins B2, B0, D6, D4, D2 and D0.
The LEDs are wired to light with logic 1.
*/
#include <16f877a.h>
#device ICD=TRUE
#fuses HS,NOLVP,NOWDT,PUT
#use delay (clock=20000000)
#define LDR PIN_B4
#define LED1 PIN_B2
#define LED2 PIN_B0
#define LED3 PIN_D6
#define LED4 PIN_D4
#define LED5 PIN_D2
#define LED6 PIN_D0
void light_one_led(int led) // define a function to be called from main
{
Output_low(LED1); // turn OFF all LEDs
Output_low(LED2);
Output_low(LED3);
Output_low(LED4);
Output_low(LED5);
Output_low(LED6);
Switch(led) // use Switch/Case statements to select LED
{
Case 0 : output_c(LED1, (reading * 6)); break; //output_c?
Case 1 : output_high(LED1);
output_c(LED2, (reading - 42 * 6)); break;
Case 2 : output_high(LED1);
output_high(LED2);
output_c(LED3, (reading - 84 * 6)); break;
Case 3 : output_high(LED1);
output_high(LED2);
output_high(LED3);
output_c(LED4, (reading - 126 * 6)); break;
Case 4 : output_high(LED1);
output_high(LED2);
output_high(LED3);
output_high(LED4);
output_c(LED5, (reading - 168 * 6)); break;
Case 5 : output_high(LED1);
output_high(LED2);
output_high(LED3);
output_high(LED4);
output_high(LED5);
output_c(LED6, (reading - 210 * 6)); break;
}
}
void main( )
{
int reading;
Setup_adc_ports (RA0_Analog); // B4 Pin?
Setup_adc (ADC_CLOCK_INTERNAL); // Setup ADC
Set_adc_channel ( 0 ); // B4 Pin?
while(TRUE)
{
reading = read_adc( );
if (reading >=0)&&(reading <42)
light_one_led(0); // LED 1 dimming
else if (reading >=42)&&(reading <84)
light_one_led(1); // LED 1 on, LED2 dimming
else if (reading >=84)&&(reading <126)
light_one_led(2); // LEDs 1 and 2 on, LED3 dimming
else if (reading >=126)&&(reading <168)
light_one_led(3); // LEDs 1 - 3 on, LED4 dimming
else if (reading >=168)&&(reading <210)
light_one_led(4); // LEDs 1 - 4 on, LED5 dimming
else
light_one_led(5); // LEDs 1 - 5 on, LED6 dimming
}
}