AvBrand Exploring Technology
Power Monitor Source Code
This code is copyright © 2009 Avatar-X. If you use it, please let me know.
void setup() {
// Pin 13 is the blinking status LED
pinMode(13, OUTPUT);
// Pin 2 is the input from the phototransistor
pinMode(2, INPUT);
// Start serial communication
Serial.begin(115200);
}
int lastRead = HIGH; // The last reading (off)
long lastUpdate = 0; // The last time we sent an update
long counter = 0; // The current counter
// Track the rate.
long lastBlink = 0; // The last time we saw a blink
// Average blink times over 10 blinks
long blinkTimes[10];
byte currBlink = 0;
void loop()
{
int r = digitalRead(2);
if (r != lastRead)
{
lastRead = r;
if (r == LOW) // A blink has been detected.
{
counter++;
blinkTimes[currBlink] = millis() - lastBlink;
lastBlink = millis();
currBlink++;
if (currBlink > 9) currBlink = 0;
digitalWrite(13, HIGH);
} else {
digitalWrite(13, LOW);
}
}
if (millis() > lastUpdate + 1000 || millis() < lastUpdate)
{
// Send data out the serial port.
lastUpdate = millis();
Serial.print(counter);
Serial.print("\t");
Serial.println(avgBlinks());
}
}
long avgBlinks()
{
// Calculate the average time between blinks.
// This gives us the number we need to calculate the watts
long avgCounter = 0;
for (int i = 0; i <= 9; i++)
{
avgCounter += blinkTimes[i];
}
return avgCounter / 9;
}