Perl uses a multimeter to report power consumption
Document Sample


Perl: Multimeter to Measure Power Consumption PROGRAMMING
Perl uses a multimeter to report power consumption
ELECTRICKERY
Today’s digital multimeters can do more than measure current and voltage.
madochab, photocase.com
Multimeters also measure capacity and temperature. An inexpensive
multimeter can talk to your PC via the serial port, and simple Perl scripts let
you read and visualize data in neat charts. BY MICHAEL SCHILLI
I
was browsing a mail order catalog ter to the measuring device. The device retrieve a maximum of one measured
for electronics the other day when I responds with a 14-byte string contain- value per second.
noticed a couple of low-budget, digi- ing the value shown on the multimeter’s Listing 1 shows a test script that
tal multimeters with RS 232 interface. I LCD display, and other useful informa- fetches a value from the multimeter. The
discovered the MAS-345 model by Mas- tion like what’s being measured and the CPAN Device::SerialPort module gives
tech on eBay for US$ 35 and quickly selected range. developers a convenient, object-oriented
pressed the “buy-it-now” button. If the string returned by the Mastech interface for talking to the computer’s
device is V -120.3 mV, this indicates that serial port. The port will use the RS 232
Windows? No Thanks! the multimeter is in voltage mode and protocol to talk to the multimeter on the
When the device arrived, it came with showing a value of -120.3 millivolts. other end of the line.
just a Windows CD. After a quick search The multimeter takes about one sec- mmread in Listing 1 sets up a connec-
on the web, I discovered the Marsh proj- ond to respond, so the computer can tion with the computer’s first serial port,
ect [2], which uses a bit of C code to ad-
dress the Mastech MAS-345 among other Listing 1: mmread
multimeters. 01 #!/usr/bin/perl -w 12 $serial->dtr_active(1);
The serial line protocol used by the
02 use strict; 13
device is fairly straightforward. After a
03 use Device::SerialPort; 14 # Send request
couple of introductory signals to set up
the line, the PC sends a newline charac- 04 15 $serial->write("\n");
05 my $serial = Device:: 16 # Wait one second
Michael Schilli works
SerialPort->new( 17 select(undef, undef, undef,
as a Software Devel-
THE AUTHOR
oper at Yahoo!, 06 "/dev/ttyS0"); 1);
Sunnyvale, Califor- 07 18
nia. He wrote “Perl
Power” for Addison- 08 $serial->baudrate(600); 19 # Read response
Wesley and can be 09 $serial->databits(7); 20 my($count, $data) =
contacted at mschilli@perlmeister. $serial->read(14);
10 $serial->purge_all();
com. His homepage is at
http://perlmeister.com. 11 $serial->rts_active(0); 21 print "$data\n";
W W W. L I N U X - M A G A Z I N E . C O M ISSUE 83 OCTOBER 2007 77
PROGRAMMING Perl: Multimeter to Measure Power Consumption
which has a device name of /dev/ttyS0 measured numeric $value, the $unit, 220V! Thankfully, new measuring cables
on Linux. To enable the script to run on and the $mode. Before launching into for multimeters always use insulated ba-
a normal user’s account, the root user the infinite loop, the script switches to nana plugs; I just bought myself a couple
will need to open the device file for autoflush mode by setting $|, making to connect to a multiple socket. Also,
global reading and writing by entering sure that subsequent print commands don’t try the soldering experiment men-
chmod a+rw /dev/ttyS0. If you have a won’t hold back the output. tail -f moni- tioned below if you’re not feeling com-
new-fangled computer without a serial tors the progress in the output file. fortable working with high voltage. This
port, you will also need to invest about is for experts who know how to use
US$ 10 in a serial PCI card. Note that Caution, Voltage! proper safety precautions.
Linux might then show the serial ports I’ve always wondered how much power The amperemeter needs to be con-
under different names; typical examples my desktop computer, which runs 24x7, nected in series with the consumer. Fig-
are /dev/ttyS5 and /dev/ttyS6. consumes in the course of the day. Does ure 1 shows the circuit diagram, and Fig-
The test script first sets the baud rate my computer save power when I’m not ure 2 shows the physical wiring using a
to 600 and the number of data bits to 7. using it? A device like the Kill-A-Watt [3] low-budget multiple socket. In ampere
A call to the purge_all() method triggers can calculate the total consumption, but mode, the multimeter’s internal resis-
the Unix tcflush(2) internally with the I’m interested in what the computer tance is almost zero and connecting it in
TCIOFLUSH flag set to delete any dan- does in the middle of the night when no- parallel to the socket would be fatal. You
gling data bits. The RTS line is then body’s looking. could destroy your multimeter this way
cleared and the DTS line is set to initiate The MAS-345 measures current up to or, at best, blow fuses all over the house
communications with the multimeter. 10 Amps and it also measures alternating and in the multimeter (if it happens to
The write() method then sends a new- current, which is a feature you can’t take have one).
line character to the multimeter, which for granted with low-budget multime- The soldered joints in my multiple
responds after a short while with the ters. Moreover, as any electrical engineer socket were tougher than expected. In
data in its display. For reasons explained can assure you, simply multiplying volt- fact, I had to buy a 60W soldering iron
above, the script waits for a second be- age and current doesn’t give you the ac- for the job because my other two solder-
fore issuing a read() command to fetch tual power consumed, but I’ve verified ing irons were designed for use with
more data from the serial port. You could with the Kill-a-Watt that it comes pretty smaller electronic devices.
use sleep(1) to do this, but select() sup- close for both my PC and my Laptop. After double-checking the modified
ports fractions of seconds, and I tried Be careful when using your multime- hardware, I plugged in carefully and
various values while developing the ter to measure the power coming out of started measuring the power consump-
script before deciding on one second as the wall sockets. Mains power in the tion of the Linux-based home PC and a
the most reliable approach. United States is just 110V, but that can laptop with docking station in the Perl-
We know that the multimeter will be more than enough to cause serious meister lab.
send exactly 14 characters, and read ex- injury. Uninsulated banana plugs like
plicitly requests to retrieve that many. those used for low-voltage experiments Visualization
The result string ends up in $data, aren’t appropriate here. Obviously you’re not going to thrill the
which the print command subsequently A long time ago, one of my physics crowds by generating a text file with
writes to STDOUT. teachers paid a high price for being ab- rows of figures. To help visualize the
sent minded and ended up in a hospital data, the mm2rrd script in Listing 3
One for All after touching a banana plug carrying parses the file line by line and separates
I bundled everything into a module and
dropped it off at CPAN as Device:: Listing 2: mmloop
MAS345, so other MAS345 enthusiasts 01 #!/usr/bin/perl 13 # Autoflush
can read their multimeters without con-
02 use strict; 14 select FILE;
cerning themselves with the underlying
03 use warnings; 15 $| = 1;
technology. Another advantage that
CPAN modules offer is that they are 04 use Device::MAS345; 16
available wherever you are and are easy 05 use Log::Log4perl qw(:easy); 17 while(1) {
to find using search.cpan.org. 06 Log::Log4perl-> 18 my($val, $unit, $mode) =
Device::MAS345 gives developers an easy_init($DEBUG); $mas->read();
object-oriented interface at a higher ab-
07 19 die $mas->error() unless
straction level. The mmloop script in
08 my $mas = Device::MAS345->new( $mode;
Listing 2 shows how to fetch data from
the multimeter using an infinite loop and 09 port => "/dev/ttyS0"); 20 print FILE time(), " ",
how to store the acquired data along "$val\n";
10
with the current time in a text file. The 21 sleep 10;
11 open FILE, ">>values.txt" or
CPAN module picks up the raw string 22 }
die;
from the multimeter via the read
method, and it splits the result into the 12
78 ISSUE 83 OCTOBER 2007 W W W. L I N U X - M A G A Z I N E . C O M
Perl: Multimeter to Measure Power Consumption PROGRAMMING
Figure 1: Set up the multimeter to measure
the current in a serial connection with the
device.
the timestamps from the acquired val-
ues. Then you can pass the results to
rrdtool to create a neat graph with a min-
imum of effort.
We use the plough method from the
CPAN Sysadm::Install module to read Figure 2: A modified multiple socket with insulated banana plugs for connecting the digital
the data line by line. The method ex- amperemeter.
pects a subroutine reference and a file.
The method opens the file, iterates over the measured value and pushes both as velopers an understandable interface by
the lines and jumps to the function for array references to the end of the converting input into rrdtool commands.
each, and sets the $_ variable to the con- @points array. The create() command generates a
tent of the current line. rrdtool options are fairly cryptic, but round-robin database, mmdata.rrd, with
mm2rrd extracts the timestamp and the CPAN RRDTool::OO module gives de- 10000 primary data points (PDPs),
Advertisement
W W W. L I N U X - M A G A Z I N E . C O M ISSUE 83 OCTOBER 2007 79
PROGRAMMING Perl: Multimeter to Measure Power Consumption
Figure 3: The power consumption of a PC at night: A cron job starts a Figure 4: Power consumption of a laptop shortly before and after
2am and completes at 7am. switching on.
which it expects every 30 seconds (step time scale for the graph, but in this case, There is a noticeable increase in power
value). The previous script outputs mea- $points[-1]->[0] sets the end point to consumption caused by the backup and
sured values at 10-second intervals, but the timestamp of the last data point in indexing process kicking in at 2am. The
rrdtool automatically calculates the 30- the @points array. The graph method three disks I installed in the machine
second average to arrive at the PDPs. generates a nice chart as a PNG file. were spinning up and pushed the power
rrdtool does not respond well to values usage. The process terminated and
outside the start point of the RRD data- Results power consumption dropped to the origi-
base, so the script sets the $start param- Figure 3 shows the power consumption nal level just before 7am.
eter for the create method to one second of the Linux PC at night. The machine Figure 4 shows the power consump-
before the first measured value. did not sleep at all because I also used tion for my laptop, which is connected
A similar approach is used to set the the system to run the measuring script. to a docking station, a couple of minutes
before and after switching on. The dock-
Listing 3: mm2rrd ing station still consumes 40mA when it
01 #!/usr/bin/perl -w 22 data_source => { name => is switched off, which means I’m wast-
02 use strict; "amps", ing 4 watts day and night!
23 type => "GAUGE" }, The consumption values rocketed after
03 use RRDTool::OO;
switching on the docking station. That’s
04 use Sysadm::Install qw(:all); 24 archive => { rows => 10_000
no surprise because the system has to
});
05 ramp the disk up to speed and launch
25
06 my @points; the operating system.
26 for(@points) { After a couple of minutes, the value
07
27 $rrd->update(time => $_->[0], dropped to about 130mA. In other
08 plough sub {
28 value => $_->[1]); words, my laptop uses about 15 watts,
09 chomp;
29 } which is just more than a tenth of what
10 my($time, $value) = the PC uses. The multimeter will also
split / /, $_; 30
measure temperature and capacity, and
11 push @points, [$time, 31 $rrd->graph(
online nerd stores have all kinds of sen-
$value]; 32 width => 600, sors with voltage output, so creative tin-
12 }, "values.txt"; 33 height => 400, kerers will have hours of fun discovering
13 34 image => "mmdata.png", new applications. ■
14 # Constructor 35 vertical_label => "Amperes",
15 my $rrd = RRDTool::OO->new( 36 start => $points[0]->[0],
INFO
[1] Listings for this article:
16 file => "mmdata.rrd" ); 37 end => $points[-1]->[0],
http://www.linux-magazine.com/
17 38 draw => { Magazine/Downloads/83
18 # Create a round-robin 39 type => "line", [2] Marsh project for controlling the
database 40 color => "0000FF", Mastech MAS-345, http://savannah.
19 $rrd->create( nongnu.org/projects/marsh
41 legend => "Laptop Power",
[3] The Kill A Watt power measuring
20 step => 30, 42 } device, http://www.p3international.
21 start => $points[0]->[0] - 43 ); com/products/special/P4400/
1, P4400-CE.html
80 ISSUE 83 OCTOBER 2007 W W W. L I N U X - M A G A Z I N E . C O M
Related docs
Get documents about "