Simple PWM in PicBasic Pro
Simple PWM in PicBasic Pro
This is an example of pulsewidth modulation for the PIC. The value received from an
analog input is used to dim an LED, using the PWM command. The LED is on RD2,
and the analog in is on RA0.
The PWM command has three parameters: the pin, the duty cycle (a byte), and the
number of times to pulse the pin (a word). The duty cycle is how long the pin is on for
each cycle. If the duty cycle is 100% (255), then the pin is on all the time. A duty cycle
of 50% turns the pin on for half of each cycle, and so forth.
At 4MHz, one on-off cycle is about 5 milliseconds. A higher number of cycles makes
for smoother PWMing, but less interactivity, because the PIC does nothing else until it’s
finished all the cycles for each PWM command.
' This example takes an analog input on RA0 and uses it to generate
' a duty cycle for the PWM command. The PWM command is used
' to dim an LED on pin RD0.
output portc.3
main:
ADCIN 0, adcVar
' convert ADC value to a byte value:
dutyCycle = adcVar / 4
' PWM the LED. The third parameter is the number of
' cycles to repeat the PWM. at 4MHz, 1 cycle = 5 ms.
pwm portd.2, dutyCycle, 10
goto main