Connect with us

Need help with loop

Discussion in 'Microcontrollers, Programming and IoT' started by Joshsinclair, Jul 7, 2015.

  1. Joshsinclair

    Joshsinclair

    3
    0
    Feb 28, 2015
    Hi
    Im having trouble writing code for a adc loop.

    What the program needs to do is update the display when the ADC value changes, Currently it is set up so every 200ms the loop restarts, reads the adc value and updates the display.
    The reason im wanting to change this is so the lcd only rewrites the value when it changes. currently the lcd flickers because it is clearing the lcd and rewriting the same value every 200ms.

    this is my current loop written in Mikroc for pic

    Code:
    //Variables
    
    float A = 1000.0;
    float B = 1001.0;
    float C = 1002.0;
    float D = 1003.0;
    flaot E = 1004.0;
    char Txt[15];
    
    //loop
    While (1){
    E = ADC_Read(2);
    D = A * ((E - B) / (C - B));
    InttoStr(D, Txt);
    Lcd_Cmd(_LCD_CLEAR);
    Lcd_Cmd(_LCD_CURSOR_OFF);
    Lcd_Out(1,1,Txt);
    Delay_ms(200);
    
    }
    Thanks Josh
     
    Last edited by a moderator: Jul 7, 2015
  2. Harald Kapp

    Harald Kapp Moderator Moderator

    9,394
    1,918
    Nov 17, 2011
    Josh,
    I took the liberty to put the code into a code-box for better readability.
    Your choice of variable names (A, B, C, D etc.) is sub-optimal :rolleyes:. Nobody but you can decipher what D=A*((E-B)/(C-B)) is doing.

    Back to the question:
    Use an additional variable to store the result of the previous ADC reading. Output only if the new reading differs from the old reading:
    Code:
    old_ADC=0;
    While (1){
    E = ADC_Read(2);
    if (old_ADC != E) // only if the new reading differs from the old reading
    {
       D = A * ((E - B) / (C - B));
       InttoStr(D, Txt);
       Lcd_Cmd(_LCD_CLEAR);
       Lcd_Cmd(_LCD_CURSOR_OFF);
       Lcd_Out(1,1,Txt);
       old_ADC = E; // set the old reading to the new reading to prepare for the next pass
    }
    Delay_ms(200);
    
    }
    Regards,
    Harald
     
Ask a Question
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.
Electronics Point Logo
Continue to site
Quote of the day

-