Go Down

### Topic: Function for incrementing variable every 1000 ms (Read 437 times)previous topic - next topic

#### steskaniarduino

##### Jun 14, 2016, 04:05 pm
Is making this Function for incrementing variable every 1000 ms good for measuring realtime power consumption in Wh . If it is what is the best way to vrite that kind of function. Thanks

#### KeithRB

#1
##### Jun 14, 2016, 04:07 pm
Don't use a function. Just put a section of loop that fires every 1000 ms. Check out Blink without delay and just increment your variable instead of blinking.

#### steskaniarduino

#2
##### Jun 14, 2016, 04:15 pm
Not sure if i know how to do it I am just beginner :S

#### aarg

#3
##### Jun 14, 2016, 04:16 pm
Not sure if i know how to do it I am just beginner :S

Did you try?
... with a transistor and a large sum of money to spend ...
Please don't PM me with technical questions. Post them in the forum.

#4

#### steskaniarduino

#5
##### Jun 14, 2016, 04:33 pm
This is code for measuring power consumption and current

Code: [Select]
`#include <LiquidCrystal.h>const int sensorIn = A0;int mVperAmp = 66; double Voltage = 0;double Power = 0;double VRMS = 0;int time = 0;double AmpsRMS = 0;LiquidCrystal lcd(12, 11, 5, 4, 3, 2);/*time counter*/unsigned long previousMillis = 0; const long interval = 1000; void setup(){lcd.begin(16,2);}void loop(){    Voltage = getVPP();VRMS = (Voltage/2.0) *0.707;AmpsRMS = (VRMS * 1000)/mVperAmp;lcd.setCursor(0,0);lcd.print("I=");lcd.print(AmpsRMS);lcd.print(" A");Power = 220*AmpsRMS;  lcd.setCursor(7,0);  lcd.print("P=");  lcd.print(Power,2);  lcd.print(" W");  unsigned long currentMillis = millis();if(currentMillis - previousMillis >=interval){ time++;}lcd.setCursor(0,1);lcd.print(whC(int time, float Power ),2)}float getVPP(){float result;int readValue; //value read from the sensorint maxValue = 0; // store max value hereint minValue = 1023; // store min value hereuint32_t start_time = millis();while((millis()-start_time) < 1000) //sample for 1 Sec{readValue = analogRead(sensorIn);// see if you have a new maxValueif (readValue > maxValue){/*record the maximum sensor value*/maxValue = readValue;}if (readValue < minValue){/*record the maximum sensor value*/minValue = readValue;}}// Subtract min from maxresult = ((maxValue - minValue) * 5.0)/1023.0;return result;}float whC(int time, float Power ){ float result; result = (Power * time)/3600; return result;}`

#### KeithRB

#6
##### Jun 14, 2016, 06:22 pm
Looks pretty good, you need to reset previousmillis inside the time check loop so it happens again 1 second later

Go Up