Module CCP1 as a PWM signal generatorThis example illustrates the use of CCP1 module in PWM mode. To make it more interesting, the width of P1A output pulses (PORTC,2) may be changed using pushbuttons symbolically marked as ‘DARK’ and ‘BRIGHT’, while the set width is visible as a binary combination on PORTB. The operation of this module is under control of the procedures belonging to the specialized PWM Library. Three of them are used here:
sub procedure PWM1_Init(const freq as longint)Parameter freq sets the frequency of PWM signal expressed in herz. In this example it is 5 KHz.
sub procedure PWM1_Start()
sub procedure PWM1_Set_Duty(dim duty_ratio as byte)Parameter duty_ratio sets pulse duration in a pulse sequence.
sub procedure PWM1_Stop()
' Header ****************************************************** program example_6 ' Program name dim current_duty, old_duty, oldstate as byte ' Define variables current_duty ' old_duty and oldstate main: ' Start of program ANSEL = 0 ' All I/O pins are configured as digital ANSELH = 0 PORTA = 255 ' PORTA initial state TRISA = 255 ' All PORTA pins are configured as inputs PORTB = 0 ' Initial state of PORTB TRISB = 0 ' All PORTB pins are configured as outputs PORTC = 0 ' PORTC initial state TRISC = 0 ' All PORTC pins are configured as outputs PWM1_Init(5000) ' PWM module initialization (5 KHz) current_duty = 16 ' Initial value of variable current_duty old_duty = 0 ' Reset variable old_duty PWM1_Start() ' Start PWM1 module while 1 ' Endless loop if oldstate and Button(PORTA, 0,1,1) then ' If the button connected to RA0 is pressed current_duty = current_duty + 1 ' increment variable current_duty if Button(PORTA, 0, 1, 1) then oldstate = 255 end if end if if oldstate and Button(PORTA, 1,1,1) then ' If the button connected to RA1 is pressed current_duty = current_duty - 1 ' decrement value current_duty if Button(PORTA, 1, 1, 1) then oldstate = 255 end if end if if old_duty <> current_duty then ' If current_duty and old_duty are not PWM1_Set_Duty(current_duty) ' equal set PWM to a new value, old_duty = current_duty ' save the new value PORTB = old_duty ' and show it on PORTB end if Delay_ms(200) ' 200mS delay wend end. ' End of programIn order to make this example work properly, it is necessary to check the following libraries in the Library Manager prior to compiling: