كود:
short LVD_flag; //low voltage detect flag
void pic_init();
void variable_init();
void sine_PWM_processing();
void low_voltage_detect();
void delay(unsigned int i);
const unsigned int pulseW[120]={345, 382, 308, 419, 271, 455, 236, 490, 201, 523, 169, 555, 138, 584, 110,
611, 84, 635, 62, 656, 42, 674, 26, 688, 14, 698, 5, 705, 1, 708, 0, 707, 2,
702, 9, 694, 20, 681, 34, 665, 52, 646, 73, 623, 97, 598, 124, 570, 153, 539,
185, 507, 218, 473, 253, 437, 290, 400, 326, 364, 363, 326, 400, 290, 437, 253,
473, 218, 507, 185, 539, 153, 570, 124, 598, 97, 623, 73, 646, 52, 665, 34, 681,
20, 694, 9, 702, 2, 707, 0, 708, 1, 705, 5, 698, 14, 688, 26, 674, 42, 656, 62,
635, 84, 611, 110, 584, 138, 555, 169, 523, 201, 490, 236, 455, 271, 419, 308, 382, 345};
unsigned int j;
unsigned int pulseN=120; //
unsigned int lvd_pos;//low voltage detect position
void variable_init();
unsigned short counter;
void variable_init()
{
LVD_flag=0;
lvd_pos=30;
}
void pic_init()
{
//PORTB init
TRISB=0x03;//PORTB direction define-- RB6,5:output RB1,0:input
PORTB=0x00;
//Analog comparater module initialization
CMCON.C2INV=1;
CMCON.CIS=1;
CMCON.CM2=0;
CMCON.CM1=1;
CMCON.CM0=0;
//PORTA init
TRISA=0xC4; //RA3:output
PORTA=0x08;
// voltage reference module initialization
VRCON.VREN=1;
VRCON.VROE=0;
VRCON.VRR=0;
VRCON.VR3=1;
VRCON.VR2=1;
VRCON.VR1=0;
VRCON.VR0=1;
}
void sine_PWM_processing()
{
counter=0;
do{
if(counter==lvd_pos) // implement the low voltage check
low_voltage_detect();
// Low level output RB6=1
PORTB=0x40;
delay(pulseW[counter]);
counter++;
// High level output RB5=1
PORTB=0x20;
delay(pulseW[counter]);
counter++;
} while(counter<pulseN);
}
void low_voltage_detect()
{
if(CMCON.C2OUT==1) //low voltage detect
{
LVD_flag=1; //set the low voltage detect flag
PORTA=0x00; //startup Buzzer
}
}
void main()
{
pic_init();
variable_init();
do{
sine_PWM_processing();
} while(1);
return;
}
void delay(unsigned int i) // 1 loop=2.82us
{
for(j=0;j<i;j++) ;
}