كود:
/*
Pulse Width Modulation
Description: CCP module generating a PWM signal
MCU: PIC16F628A
Oscillator: XT, 4.0 MHz, MCLR Enabled
*/
sbit UP at RB0_bit;
sbit DOWN at RB1_bit;
unsigned short new_DC, current_DC;
void debounce(){
Delay_ms(300);
}
void main() {
CMCON = 0x07; // Disable comparators
PORTB = 0x00;
TRISB = 0b00000011; // RB0, RB1 input, RB3 (PWM1) output
PWM1_Init(5000); // PWM module initialization (5KHz)
new_DC = 0; // Initial value of variable Duty Cycle
current_DC = 0;
PWM1_Start(); // Start PWM1 module with Zero DC
PWM1_Set_Duty(current_DC);
do {
if (!UP){ // If the button connected to RB0 is pressed
debounce();
if (new_DC < 250) // Don't go above 250
new_DC = new_DC + 25 ; // increment Duty Cycle by 25
}
if (!DOWN) { // If the button connected to RB1 is pressed
debounce();
if (new_DC !=0) // Don't go below 0
new_DC= new_DC - 25 ; // Decrement Duty Cycle by 25
}
if (current_DC != new_DC) {
current_DC = new_DC ;
PWM1_Set_Duty(current_DC); // Change the current DC to new value
}
} while(1);
} // END main()