Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <avr/sleep.h>
- #include <avr/wdt.h>
- #ifndef cbi
- #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
- #endif
- #ifndef sbi
- #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
- #endif
- /*
- #define LANG_ELECTRICITY 'E'
- #define MESG_ELEC_CURRENT 'c'
- typedef struct {
- char lang;
- char mesg;
- double power;
- double elapsedkWh;
- } Packet_t;
- */
- #define SRAM __attribute__((section(".noinit")))
- //Number of pulses, used to measure energy.
- long pulseCount = 0;
- //Used to measure power.
- unsigned long pulseTime,lastTime;
- //power and energy
- double power, elapsedkWh;
- //Number of pulses per wh - found or set on the meter.
- int ppwh = 1; //1000 pulses/kwh = 1 pulse per wh
- #define sleepmode 1
- void setup()
- {
- Serial.begin(115200);
- // KWH interrupt attached to IRQ 1 = pin3
- attachInterrupt(0, onPulse, RISING);
- cbi( SMCR,SE ); // sleep enable, power down mode
- cbi( SMCR,SM0 ); // power down mode
- sbi( SMCR,SM1 ); // power down mode
- cbi( SMCR,SM2 ); // power down mode
- }
- void loop()
- {
- //-------------------------------------------------------------
- // 1) Enter sleep mode
- //-------------------------------------------------------------
- #if sleepmode
- /*
- The 5 different modes are:
- * SLEEP_MODE_IDLE -the least power savings
- * SLEEP_MODE_ADC
- * SLEEP_MODE_PWR_SAVE
- * SLEEP_MODE_STANDBY
- * SLEEP_MODE_PWR_DOWN -the most power savings
- *
- */
- cbi(ADCSRA,ADEN); // switch Analog to Digital converter OFF
- set_sleep_mode(SLEEP_MODE_PWR_DOWN);
- // cli();
- sleep_enable();
- sleep_mode();
- sleep_bod_disable();
- sei();
- sleep_cpu();
- // The arduino is now sleeping...
- //-------------------------------------------------------------
- // 2) Program will resume from here on interrupt
- //-------------------------------------------------------------
- sleep_disable();
- sbi(ADCSRA,ADEN); // switch Analog to Digitalconverter ON
- Serial.println('P');
- Serial.println(millis(),3);
- delay(10);
- Serial.println(millis(),3);
- delay(20);
- Serial.println(millis(),3);
- delay(10);
- Serial.println(millis(),3);
- delay(10);
- #endif
- }
- // The interrupt routine
- void onPulse()
- {
- //used to measure time between pulses.
- lastTime = pulseTime;
- pulseTime= micros();
- //pulseCounter
- pulseCount++;
- //Calculate power
- power = (3600000000.0 / (pulseTime - lastTime))/ppwh;
- //Find kwh elapsed
- elapsedkWh = (1.0*pulseCount/(ppwh*1000)); //multiply by 1000 to pulses per wh to kwh convert wh to kwh
- //Print the values.
- Serial.print("W:");
- Serial.print(power,4);
- Serial.print(" kWh:");
- Serial.print(elapsedkWh,3);
- Serial.print(" C:");
- Serial.print(pulseCount,4);
- Serial.print(" LT:");
- Serial.print(lastTime,4);
- Serial.print(" PT:");
- Serial.println(pulseTime,4);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement