#include"16F877.h"
#device ADC=8
#fuses HS,NOWDT,PUT,NOPROTECT,BROWNOUT,NODEBUG,NOLVP //High-speed 20Mhz
#use delay(clock=20000000) //20MHZ Crystal
void main(void)
{
signed int direction;
int delta;
int pwm;
int upperbound;
int lowerbound;
float power;
float powerold;
float voltage;
float voltagedrop;
float voltagedifference;
float measuredvoltage;
float measuredvoltagedrop;
direction=1; //Set initial direction to positive
delta=1; //Amount by which to adjust the PWM-7-bit resolution so duty step of 2%
pwm=26; //Initial position of the PWM-50% Duty Cycle with 7-bit resolution
upperbound=49; //Upper bound of the PWM%
lowerbound=1; //lower bound of the PWM%
power=0; //Initial Value of Power
setup_adc(ADC_CLOCK_DIV_32); //ADC clock
setup_adc_ports(ALL_ANALOG); //set all inputs to analog
output_low(PIN_C1); //set CCP1 output low
setup_ccp1(ccp_pwm); //setup pin CCP1 (RC2) to do PWM
setup_timer_2(T2_DIV_BY_1,12,1); //384.615kHZ
while(1)
{
delay_ms(1000); //wait 1second
set_adc_channel(0); //select RAO
delay_ms(20); //wait to read ADC
measuredvoltage=read_adc(); //Read the voltage input from ADC channel 0
set_adc_channel(1); //select RA1
delay_ms(20); //wait to read ADC
measuredvoltagedrop=read_adc(); //read the Voltage dropped across the R from ADC channel 1
voltage=measuredvoltage/51; //measured Voltage is 51 step per Volt at a Reference Voltage of 5V
voltagedrop=measuredvoltagedrop/51;
voltagedifference=voltage-voltagedrop;
currentma=voltagedifference; //Calculating Current using 1K Resistance
powerold=power; //Calculating the Power from the inputs
power=voltage*currentma;
pwm=pwm+direction*delta; //Adjust Pulse Width Modulation Value by Delta
if(power<powerold) //if at top of curve,change direction
{
direction=-direction;
continue;
}
if(power>upperbound) //if at maximum PWM.Stop here
{
pwm=upperbound;
continue;
}
if(power<lowerbound) //if at minimum PWM.Stop here
{
pwm=lowerbound;
continue;
}
set_pwm1_duty(pwm); //set PWM Mark-Space Radio to approx 50%
}
}
评论1