How it works in short
In the hall of our apartment there's a fusebox and a little box which has a little LED which blinks each time 1 watt hour has been used. A record is saved to the database every time there's a blink and the statistics are then published on a little website which is running from the Raspberry Pi.
This is what the statistics and the graph look like on my smart phone.
This is how the installation itself looks like.
First of all you need some parts
1. A Raspberry Pi with an SD-card and power adaptor, which can be purchased from Farnell (Delivery 1-2 days). Optional: You can also buy a WiFi dongle and a shell with it.
A slice of Pi :) (version B)
2. If you don't want to solder directly on the Raspberry Pi's GPIO interface, I would recommend buying some Female-to-Female Jumper Wires.
Lesbian Jumper Wires
3. Light-dependent resistor
Photocells are sensors that detects light. They are small, inexpensive, low-power, easy to use. They are often called CdS cells or photoresistors.
Light-dependant resistor (CdS cell / photoresistor)
This component works like a very precise battery, which is good to convert voltages to time as we know how long it will take to discharge.
1uF capacitor
Let's get connected
I use coloured Jumper Wires to connect it all up as it's easier to hook up and I can refer to the Jumper Wire by colour in these instructions.- Connect a red Jumper Wire to the 3.3 VDC power (P1, see below) on the Raspberry Pi and the other end to the Light-dependent resistor.
- Connect a green Jumper Wire to the other leg on the Light-dependent resistor and to the plus (+) side (long leg) of the 1uF capacitor.
- Connect a blue Jumper Wire from the same (long leg, (+ side)) of the 1uF capacitor to the GPIO (P12) on the Raspberry Pi. Connecting two Jumper Wires to one leg of a component can be done by jumping a 1cm long leg from another component or by making a make-shift Jumper Wire.
- Connect a black Jumper Wire from the minus (-) side (short leg) of the 1uF capacitor to the Ground (P6) on the Raspberry Pi. Use some tape to cover exposed parts around the capacitor
The GPIO interface for pin placement on the Raspberry Pi (eg P1)
It should now look like this.
Before you power on the Raspberry Pi, check everything is connected in the right way, otherwise you might damage your Pi.
5. Place the Light-dependent resistor so it faces towards the blinking LED on the power meter.
6. Cover the LED and Light-dependent resistor with black tape or simply make the tape black so light from the surrounding environment wouldn't interfere with the system.
If it doesn't kinda look like this when it's all hooked up then you've done it wrong son!
7. Connect the Raspberry Pi to your local network with a wireless USB dongle or simply with a network cable.
That was the hardware part, now it's time for a cuppa!
The software!
1. The solution can run on any Linux distribution but some specific modules are needed, so it's easier just to install the Adafruit Raspberry Pi Educational Linux-distro2. When the operating system is installed into the SD-card, put it in the Raspberry Pi, connect the screen and keyboard then turn it on. Run $ sudo raspi-config to change timezone, change locale, enable ssh, change password, and expand the filesystem.
Then log in to your Raspberry Pi through SSH and install the required modules and applications:
$ sudo apt-get install python-dev
$ sudo apt-get install python-setuptools
$ sudo easy_install rpi.gpio
$ sudo apt-get install mysql-server-5.5
$ sudo apt-get install python-mysqldb
$ sudo apt-get install phpmyadmin
$ sudo apt-get install apache2
$ sudo apt-get install nano
3. Then download and install the Cheappowermeter application
$ wget https://www.dropbox.com/s/xcb2ntrt2d3xlkd/Cheappowermeter.tar.gz
$ tar -xvvzf Cheappowermeter.tar.gz
$ sudo cp Cheappowermeter/www/* /var/www -R
$ sudo rm /var/www/index.html
PS: The code is available at GitHub please contribute.
https://github.com/comzone/cheappowermeter
If you want to see if the light-sensor is working then you can run:
$ sudo /var/www/cheappowermeter-Python/./debug
This script outputs the light values and is very handy if you need to know the light values for calibration later on.
4. Now you have to set up the database: Open a web-browser and go to your Raspberry Pi's MySQL interface (http://<the ip address>/phpmyadmin) or use $ mysql direct from the console.
If you don't know the IP-address simply run $ ifconfig | grep inet
5. Run the following SQL sentences to add a database, table and a user.
Remember to change "yourpasswordhere" to your own password.
CREATE DATABASE measurepower;
CREATE USER 'measurepower'@'localhost' IDENTIFIED BY 'yourpasswordhere';
GRANT ALL ON measurepower.* TO 'measurepower'@'%';
Log off and log on again with your new username measurepower and your new password and do:
CREATE TABLE IF NOT EXISTS `watthours` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`datetime` datetime NOT NULL,
`lightvalue` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;
6. We now have to change the passwords in the application so it fits the ones you've just made. Run this in your console:
$ sudo nano /var/www/cheappowermeter-Python/readlight
Then find this line and change the password.
con = mdb.connect('localhost', 'measurepower', 'yourpasswordhere', 'measurepower');
Next, run this in your console: $ sudo nano /var/www/index.php
Then find this line and change the password:
$link = mysql_connect('localhost', 'measurepower', 'yourpasswordhere');
7. The last thing to do is to ensure that the logging application starts when the Raspberry Pi starts:
Run this in your console: $ sudo nano /etc/rc.local
Then add this line as the 2nd last line: /var/www/cheappowermeter-Python/./readlight &
so the line will end with exit 0
Your are done!
Go to http://<the ip address> to see the result!
This is how your power consumption statistics look like in a browser
If the logger saves too many or too few watt hours, you might try to adjust the light-value:
$ nano /var/www/cheappowermeter-Python/readlight
Look for this line: if result<=150:
You can read the light-value by running:
$ /var/www/cheappowermeter-Python/./debug
PS: The code is available at GitHub please contribute.
https://github.com/comzone/cheappowermeter
Happy Geekend!
Handy links:
http://learn.adafruit.com/basic-resistor-sensor-reading-on-raspberry-pi/basic-photocell-reading
http://raspberrypi-projects.com/how-to-connect-a-photocell-to-a-raspberry-pi-6/
This blog post has been proofread by a Technical Writer before being published.
You've messed up units a bit.
SvarSletI believe by "the box" you've meant a energy meter. Your meter's LED blinks every X wattHOUR (Wh) not watt, as watts alone are not a measurement of energy (but power).
However the current usage on web panel should be in kWh/unit of time = kW. OFC unless it's "energy used up in most recent unit of time".
My meter has "6400 pulses per 1kWh" written on it's faceplate, which makes 1 blink every 0,15625 Wh. I guess it depends on the model but one can't assume that 1 blink means 1 of something.
Have you tested if your system is not miscalibrated by using just one appliance with known load, like toaster or hairdryer?
Hi Szymon.
SletThe first release was put together late at night, so I'm not surprised that there are some mistakes :) I will fix them in next release.
I figured out that 1 blink is equal to 1 kWh by switching everything off in my apartment and then turning on my kettle, (because I know exactly how much it uses). In Denmark I think it's the same for all energy companies but the kWh value for a blink might be different in other countries.
Thanks for your comment.
Søren
Søren, cat figure out how to calculate when 100 blinks is a kWh. can you give a hint?
SletHi,
SvarSletNice article! I was playing with something similar last week. I gave up on using a capacitor. The led on my 'electricity meter' is quite faint so the LDR would not pick up on it often enough to bother me. The values/timings differed very much. I could experiment with smaller capacitors but I abandened the idea in favour of using an old Arduino to read the analog sensor (plus keeping an eye on the BeagleBone Black) and connecting that to (+powering it by) the Raspberry Pi. I've written everything in Python. I'm using www.pvoutput.org for displaying the data and a little server I call a webcache to display arbitrary key/value pairs. In this case the current Wattage. My code can be found on https://github.com/ericvrp/PowerToThePeople
cheers,
Eric
Hi Eric.
SletI had some of the same problems as you, but calibration and gaffa tape fixed the problem. Incredible what gaffa can do ;-) My Python code uses a lot of CPU, so my next step is to make the code better. pvoutput.org looks very interesting, I will differently check that out and probably add functionality so my program can upload data to pvoutput.org
Cheers
Søren
Hi,
SvarSletThanx for your tutorial ! i made it last night and works fine, i will translate a french version from this tutorial and put it soon as possible online.
Big thanks again to share this knowledge !
Pierre-Antoine
Hi GéRarD.
SletThanks you so much for you comment.
Your are more than welcome to translate it and use it as you want to, but please link back to this article ;)
Søren
Hi,
SvarSletHere's the french version from this exciting experience !
http://blog.foulquier.info/2-Mise-en-place-du-projet-Cheap
Pierre-Antoine
Hi Pierre-Antoine.
SletIt's super cool, cheers mate!
Feel free to make improvements to the code and upload them to my project at github.
https://github.com/comzone/cheappowermeter
Søren
Are there different types of CDS photoresistors?
SvarSletIt seems like there are different sizes available (3mm,4mm,5mm)
And CDS photoresistors with different 1k 5k 10k 20k 50k 100k, what is the meaning of this?
Which CDS photoresistor would work of the following:
http://www.aliexpress.com/store/205478/search?SearchText=cds
It seems like 1k 5k 10k 20k 50k 100k is related to the resistance (Ohm), what would you recommend if I want to try your power consumption measurement solution?
SletHi Jonas.
SletThe Capacitor should be a 1uF 50V Electrolytic Capacitor and the CDS photoresistor should be about 5KΩ to 200KΩ.
If you have the wrong CDS you can easily calibrate so it works, just adjust the light variables in the readlight script. Adjust the number in this line: if result<=150:
The debug script is very handy to find the right light value.
Hej Søren, rigtigt fint guide du har fået lavet, :) Jeg skal helt sikkert i gang, vil disse fungere?
SvarSlethttp://elektronik-lavpris.dk/p79616/VT83N1_Photoresistor_12k/100k_Plastic/
http://elektronik-lavpris.dk/p118745/CS0001/50_El-Capacitor_1/50_5x11_P2,5/
Hej Rico.
SvarSletDe bør fungere. Det værste der kan ske er at du lige skal køre debug scriptet for at aflæse "lys værdierne" og derefter justere disse i min kode.
Søren
Hi! What a great project you have here!
SvarSletI have followed your tutorial but have one problem. I can se the light values when using the command sudo /var/www/cheappowermeter-Python/./debug so the sensor must be working. However, when i go to my ip adress I can acces the site but there is no data on it. Do you have any idea what the problem is? I suspect it might have something to do with the database.
Sincerely Henrik
Hi Henrik.
SletTry to see in the database if any records have been inserted into the table.
If not try to check the database user/pass or the light value in the script.
Søren
Well, I managed to solve it, the "readlight" file in the WWW folder was not executable by my user. I changed it to 777 and now the website is recieving data! Now the problem is that the graph dosn't show up, just an icon of a broken picture.
SvarSletHi Henrik,
SletSuper that you figured the first problem out.
Did you use my code from Dropbox or from GitHub? The one on Dropbox might be more stable...
If you followed the instructions from start to the finish, it should work!
Søren
Hello, I have the same problem with Henrik. There is no data in my page, what do you mean, you changed it to 777? How did you do it?Thank you.
SvarSletDaniel
This is the response when I run readlight code..
SvarSletroot@raspberrypi:/home/pi# /var/www/cheappowermeter-Python/readlight
Traceback (most recent call last):
File "/var/www/cheappowermeter-Python/readlight", line 71, in
result = RCtime(18)
File "/var/www/cheappowermeter-Python/readlight", line 53, in RCtime
GPIO.setwarnings(False)
AttributeError: 'module' object has no attribute 'setwarnings'
Hi Mark, what was the solution to this?
Sletgot the same problem.
I noticed that the install command "easy_install rpi.gpio" didnt work so used "apt-get install rpi.gpio" which installed python-rpi.gpio.
could this be the reason?
That was the problem.
SletMust have typed the command wrong the first time.
typing easy_install rpi.gpio replaced a gpio version with a newer one.
No graph is showing in my page. How can i solve it??please help me.:(
SvarSletTry:
SvarSletcd /var/www
chmod 777 chart.png
Thanks, you made my day, not just my day,my whole month.i really dont have any experience about php and sql.haha.Thanks again.:)
SvarSletSuper that you figured it out guys!
SvarSletThe newest version of the software can be found at: https://github.com/comzone/cheappowermeter
Speed have been increased a lot!
Can you make a how-to of your new new version?
SletI will release an new installation and how to for the now improved version which is at my Github as soon as I find time for it ;-/
SletFeel free to improve the code or bring suggestions.
Søren
Hi there! you might want to check out www.ubidots.com to push your data to a live web dashboard. You can use Ubidots' Python library for the Pi
SvarSletLooks cool!
SletSøren
Hej, super guide, lige hvad jeg har ledt efter. Det skal prøves ligeså snart jeg får købt mig en fotocelle.
SvarSletHar nemlig en bimåler til min varmepumpe, og har længe drømt om live forbrug.
Min bimåler har også en puls udgang. Vil det være en let modifikation at indkode i programmet? eller vil man endda kunne forbinde dme istedet for fotocellen?
glæder mig til at prøve dit program.
Tak.
SletPrøv at finde ud af hvor meget spænding der er på din pulsudgang. Hvis den kan drive en lysdiode kan ban bruge sådan en sammen med det skitseret setup. En direkte sammenkobling kan garanteret også laves men jeg ved ikke på stående fod hvad der skal til.
Søren
Hi Søren do you have any idea how to change the blink/impulse interval from 1 blink pr kWh to 100 blink pr kWh?
SvarSletI cant figure it out.
Hi!
SletIt blinks pr. 1 watt hour which is equal to 0,001 kWh.
So this line in index.php have to be changed from $watt[] = (($row['watt']*$intervalmultiply)/1000);
To:
$watt[] = (($row['watt']*$intervalmultiply)/100);
That should fix it.
hi sir Soner im a beginner and im curious with this project ..can i have a little knowledge on how you make the code of the graphing part in your project.because Im planning to use this idea to my thesis project.Thank you for your help ..
SvarSletHi!
SletHave a look at http://pchart.sourceforge.net
hi soren,
SvarSletjust tried your github version, but got an error message "Could not find driver" ?
Hey.
SletYou need to use the Adafruit image as they have installed the right Gipo drivers which is necessary.
https://learn.adafruit.com/adafruit-raspberry-pi-educational-linux-distro/occidentalis-v0-dot-2
pi@pitest /var/www/cheappowermeter-Python $ sudo ./readlight
SvarSletTraceback (most recent call last):
File "./readlight", line 71, in
result = RCtime(18)
File "./readlight", line 53, in RCtime
GPIO.setwarnings(False)
AttributeError: 'module' object has no attribute 'setwarnings'
after if i login with new user to mysql you need write to use database where you create table.Sorry my english
SvarSletToday all working ok but i have small question: how to i change price kw? 1kw=0,13eur
SvarSletHeya!
SletSuper you got it to work.. Please share your modifications here so others can learn form it ;-)
Hi Søren.
SvarSletCool program - I just made this evening.
I though have a small problem.
When it lights up, I have too many impulses. I get 2-3 impuls each time!
Here's an example:
506
547
870
120 - 1.impuls
102 - 2.impuls
80 - 3.impuls
507
408
608
120 - 1.impuls
135 - 2.impuls
605
Does anyone have a solution for this problem?
Best regards
Anders :-)
I think it can be fixed by fiddling around with the time.sleep value in the readlight.php . Use the debug script to find the right value.
SletPlease share your results.
Anders, I have the same problem as you.
SvarSletMy power meter uses a quite faint red led for its pulse mechanism. Just like you I'm getting several reading for the same pulse. I'm wondering if the capacitor I use "fill up" several times during one pulse and hence I should be using a larger capacitor. I'm a total newbie to electronic circuits so bit out of my depth.
My power consumption is roughly 35 000 kWh per year. Which equals about 1,1 blinks per second on average. So at peaks I guess there will be probably 5 blinks per second.
First question is if the led pulse will be able to resolve that granularity or if will just a constant flicker. Assumed that that will be OK I need a device that can capture at that frequency.
The only rule a I remember from school for capacitors was t = RC where t is the time to discharge the capacitor (correct?). In my case tmax should be no more than 0,2s.
My LDR is 2-20 kOhm. So at full light C = tmax/2k => C = 1000 uF
Is that a correct reasoning?
Heya.
SletDid you try it out?
Otherwise check out my reply to Anders Bertelsen. It could maybe also fix it.
Dear Mr. Soren,
SvarSletI got an error message "GnuTLS: Error in pull function" "Unable to establish SSL connection" while downloading the cheappowermeter application.
Your advice will be highly appreciated.
Regards
Kinley
Denne kommentar er fjernet af forfatteren.
SvarSletI just tried in a terminal with: wget https://www.dropbox.com/s/xcb2ntrt2d3xlkd/Cheappowermeter.tar.gz
SvarSletIt works for me. Try https://www.dropbox.com/s/xcb2ntrt2d3xlkd/Cheappowermeter.tar.gz with a webbrowser like Chrome or Firefox.
Dear Mr. Soren,
SvarSletI solved the downloading issue as it was related to some certificates issues but now i came across a new problem.
When i enter my ip address it simply display's the apache default page.
Please your help will be highly appreciated!!!
My best guess is that the www document root have been changed in the newer versions of Apache. Try to modify the Apache settings so the document root is /var/www/
SletAlternatively you can move the data from /var/www/ to the new Apache document root whict I trhink is /var/www/html/..
even when i use the command "SELECT * FROM watthours", it's showing "Empty set"
SvarSletIt sounds like you got no input from the GPO.. Try to use the debug script which you can find in the same directory as the main-script to see if thats the case.
SletIs it possible to directly interface raspberry pi gpio with meter led?
SvarSletIt is.. You can probally merge this project web my Super cheap web-enabled power measurement solution with this project:
Slethttps://learn.adafruit.com/light-painting-with-raspberry-pi/hardware
What verision are we using in this projekt ?
SvarSletThere is 0.1 0.2 and 0.3 today
Which one is the intended one for this ?
I got it to work!
SvarSletBeaware of Hynx RAM!!! I thougt all my SD-Card was kaputt. By accident I put my SD card in to an old A version. Then it booted!! My head was spinnig for some time until I read this:
https://www.raspberrypi.org/forums/viewtopic.php?f=26&t=43484
I had to replace:
bootcode.bin
start.elf
fixup.dat
Then manage to boot on the B version.
Also....
When You logged in at mysql with the user measurepower. You need to issue the command "use measurepower" to select the correct database before you do.
CREATE TABLE IF NOT EXISTS `watthours` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`datetime` datetime NOT NULL,
`lightvalue` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;
I also had to do chmod 777 on readlight and on the chart.png
rwxrwxrwx 1 root root 2054 Feb 13 22:40 readlight
rwxrwxrwx 1 root root 18172 Feb 13 23:48 chart.png
But the Hynx was the biggest issue for me! Hope above text will help others.
Sören ! Great work!!! I am impreesed and I have learnt a lot of doing this.
Thank You!
Hi Carl!
SletVery good figured out.. I'l try to find some time for updating the instructions with your corrections and also update the installation so it works better with the new PI's.
Thanks for praise!!
Søren
I am having some difficulties with getting good values from a not that faint red led.
SvarSletThe debug is returning values of 750,000 to 1,000,000 on a flash (I suspect on flash) and random values of about 1,74x,xxx.
I wired according to your tutorial and used the following components:
Capacitator: 50V 1uF
LDR: JTRON 5537 with a spectral peak at 520 nm and a light resistance of 20 ~ 45 K at 10 lux
What could be the problem? Capacitator voltage does not mather does it?
Hi!
SletThe Capacitator voltage matters. You will get other values but that’s why you can change the threshold in the code and still make it work.
Søren
Hej Søren.
SvarSletFedt projekt, som jeg stærkt overvejer at lave. Jeg har dog et problem, jeg har allerede flere projekter kørende på min pi med raspbian kørende.
Så enten skulle jeg ud og købe en ny pi, bare til ovenstående, og ellers, så skulle det installeres på min eksisterende installation.
Så mit spørgsmål går på, er det muligt at sideloade adafruit driverne som ovenstående image skal bruge?
Hi there.
SletI am sure that it is possible to load the drivers into your existing installation but it requires modifying of the Kernel so I would only recommend this solution if you are experienced Linux user.
Søren
Hi, got mine running for about six months then it Crashed somehow.
SvarSletNot im looking into trying to measure it and send it to thingspeak. Need some place where the database is fast, and reliable, my pi wasnt fast for showing the data in graphs, and I liked the historics.
unfortunately I dont have the experience to program it. one of the problems would be temporary saving the data with time stamps until it can be sent to thingspeak, they only allow upload every 20 sec or so.
sending data to thingspeak is quite easy thou its like this:
http://api.thingspeak.com/update?key=XXXXXXXXX&field1=7&created_at=2011-07-18T01:02:03Z
were field1 is the data
ceated_at is the date/time
Key is one's personal thingspeak id/channel
but when only limited to sending every 30 sec or minute, there has to be some counting of impulses in a variable.
Just wanted to share my thoughts
Hi Svar, did you made some progress on the installation description for the new Github setup (i.e the one that either uses sqlite or mysql)? I have the "original" setup working on a standard Jessie Lite image. However the newer/modified version immediately gives an "could not find driver" error. I'm now downloading the Occidentalisv02.zip but I do not feel comfortable with this old distribution. Any news?
SvarSletHi,
SvarSletis it possible to download your SD-card image , so I can install it on my raspberry?
I'm a technician, nut not a programmer...
my e-mail : demeyert@telenet.be
Denne kommentar er fjernet af forfatteren.
SvarSletI got this working on a fresh Raspbian image, I will post a updated guide on my webpage (https://www.rakett.dk) soon.
SvarSletJeg har fået det til at virke på en ny installation af Rasbian, jeg har lavet en ny guide på min side https://www.rakett.dk - den er på engelsk, men er der nok efterspørgelser, oversætter jeg gerne.
SletHey Kasper.
SletSuper fedt at du har fået det op at køre på en fresh installation. Og super blog!
Den nyeste udgave af softwaren ligger på min GIT.. https://github.com/comzone/cheappowermeter Det kunne være fedt om du kunne få den til at spille sammen med din installation og eventuelt pushe dine ændringer til GIT så andre lettere kan få adgang til løsningen samt udvikle videre.
Mvh
Søren
Hi Søren.
SvarSletIf I don't get any values running the debug, can that be a faulty component ? - Can I test it in some way, like touching 2 pins with a resistor ?
Nothing happended when running debug, then suddenly hundred of lines showed up, with values between 1700 and 1900 - and then again NOTHING happens... tried restarting debug, nothing happens.. (Have taped it at Electricity meter)
Used these parts
http://elektronik-lavpris.dk/p79616/VT83N1_Photoresistor_12k/100k_Plastic/
http://elektronik-lavpris.dk/p118745/CS0001/50_El-Capacitor_1/50_5x11_P2,5/
Never mind, in your instructions you wrote to use GPIO (P18) - But when seeing the picture you are using (P12) - that solved it (Besides my next struggles, getting very high values, and no data logged, but thats for another day to be examined :)
SletDenne kommentar er fjernet af en blogadministrator.
SletHej Steen.
SletFedt at du fandt fejlen. Det er nu rettet i teksten.
Mvh
Søren
Hej Søren,
SvarSletDejligt stykke software ide. jeg har dog problemer med at får det som du har lagt på Github til at virke rigtigt - bliber der udviklet mere på det ?
Mit problem er at den www folder giver 500 error og kan ikke se hvor jeg skal sætte mysql conn detaljerne henne.
mvh
Phillip J
Hej Phillip.
SletDet smarteste er at installere udgaven der ligger her:
https://www.dropbox.com/s/xcb2ntrt2d3xlkd/Cheappowermeter.tar.gz
Den er nemlig tested og bør derfor virke out of the box.
Udgaven på Github er ikke helt produktions klar de vi forsøgte at konvertere løsningen til C.
Mvh Søren
Hey Nice Blog!! Thanks For Sharing!!!Wonderful blog & good post.Its really helpful for me, waiting for a more new post. Keep Blogging!
SvarSletbest java training in coimbatore
php training in coimbatore
best php training institutes in coimbatore
Fantastiskt projekt! Undrar om nån kör detta med sqlite databas istället och vill dela med sig av hur isåfall?
SvarSletI am want to use this program on Ubuntu and RBPi but get only tekst no graph , any suggestions tanks.
SvarSletBertus