Hey, everyone!
I'm reading 240V AC from my wall outlet with Arduino. I'm successfully reading the voltage but it's fluctuating from 220V to 234V peaks. Now, when I measure the AC voltage with my multimeter I read around 235V so I've come to a conclusion that I need to save these peaks to 234V. Peaks happen every 3 seconds approximately. How do I save those highest values (peaks)?
int b;
float a,y=0;
void setup()
{
pinMode(A0,INPUT);
Serial.begin(9600);
}
void loop()
{
b=analogRead(A0);
a=(b* 0.33);
delay(100);
if(y!=a)
{
Serial.print(" analog input " ) ;
Serial.print(b) ;
Serial.print(" ac voltage ") ;
Serial.print(a/sqrt(2)) ;
Serial.println();
y=a;
}
else
delay(100);
}
Compare current reading to the previous highest value.
If it is greater, write the value of the current reading to the highest value.
Make the highest value static or global (or both)
First of all remove all the delays.
Then have a variable say called max that you keep the maximum value of the analogue read in.
So
b=analogRead(A0);
if(b > max) max = b;
Do this for your three seconds, time this using the value you get from millis()
unsigned long now = millis();
while( millis() - now < 3000) {
// do the data gathering thing as shown above
}
Then work out your voltage from the max variable, print it and reset the max variable back to zero.
Then it is the end of the loop and the process repeats.
Your could make another global variable. Call it "m" if you want, although it's better to give all your variables meaningful names. Set it to zero initially. Each time you make a new reading, compare it to m and if it is higher, set m equal to the new reading.
But by itself, the above will never allow m to go down again, even if the peaks are lower. So you could regularly reset m to be equal to the latest reading, even if that reading is lower than m. To do something regularly, you need to use millis(). Think of millis() like a stopwatch, except it ticks 1000 times per second, and you can't pause or reset it. To know when a certain amount of time has passed, you need to record the time from the stopwatch at the start of the period, then keep comparing the current time on the stopwatch with that recorded time to calculate how much time has passed. To "record" the time from millis(), store it in another global variable, which should have a type of "unsigned long".