Menu

Removing "Offset" From ReadAD10

2015-12-13
2018-02-05
  • William Roth

    William Roth - 2015-12-13

    Removing Low Range offset from READAD10 Result

    Background:
    With a PIC18F25K22 the 10-Bit ADC Result has a positive offset of 2, even when the ANx PIN is tied directly to the PIC Ground pin. With a quality 10K pot the result swings from 2 to 1023. It should swing from 0 to 1023. I am not sure if this is a problem with GCB "ReadAD10" or something else.

    How to do it:
    In any case, to remove this "offset" I used the following formula borrowed from the Arduino "MAP" command.

    return (x - inmin) * (outmax - outmin) / (inmax - inmin) + outmin

    With the values plugged in it becomes:

    adc_val = (adc_val - 2) * (1023 - 0) / (1023 - 2) + 0

    Simplified, it becomes:

    adc_val = (adc_val -2) * 1023 / 1021

    Example Code (Tested to Work):

    #chip 18F25K22, 16
    #config MCLRE = INTMCLR
    #Config XINST = OFF
    #config OSC = INTIO67
    
    ;----- Setup LCD Parameters
    #define LCD_IO 4
    #define LCD_NO_RW
    #define LCD_Speed fast
    
    ; ----- Define Hardware settings
    #define LCD_RS PORTC.2
    #define LCD_Enable PORTC.3
    #define LCD_DB4 PORTC.4
    #define LCD_DB5 PORTC.5
    #define LCD_DB6 PORTC.6
    #define LCD_DB7 PORTC.7
    
    ; ----  Pins and Variables
    DIR PORTA.5 IN
    DIM adc_val as LONG
    
    ; ----- Main body of program starts here.
    CLS
    do
        Locate  0,4
        adc_val = (ReadAD10(AN4))                 'Raw ADC reading
        adc_val = (adc_val - 2) * 1023 / 1021      'Remove Offset
        Print adc_val
        wait 1 s
        Locate 0, 4
        Print "          "
    loop
    
    END
    
     

    Last edit: William Roth 2015-12-13
  • polyconnect

    polyconnect - 2018-02-05

    Very useful stuff. Thanks !

     

Log in to post a comment.