'jleblanc 10.29.05: control a servo with a POT
'this code controls the postion of a servo with a POT
'at pin A0 and output to servo at D2.
'written to work with a 20mhz clock

' Define ADCIN parameters
' Set number of bits in result
DEFINE  ADC_BITS        10
' Set clock source (3=rc)
DEFINE  ADC_CLOCK       3  
' Set sampling time in microseconds
DEFINE  ADC_SAMPLEUS    10       

adcVar  VAR WORD ' Create variable to store result

' Set PORTA to all input
TRISA = %11111111    
' Set up ADCON1
ADCON1 = %10000010     

PAUSE 500               ' Wait .5 second

start:
    'div will modify adcVar to output to Servo. it is set at the end
    'of start
        div VAR BYTE
    'set up constants with the minimum and maximum pulsewidths
    'NOTE: change these according to your servo. trial and error works
        minPulse CON 20
        maxPulse CON 230
    ' set up a constant with the time between pulses:
        refreshPeriod CON 20
    'clkadjust adjusts our pulse out period depending on what speed clock
    'we use. The code is default for 4mHZ in which case clkadj should
    'be 1. Since a 20mhZ runs 5 times as fast when using a 20mhz clock
    'clkadj must be set to 5
        clkadjust CON 5
    
    ' set an initial pulsewidth:
        pulseWidth = minPulse
    
    'set div. We assume adcVar varies from 0-1023
        div=1023/(maxPulse-minPulse)
    

main:
    ADCIN 0, adcVar ' Read channel 0
    
    'take the output pin low so we can pulse it high
    LOW PORTD.2
    ' pulse the pin Here we multiply by 
    PULSOUT PORTD.2, adcVar/div*clkadjust+minPulse
    ' pause for as long as needed:
    PAUSE refreshPeriod
    
GOTO main