For loops for reading analog input

Hi guys, recently I’ve been tried to read the solar panel voltage by connecting my panel to A0. The code is work though, but I’m not sure why the reading I read in serial monitor is not what I expected.

This is the code:

float volt;
unsigned long val = 0;
unsigned long real = 0;

void setup() 
{
  
  Serial.begin(9600);// put your setup code here, to run once:
  pinMode(A0, INPUT);
}

void loop() 
{
     for(int i = 0; i < 100; i++)
    {
      val += analogRead(A0);
      delay(10);
    } 
  
   real = val / 100;
   volt = real * 5.0 / 1023;
  
   
   Serial.println(volt, 4);
   Serial.println(real, DEC);
   Serial.println();
   delay(5000);

}

The reading I get is keep adding to the previous reading, but what I expect is the serial monitor should be display the current reading without adding back the previous value. Let’s said the 1st reading is 4v and the 2nd reading is 4.2v, the serial monitor should display like 4v 4.2v but now what I get is 4v then 8.2v and so on. How can I modify my code just to show the current measure value and not the value that keep adding together with the previous value???

When do you ever reset 'val' back to zero?

Steve

Try this

float volt;
unsigned long val = 0;
unsigned long real = 0;

void setup() 
{
  Serial.begin(9600);
  pinMode(A0, INPUT);
}

void loop() 
{
     for(int i = 0; i < 100; i++)
    {
      val = analogRead(A0);
      delay(10);
      volt = val * 5.0 / 1023;
      Serial.println(volt, 4);
      real += val;
    } 
  
   volt = real * 5.0 / 1023. 0 / 100.0;
  
   Serial.println();
   Serial.println(volt, 4);
   Serial.println(real, DEC);
   Serial.println();
   delay(5000);

}

lesept:
Try this

float volt;

unsigned long val = 0;
unsigned long real = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(A0, INPUT);
}

void loop()
{
    for(int i = 0; i < 100; i++)
    {
      val = analogRead(A0);
      delay(10);
      volt = val * 5.0 / 1023;
      Serial.println(volt, 4);
      real += val;
    }
 
  volt = real * 5.0 / 1023. 0 / 100.0;
 
  Serial.println();
  Serial.println(volt, 4);
  Serial.println(real, DEC);
  Serial.println();
  delay(5000);

}

I will try it!!

slipstick:
When do you ever reset ‘val’ back to zero?

Steve

Oh yes!!! I forgot >.<

I solve it!! Thanks Steve >.< I forgot to reset the value to 0 haha!