#include <16f876.h>
#device *=16 ADC=10
#use delay(Clock=20000000)
#fuses XT, NOWDT, NOPROTECT, NOPUT, NOBROWNOUT,NOLVP
#define BATTERY_CHARGED 63
#define night_voltage 61
float mean_adc(byte channel) // Reads the adc port 30 times and gives the mean value
{
int i,mean_total = 30;
float mean = 0,mean1 = 0;
set_adc_channel(channel);
delay_us(100);
for (i=1; i<=mean_total; i++)
{
mean =mean + read_adc();
delay_us(100);
mean1=(mean/mean_total);
}
return(mean1);
}
main()
{
const byte current_channel = 0; // sets the channel one to read solar panel current
const byte voltage_channel = 1; // set to read solar panel voltage
const byte voltage_battery_channel=2;
const byte current_battery_channel=4// set to read battery voltage
float current; // initialising variables
float battery_voltage;
float voltage;
float power_new = 0.0;
float power_old= 0.0;
long duty_change = 1;
long pwm_value;
setup_adc_ports(ALL_ANALOG); // setting up all port a as analog
setup_adc(adc_clock_div_32);
setup_ccp1(CCP_PWM);
setup_timer_2(T2_DIV_BY_1, 99, 1);// pwm frequency 50KHz
set_pwm1_duty(60)
delay_ms(1000);
while(TRUE) {
current = mean_adc(current_channel);
voltage = mean_adc(voltage_channel);
battery_voltage=mean_adc(voltage_battery_channel);
battery_current=mean_adc(current_battery_channel);
power_new = current * voltage;
if (battery_voltage > 517 || battery_current>670) // 517 corresponding to 14.4 battery voltage and 670 corresponding to 3A
{
set_pwm1_duty(0);
output_high(battery_charged);
}
if (power_old >= power_new) {
duty_change -= duty_change; // decrease duty cycle
}
else if (power_old<power_new)
{
duty_change += duty_change; // increase duty cycle
}
power_old = power_new;
pwm_value =pwm_value+ duty_change;
if (pwm_value > 160)// maximum duty cycle
{
pwm_value = 160;
}
else if (pwm_value< 36) // duty cycle minimum
{
pwm_value = 36;
}
if (voltage<429)//429 CORRESPONDING TO 12V
{
pwm_value=0;
out_high(night_voltage);
}
set_pwm1_duty(pwm_value);
delay_ms(1000);
} // end of while
} //end main