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.
' Simple PWM. ' by Tom Igoe, 2004 ' 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. ' Define ADCIN parameters DEFINE ADC_BITS 10 ' Set number of bits in result DEFINE ADC_CLOCK 3 ' Set clock source (3=rc) DEFINE ADC_SAMPLEUS 15 ' Set sampling time in uS adcVar VAR WORD ' ADC result dutyCycle var byte ' Duty cycle for PWM ' Set PORTA to all input TRISA = %11111111 ' Set up ADCON1 ADCON1 = %10000010 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