+ Post New Thread
Results 1 to 4 of 4
  1. #1
    Newbie level 5
    Points: 171, Level: 2

    Join Date
    Nov 2012
    Posts
    10
    Helped
    0 / 0
    Points
    171
    Level
    2

    While Loop problem using PIC12F683

    Hi guys :)

    I have a problem, hope to find help here :)

    This is a simple program to let (B1= High) if (set = 8.1)
    Unfortunately it doesn't work BUT it works only if we replaced the condition to (set<5.4 OR set<2.7).
    So, could anyone tell me what is the problem.





    double set;

    void main() {

    ANSEL =0b00100001;
    GPIO=0;
    TRISIO=0b000001; // All pins are output except pin one


    while(1){
    set=0;
    while(set<8.1){
    set+=2.7;
    }
    if(set == 8.1){
    GPIO.B1 = 1;
    }
    }
    }

    •   AltAdvertisment

        
       

  2. #2
    Super Moderator
    Points: 49,672, Level: 54
    Achievements:
    7 years registered
    keith1200rs's Avatar
    Join Date
    Oct 2009
    Location
    Yorkshire, UK
    Posts
    10,877
    Helped
    2074 / 2074
    Points
    49,672
    Level
    54

    Re: While Loop problem using PIC12F683

    2.7 and 8.1 in binary are recurring numbers so rounding errors will make a genuine equals prone to problems.

    Keith
    I started life with nothing and I've still got most of it left. (Seasick Steve)


    1 members found this post helpful.

    •   AltAdvertisment

        
       

  3. #3
    Super Moderator
    Points: 250,686, Level: 100
    Awards:
    1st Helpful Member

    Join Date
    Jan 2008
    Location
    Bochum, Germany
    Posts
    43,647
    Helped
    13274 / 13274
    Points
    250,686
    Level
    100

    Re: While Loop problem using PIC12F683

    I presume your code works according to C language specification. The problem is solely about understanding the nature of floating point numbers. Other than integer and fixed point numbers, they involve a rounding error. In the present case, matching 8.1 is missed by a very small difference. You can visualize by printing the numbers with full resolution.

    But there's a simple solution: Never test for equality with float numbers, because it possibly never happens.

    By the way, it seem pretty stupid to use float or even double (not actually supported by your compiler and casted to real, I guess) with a tiny PIC12F.



    •   AltAdvertisment

        
       

  4. #4
    Full Member level 5
    Points: 1,841, Level: 9
    Golden Electronics's Avatar
    Join Date
    May 2013
    Location
    India
    Posts
    309
    Helped
    49 / 49
    Points
    1,841
    Level
    9
    Blog Entries
    1

    Re: While Loop problem using PIC12F683

    u may insert >=8.1 instead of set==8.1



--[[ ]]--