The program uses Timer2 as a counter and timer set up to increment every 8us (prescaler = 16) and will provide a Period of 2048us (256 x 8us). We can create an ON-OFF cycle within that period by using the ADC reading in its 8-bit form. You can create an accurate 8-bit reading by shifting the 10-bit result left into the ADRESH register. This is easily done by setting ADCON1.7 = 0. Comparing the Timer2 value to the ADC value and we can effectively control the ON and OFF duty cycle within the 2048us (488 Hz).
Enjoy.
Code: Select all
{
****************************************************************
* Name : ADC2PWM.BAS *
* Author : Warren Schroeder alias "xor" *
* Notice : Copyright (c) 2006 Warren Schroeder *
* : All Rights Reserved *
* Date : 11/18/2006 *
* Version : 1.0 *
* ; *
* Notes : Simple demonstration using an 8-bit ADC reading *
* : to do LED dimming using PWM techniques *
* ; Tested using a 18F452 @ 8MHz on an EasyPIC3 *
* : Development Board connected to 8 LED's on PortB *
****************************************************************
}
Device = 18F452
Clock = 8
Include "ADC.bas"
TRISA = 4 ' RA2/AN2 as input
LATB = 0 ' initialize PortB output register
TRISB = 0 ' PortB is all outputs
T2CON = 7 ' Timer2 is ON and Prescaler=16; Timer2 increments every 8us
ADCON1 = 66 ' left justify; TOSC=16; AN0 to AN5 enabled
Repeat ' start routine
If ADC.Read(AN2) <> 0 Then ' read ADC2 and store 8 bit result in ADRESH
TMR2 = 0 ' initialize Timer2
Repeat
LATB = 255 ' turn on PortB
Until TMR2 = ADRESH ' keep ON until Timer2 is ADC value
Repeat
LATB = 0 ' turn off PortB
Until TMR2 = 0 ' keep OFF until Timer2 increments to rollover
End If
Until 0=1 ' do all again