unsigned int i; unsigned long t1,t2,t3; unsigned long tt1,tt2,tt3; float instV,instI; float sumV,sumI,sumP; float Vrms,Irms,realPower,avaragePower,powerFactor,kWattHrs; float Iscale,Vscale,Pscale; float adc2V; unsigned long vPeriod,vPeriodSum,vLastZeroMsec,vPeriodCount; float fpVLastValue, freq; float sqV,sqI; float peakV,peakI; void setup() { Serial.begin(115200); Serial.println("Start"); adc2V = 0.512 / 1024.0; Vscale = 4844401 / 1000; Iscale = 1 / (0.025 * 0.025) / 1000; Pscale = 2201.0 / 0.025 / 1000; } void loop() { t1 = millis(); for(i=1; i<1001; i++) { instI=(adc2V*analogRead(0))-0.256; instV=(adc2V*analogRead(1))-0.256; sqV = instV*instV; sqI = instI*instI; sumV=sumV+sqV; sumI=sumI+sqI; sumP=sumP+(instV*instI); if (sqV>peakV) peakV = sqV; if (sqI>peakI) peakI = sqI; if (fpVLastValue < 0 && instV >= 0) { vPeriod = millis() - vLastZeroMsec; if (vPeriod > 0) { vPeriodSum += vPeriod; vPeriodCount++; } vLastZeroMsec = millis(); } fpVLastValue = instV; delayMicroseconds(669); } t2 = millis(); t3 = t2 - t1; Vrms = sqrt( Vscale * sumV ); Irms = sqrt( Iscale * sumI ); realPower = Pscale * sumP; avaragePower = Vrms * Irms; powerFactor = realPower / avaragePower; kWattHrs += realPower / 3600000.0; freq = (1000.0 * vPeriodCount) / vPeriodSum; vPeriodSum=0; vPeriodCount=0; tt2=millis(); tt3=tt2-tt1; tt1=millis(); Serial.print((int)realPower); Serial.print("A"); Serial.print((int)avaragePower); Serial.print("B"); Serial.print((int)(powerFactor*1000)); Serial.print("C"); Serial.print((int)(freq*100)); Serial.print("D"); Serial.print((int)Vrms); Serial.print("E"); Serial.print((int)(Irms*1000.0)); Serial.print("F"); Serial.print((int)sqrt(4004001.0*peakV)); Serial.print("G"); Serial.print((int)(sqrt((1/(0.025*0.025))*peakI)*1000)); Serial.print("H"); Serial.print(t3); Serial.print("I"); Serial.print(tt3); Serial.print("J"); sumV=0.0; sumI=0.0; sumP=0.0; peakV=0.0; peakI=0.0; }