Low-level ADC control: ADMUX

While discussing the 3 phase sketch implementation here: by Pcunha which makes use of the AVR analog read commands rather than the arduino analog_read function which is a wrapping for these commands JBecker suggested that the analog reference voltage was not being selected correctly, so I had to do some reading up on this on ADMUX and bitwise operators.

So for anyone interested, this is how it works first ADMUX is an 8-bit byte that holds the settings for the analog reference voltage and the analog pin to select:

ADMUX is 8-bit:

 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 bit 

 REFS1REFS0 Voltage Reference Selection 
 0AREF, Internal Vref turned off 
 0AVcc with external capacitor on AREF pin 
 1Internal 1.1V (ATmega168/328) or  2.56V on (ATmega8)

MUX 3...0Single Ended Input

So if we want to use AVcc with external capacitor on AREF pin as our voltage reference (which is the default arduino voltage reference) and we want to select ADC2 for example, we would need to set ADMUX to:

 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 bit 

We can use bitwise operations to get there:

This is how its done in wiring_analog.c found in Arduino-1.0/hardware/arduino/cores/arduino

ADMUX = (analog_reference << 6) | (pin & 0x07);

Starting with (analog_reference << 6). The variable analog_reference is set to 1 as default for the atmega328 so 1 << 6 means bitshift 1 left 6 places where 1 in binary is 00000001 and shifting the bits left 6 places moves the 1 to 01000000. The desirable result for setting the 6th bit REFS0 to 1.

If you dont need to select different analog_reference values then we can get 01000000 directly by specifying its hexadecimal: 0x40.

Next looking at the  (pin & 0x07) part.

  • The & 0x07 is actually just for validation, it essentially says only allow selection of ADC0 to ADC5. 
  • The & bitwise operator is the AND operation.
  • 0x07 is hexadecimal whose binary representation is 00000111
  • Selecting ADC2 which is pin = 2 or in binary 00000010
  • The result of 2 & 0x07 = 00000010 AND 00000111 = 00000010.

The last part is the | bitwise operator: OR

(analog_reference << 6) | (pin & 0x07) becomes in our example here 01000000 OR 00000010. Which is equall to: 01000010 the result we where looking for above.

If you would like to read more on the AVR ADC commands see these helpful articles:

Configurable single to 3-phase interrupt based EmonTX code by Pcunha

Some great work I'd like to flag up by Pcunha, who has developed a super configurable single to 3-phase interrupt based firmware for the EmonTX.

Its up on github here:

and there is more about it in the forum thread here:

EmonGLCD Template based display's

I have been thinking about how it could be possible to program an EmonGLCD display remotely or at least specify which displays are shown i.e if you could construct a command to tell the display to:

display solar pv page as page 1, use the solar power value from node 10. 

Skipping for now the how the commands are sent and interpreted, I think the first part of creating these specifiable displays is to convert the current display code into template functions which should be of benefit whether the displays are remotely programmed or not.

Here's my first attempt at this:

draw_power_page( "POWER" ,use, "USE", usekwh);
draw_temperature_time_footer(temp, mintemp, maxtemp, hour,minute);
draws the following page:

draw_solar_page(use, usekwh, gen, 2050, genkwh, temp, mintemp, maxtemp, hour,minute);

(thanks to drsdre for the icons!)

This is what the full code looks like:

#include <JeeLib.h>
#include <GLCD_ST7565.h>
#include <avr/pgmspace.h>
GLCD_ST7565 glcd;

unsigned long fast_update;

// Fixed values for this example
double temp = 17.4 ,maxtemp = 19 ,mintemp = 16;
int hour = 23, minute = 43;
double use = 252, usekwh = 2.5;
double gen = 1760, genkwh = 4.8;

void setup()

void loop()
  // Display update every 200ms
  if ((millis()-fast_update)>200)
    fast_update = millis();
    int S1 = digitalRead(15);
    int S2 = digitalRead(16);
    int S3 = digitalRead(19);

    if (S1==1)
      // powerstr, power, energystr, kwh
      draw_power_page( "POWER" ,use, "USE", usekwh);

      // temp, mintemp, maxtemp, hour, minute
      draw_temperature_time_footer(temp, mintemp, maxtemp, hour,minute);
    else if (S2==1)
      // powerstr, power, energystr, kwh
      draw_power_page( "SOLAR" ,gen, "GEN", genkwh);

      // temp, mintemp, maxtemp, hour, minute
      draw_temperature_time_footer(temp, mintemp, maxtemp, hour,minute);
      // use, usekwh, gen, maxgen, genkwh, temp, mintemp, maxtemp, hour, minute
      draw_solar_page(use, usekwh, gen, 2050, genkwh, temp, mintemp, maxtemp, 12,43);

To run this you will need the accompanying icons and templates files, its all available in the EmonGLCD repo here:

Interested to hear any thoughts on how best to take this forward.

Reading Watt-hour data from an Elster A100C electricity meter using IrDA by Dave Berkeley

If you have an Elster meter this is a fantastic way to read the exact accumulated watt hours that you have generated or used and can compliment and cross check a CT based measurement.

Dave Berkeley writes:

The A100C has an LCD display showing the number of kilowatt hours generated, but it also has two optical outputs. One flashes momentarily each time one watt hour is recorded. The second output is an infrared port which transmits the details of the meter, including accumulated Watt Hours, every second or so.

There are lots of commercial power meter readers around, and many homemade ones too. But they all seem to simply count the 1Wh optical pulses. This does give you an accurate measure of instantaneous power usage / generation, but does not give accumulated totals. If you get a malfunction in the reader you will lose counts. If you count the IrDA output it always gives you accurate accumulated totals.

Read the full build guide here: Electricity Meter Reader

and download the Arduino source code here: elec_meter.ino

The only thing you need to get this running on an arduino or an emontx is a TSL261R optical sensor, the TSL261R has the same pin out as the TSL257 so can be connected to the emontx pulse input.

We've put together a small kit available in the shop of all the components needed to connect it to an emontx including the TSL261R a male 3.5mm jack, 1m of cable and heat-shrink to save needing to get all the components from different places.

EmonGLCD Icons by Drsdre

Drsdre writes:

I've started experimenting with using icon based information with the goal to use the limited real estimate on the LCD more efficient and make the display more attractive.

Current features of this experiment:
  • Icons for current usage, grid, solar and temperature. 
  • Solar and temperature will shown different icons based upon solar wattage/temperature on scale -15 to 40c. Solar maximum value is auto-learning. 
  • If no EmonTX or EmonBase info is received, amount of seconds when last package was seen is shown. 
  • Assigned down button to switch on/off background light. 
Ideas: also add a animated wind energy icon, use an overall more graphical representation based upon a house with panel on the roof, wind mill in garden and connection to grid. It's in a very early stage and I love to hear your feedback.

Forked EmonGLCD sketch with changes can be found on

From the forum thread here:

Almost at the next emoncms release point

Over the last couple of months I have been working closely with Ildefonso Martínez Marchena from Spain on developing emoncms to the next level and we have been making really good progress.

We are almost at the next release point with a lot of big additions including:

  • Support for multiple dashboards
  • A fully visual dashboard editor
  • Public dashboards via username i.e
  • Support for ckeditor and simeo file manager
  • 8 different dial types and a hot water cylinder
  • LED’s widgets thanks to Lloyd
  • Published and unpublished dashboards for dashboards that are being worked on.
  • A reworked dashboard renderer implementation
Data and core
  • CSV data input and identification by sensor node inputs.
  • Feed Autoconfig
  • New averaging process for creating daily temperature averages.
  • Setup script improvements
  • Thanks to Juan Sidrach for help with general code formatting and multilingual implementation. 
  • Twitter bootstrap based theme.
All this is available now on github and has been of course throughout development. At this stage we are just polishing the release and updating and writing documentation.
We've got the domain and have the latest version running there off the same server and database as so you can still access your data through

The idea here is to create a really nice launch page for emoncms and have the live instance hosted there which can be used as a main logging site or for testing before running it on your own server or both. will still be a beta service for now as its stability and reliability is established.

Bug testing
It would be great if you can try out the new version and let us know of any bugs you find so that we can try to get it as rock solid as possible before this release is complete.

Due to a couple of core implementation changes to visualisations and dashboards many of the visualisation URL’s and dashboard scripting have changed so it best to build any old dashboards from scratch using the new visual editor.

Have a look at the using emoncms documentation here if you need help with any of the steps:

Please submit any bug details either to the issue tracker on github here:
or on the forums here:
There is also a beginning on code documentation here that may come in useful.


Installation guides
To install emoncms on your own server have a look at these guides:

Let us know how you get on with it.

Open source sailing technology to clean up oil spills

What a great explanation of the importance of open hardware for developing environmental technology and the right conception of business where purpose comes first and profit is there to make the purpose happen rather than technology as a means to make profit, excellent!

emonGLCD V1.4

Introducing the current version of the emonGLCD. This post is a bit later than planned, we have actually been selling the V1.4 through the shop for the past month or so. This version features some minor incremental improvements rather than a new design. 

The main changes to this revision are:
  • This LCD power is connected to the 3.3V rail instead of instead of 5V. This will fix the problem with the LCD going blank due to over voltage, discussion thread here. *
  • The external power connection now routed through voltage regulator this means it can accept an input from 5-12V
  • The push switches are now active high, each with their own 10K pull down resistor, R7 and R8 are two additional 10K pull down resistors. 
The emonGLCD sketch examples on GitHub have been modified to work on the V1.4 as default. If you have V1.3 then you will need to uncomment the line that enables the internal pull up resistors (line 116 in emonGLCD_HEM) You will also need to comment line 199 and uncomment line 200 to change the action to active high rather than active low.

All other functions work exactly the same as previous emonGLCD versions. 

See the bottom of the main emonGLCD documentation page for a full change-log detailing the different versions over time. 

*Running the LCD at 3.3V instead of 5V is now within spec for the LCD unit, however running the LCD at a lower voltage did flag up an error in the orientation of C13 and C14 see forum discussion thread here. A note has been added to the build guide to instruct the insertion of C13 and C14 the opposite way round to what is marked on the PCB. 

emonGLCD V1.4 - Assembled (RFM12B missing)
emonGLCD V1.4 PCB - Front
emonGLCD V1.4 - Rear
The emonGLCD SolderPad page has been updated with the V1.4 Schematic and Board files:

Triac based MK2 PV Controller by Calypso Rye

Calypso Rye writes:

Based on the standard VI sketch which uses calcVI() in EmonLib, I’ve had a system in place for the last couple of months which diverts surplus PV power to our immersion heater. This system has proved to be both effective and reliable, and I am most grateful for everyone who has helped me along the way. The main downside to this arrangement is that it requires an expensive item of third-party kit to distribute the power. (I know that others have found cheaper ways, but my Carlo Gavazzi unit cost me £70).

Other contributors to this forum have shown that a standard triac can be easily controlled by an Arduino. By using a zero-crossing detector such as the Motorola MOC3041, it should be possible for the Arduino to allocate mains cycles directly to the load rather than delegating this task to a separate device.

A Mk2 system of this type has been working in our garage for the last few days. The sketch and a schematic diagram are attached, its main features being:

- a comprehensive 'debug' mode which allows real world conditions to be simulated ;

- a continuous mode of operation, for both measurement and distribution of power;

- an "energy bucket" concept which gives precise control of surplus power;

- interleaved windows for measurement and generation, each only 20mS;

- a rapid response time to changing conditions (50mS);

- suitable timing for 'arming' a zero-crossing trigger device;

- a single LPF which determines the dc-offset of raw VI samples;

- a programmable safety margin for biassing import v. export;

- minimal calibration is required.

Read the full post on the forum here:

Single AC power supply + voltage sensing

The idea of using the same AC-AC power adaptor for both sensing voltage and supplying power to emonTx has been discussed on the forums for months (see this topic), and about six weeks ago Glyn posted a simulation of a possible circuit.

I had the time this weekend to give it a try, bought the necessary components and put it all on a breadboard. After a sleepless night I can confirm: It works!

Here is my messy setup:

Small modifications had to be made to get it to work: I added a 1uF cap between 3.3v and GND to filter out some noise and redefined the voltage calibration coefficient in the code.But the main problem (took me all night to figure it out) is that the usual emonTx sketch wont work straight ahead. The line that lights up the LED (on pin 9) at the end of the setup loop has to be commented out, otherwise the setup won't work. It's no problem to flash it 2ms after each packet is sent, but apparently having it on in the beginning will prevent the program from starting. Maybe there isn't enough current to do it and move on (I must say that I use 10k ohm resistors for the voltage dividers). If it's not that then maybe full wave rectification could help.I used a humble Xprotolab to measure the Vin, Vout and at some other points in the circuit. It behaves almost exactly like the simulation. fft also shows very little noise.Would be great if other members could repeat this experiment to see if the results will be the same.Next step: Voltage sensing on the base ;)