I wrote the code below using the MikroC Pro compiler to pulse width modulate the speed of a fan. The code is written for the PIC12F683. I am not sure that this code will work and I have not teseted it; it did build sucessfully. I wanted to get some help from you all. What is happening in the code:
==>An analoge signal voltage from a temperature sensor (LM34) is entering the ADC converter on pin 7 (0 to 5 volts = 0deg far to 300deg Far)
==>Convert ADC read to a temperature value
Set PWM duty cycle. Increase in temperature increases the duty cycle.
Please help with your feedback to make it work.
Thanks,
JonathanM
Code: Select all
#include <built_in.h>
unsigned int Temp;
unsigned int adc_sample_1, adc_sample_2;
unsigned int adc_sample_3, adc_sample;
int scale_coeff = 2932;
void main() {
WDTCON = 0x0018; //Enable Watchdog timer
PWM1_Init(19530); //Initialize PWM at 19.53KHz (per pic spec-sheet allows 10bit resolution)
ADC_Init(); //Initialize ADC
ADCON0 = 0x1F; //Set VDD as Vref, ANO as analog read
TRISIO.B2 = 0; //Set pin 5 (CCP1) as output, used for PWM
TRISIO.B0 = 1; //Set pin 7 (ANO) as input, used for ADC read
while(1){
//ADC Read at ANO
adc_sample_1 = ADC_Read(0);
Delay_ms(1000);
adc_sample_2 = ADC_Read(0);
Delay_ms(1000);
adc_sample_3 = ADC_Read(0);
Delay_ms(1000);
adc_sample = (adc_sample_1 + adc_sample_2 + adc_sample_3)/3; //Take 3 sample from ADC and take the average
//Read ADC Channel 1
Temp = (adc_sample*scale_coeff)/10000; //Using Integer calculation
//PWM formular for 10 bit resolution: (Percent*1023)/100
if(Temp > 82 && Temp < 84)
{
PWM1_Set_Duty(102); //Set PWM to 10%
PWM1_Start();
}
if(Temp > 84 && Temp < 86)
{
PWM1_Set_Duty(205); //Set PWM to 20%
PWM1_Start();
}
if(Temp > 86 && Temp < 88)
{
PWM1_Set_Duty(307); //Set PWM to 30%
PWM1_Start();
}
if(Temp > 88 && Temp < 90)
{
PWM1_Set_Duty(409); //Set PWM to 40%
PWM1_Start();
}
if(Temp > 90 && Temp < 92)
{
PWM1_Set_Duty(512); //Set PWM to 50%
PWM1_Start();
}
if(Temp > 92 && Temp < 94)
{
PWM1_Set_Duty(614); //Set PWM to 60%
PWM1_Start();
}
if(Temp > 94 && Temp < 96)
{
PWM1_Set_Duty(716); //Set PWM to 70%
PWM1_Start();
}
if(Temp > 96 && Temp <98 )
{
PWM1_Set_Duty(818); //Set PWM to 80%
PWM1_Start();
}
if(Temp > 98 && Temp < 100)
{
PWM1_Set_Duty(921); //Set PWM to 90%
PWM1_Start();
}
if(Temp >= 100)
{
PWM1_Set_Duty(1023); //Set PWM to 100%
PWM1_Start();
}
else if(Temp < 82)
{
PWM1_Set_Duty(0); //Trun off PWM
PWM1_Stop();
break; //Breaks program out of the while loop and causes it to re-initialize all the registers/start over the process.
}
}
}