Results 1 to 3 of 3

Thread: Strange Arduino Glitch "Or bad programing on my part"

  1. #1
    Join Date
    Dec 2008
    Location
    Washington
    Posts
    312
    Images
    35
    Rep Power
    39

    Question Strange Arduino Glitch "Or bad programing on my part"

    I am having a strange problem with my arduino sensor averaging code. Here it is.

    Code:
    int readings[20];            
    long total = 0;                    
    int average = 0;                  
    int i;
    
    int inputPin = 2;
    
    void setup()
    {
      Serial.begin(9600);               
    }
    
    void loop()
    {
      for (i=0; i<=20; i++)
      {
      readings[i] = analogRead(inputPin);
      total += readings[i];           
    }
      average = total / 20;   // calculate the average
      Serial.println(average);            
      delay(1000);
      total = 0;
    }
    Everything works fine until the program leaves the for loop. Until that point the "total" value is accurate however after leaving the for loop "total" changes to a value like 200 that raises and lowers according to the sensors reading. It would appear that after the for loop "total" takes on the value of a single sensor reading instead of 20 sensor readings. Not sure why this is happening or what to google.
    Dalton Caughell

  2. #2
    Join Date
    Dec 2008
    Location
    Washington
    Posts
    312
    Images
    35
    Rep Power
    39

    Re: Strange Arduino Glitch "Or bad programing on my part"

    I wish I could retract that last post. Fooled around and found the problem. I didn't have enough spaces to store reading because I used 20 when I should have used 21.
    Dalton Caughell

  3. #3

    Re: Strange Arduino Glitch "Or bad programing on my part"

    What about something like


    Code:
    int getAverageReading()
    {
           int total= 0;
           int count = 0;
    
           while (count < 20)
           {
                 total += analogRead(inputPin);
                 count++;
           }
        
           return temp/count;
    }

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •