Troubleshooting Bicycle Dynohub and LED light conflict.

I bought a Shimano bicycle Hub dynamo and a Raleigh RSP2 LED bicycle headlight. When working together they are very impressive, casting a beam that makes night cycling much easier with an impressive ability to see and be seen. However from the first there were problems, such as the light occasionally stopping working and the on/off switch never working at all. Eventually the system stopped entirely. As I had bought a second headlight, originally for another bicycle, I fitted that and sought to troubleshoot the first.

The light has no meaningful instructions, despite having two wires (of different colours) and two (unmarked) terminals. This had made the initial installation difficult, especially as I also wired a rear light that did have polarity marked on its terminals. The rear light turned out not to be the problem.

To put the conclusion first : the Shimano hub connects one side of its AC output to the axle and hence the bicycle frame. The RSP light connects one side of its DC circuit to its mounting bracket and hence (usually) the frame. It is almost certain that any installation of these components will conflict. Depending on the specific wiring the light may however appear fine, although it flickers more at slow speed than necessary. It will however be being operated without current limiting and presumably be likely to fail prematurely. More details are below, but it is disappointing that this problem is not well publicised on bicycle fora.

The light seems to be a sealed unit and eventually I had to destroy it to open it and inspect the circuit. Investigations before I opened it gave no real clue as to the specific wires/terminals : in fact, all seemed to be shorted together according to my multimeter.

On disassembly the positions became clear. The external wires and the terminals are directly connected in pairs (specifically the black/white wire connects to the left-hand terminal when viewed from the rear, and the white wire to the other). Internally the wires are connected by a Transient Voltage Suppressor (P6KE9.1CA) i.e. it clips the AC to a nominal 9.1V peak value. This seemed to be faulty, conducting at all voltages, hence creating the apparent short between terminals seen by my multimeter. I suspect this to be the fault that finally caused my lamp to fail, but not the primary problem as discussed below.

The black/white wire is only distinguished from the white wire in that the latter is internally connected to the on/off switch. This is consistent with the lack of exterior markings on the terminals, although somewhat inconsistent with using different colour wires at all. It should not really matter which wire is which since they are connected as the AC inputs to a bridge rectifier. However it does actually matter in the fault condition described below, because the switch is attached to one particular wire.

The DC side of the circuit consists of two resistors in parallel, the pair then in series with the LED. In principle this is a simple circuit, typical for a LED, of a current limiting resistor on a DC circuit, with the bridge rectifier converting the AC to DC and letting the LED illuminate on both the positive and negative AC cycles. However the positive side of the LED (in fact the whole metal plate on which it is mounted) is in contact with an aluminium spar that forms the backbone of the light and presents a threaded hole for attachment to the bracket and hence the bicycle. This is likely to lead to electrical contact with the bicycle frame, especially as a metal bracket is supplied – assembled and connected to this spar. This spar may well also form a heatsink as it is in electrical and thermal contact with the LED backplate and is a piece of costly aluminium used where plastic would have been structurally adequate, so removing it may be unwise.

The electrical contact to the frame is the problem. Unlike some hub dynamos, Shimano hub dynamos are also electrically connected to the bicycle frame and for this light this shorts one AC input with the DC positive line. This is an especial problem as it circumvents the current limiting resistors used with the LED. There are now effectively two cases depending on whether it is the white or the black/white wire that is connected to the frame (recall there are no instructions). If the white wire is connected to the frame, then the on/off switch will work as expected and the light will appear to work fine. However what is actually happening is that the LED is only active on half the cycles and is working without the current limiting resistor. On the other half cycles, current still flows through a pair of diodes but the LED is out of the circuit. In the other case where the black/white wire is the one connected to the frame, the situation will be the same except that the on/off switch will not work (the light will always be connected somehow). This latter case matches exactly the symptoms I saw, although I did not realise the low speed flickering was worse than the design intent (given an AC supply, with no smoothing, some flicker is inevitable).


As the light’s case does not appear to be designed to open without destroying the headlight, an external solution is preferable. For attaching the light, the spar has a threaded M4 hole in a block with a local diameter around 8mm, i.e. could be drilled out to 5mm or 6mm diameter and an insulating sleeve placed around the original M4 bolt. A simpler technique without risking voiding the warranty is to use an insulating bolt (e.g. nylon) in the original hole (M4 at 25mm long will suit). Both of these techniques should be possible without opening the case – I have only tried the latter. The net effect is to insulate the light’s DC circuit from the bicycle frame and hence avoid a short to the AC circuit.


To probe whether the above analysis was correct, I used a MCP3008 Analogue to Digital Converter connected to a Raspberry Pi Nano to achieve around a 1 kHz sampling rate of both voltage and current, the latter using a ACS712-based sensor to convert current to voltage. The results are as follows, and confirm the above analysis as far as I can tell :results

Wider applicability

I have only tested one light from one manufacturer, and cannot tell if other lights are affected. However the fact that the symptoms were not clear cut could mean the problem is widespread yet unreported and many people are operating lights with greater flickering, without current limitation and with the unknown risk of premature failure.


When using a hub dynamo that is not electrically insulated from the bicycle frame, the RSP2 light I bought needs to be installed carefully (with changes to its supplied components) to avoid appearing to work while actually operating out of specification, adding extra drag and perhaps being damaged. The lack of any manufacturer instructions (let alone ones covering this issue) make it highly likely the light will be installed wrongly. The problem might be widespread. This cost me at least one LED headlight. I hope the article helps you avoid that.

Car Battery Tester on Steroids

Draper make a car battery tester that is a resistive element, designed to draw 100A from a 12V car battery; a toggle switch; and an analog voltmeter. This is all housed in a case and has clamps to connect to the battery. The analog voltmeter is read by eye after the load is applied for 15s. Ultimately this is crying out to be hacked into something more interesting. That ‘something’ is now an automated system that monitors both current and voltage over time and can export results.

Battery Tester.png

My hacked device is based around an Atmel AT Mega 8 microcontroller. The device is designed to firstly draw power from the 12V car battery under test, and on command from a trigger switch, record a test within its EEPROM. When disconnected from the car battery and connected to a USB host, it senses that fact (via voltage levels) and powers itself instead from the USB bus and (by pretending to be a USB keyboard) now writes the EEPROM values back to that USB host as tab-separated number columns. This is after an initial preamble describing the system, the test conditions and the firmware version. This can be used to populate a spreadsheet, and the results graphed. This is an example of the results from a brand new battery, showing the initial voltage, the drop under load, the recovery over time, and (in red) the current load :

Test example

The data is produced by two inputs to the microcontroller’s ADC pins. Firstly a resister potential divider is used to map the ~12V battery voltage to something below the 5V regulated supply to the microcontroller (High resistance values should be used to limit current). Hence a voltage trace is obtained. Secondly a solid state current sensor (an ACS755LCB-130-PFF, Hall Effect High Current Sensor) is inserted into the current path. It produces a voltage proportional to current, with the voltage read by another ADC pin on the microcontroller.

Hardware Design

The tester I obtained second-hand from eBay had a defective toggle switch, and the obvious replacement to allow automated operation was a car starter solenoid since these are effectively relays designed for this very purpose. I obtained one second-hand on eBay, and (when driven by an intermediate FET) this was happily controlled by the microcontroller. This was a few years ago, and it now looks as though 100A solid state relays can be obtained for similar prices : this might be a better idea, as it would also avoid a safety problem that I had to design around (below). That said, the solenoid provides a nice audio indication of the test starting and stopping.

The device operates well within the capabilities of the AT Mega 8. There are outputs to four LEDs (some bicolour) for status information to the user. Inputs are either ADCs; or to sense the microswitch or the solenoid status. A socket to the ISP pins are provided to allow firmware update.

As noted above, the device emulates a USB keyboard and this is achieved using the V-USB Driver, with structures/ideas from Frank Zhao’s USB business card.

I had thought this would be simpler than the Ethernet connection I used on, for example, my clamp meter conversion, but other than having the advantage that USB provides power, it was just as complex. I had been thinking also that USB was more universal and does not require bespoke software on the reading machine (especially as I might need to loan the device to people), however now that I can implement a (rudimentary) HTTP server on the microcontroller it would have been far simpler to access the data via a web server and I would do this if I undertook the project again. Alternatively writing direct to a flash card is an option, and this would both obviate the need for a separate communication system and solve the problem of limited EEPROM storage (below).

In terms of space, the starter solenoid, FET and current sensor fit within the original envelope of the tester. The lower power components, although they could possibly have fitted as well, are kept away from the heat and large currents by mounting in an old floppy drive metal case, which happens to have the same width as the tester and is riveted to stand proud above an air-gap atop the case. The whole is robust enough to live in the garage.

Software Design

The microcontroler is programmed in C, and primarily operates as a finite state machine moving from pre-test to test etc on command or timer. Overlaying that is a regular timed interrupt (10Hz) to service the LEDs etc. Some of the LED behaviour (e.g. mark-space flicker) is designed to minimise the power drain on the USB (theoretically only 100mA is available and, while the microcontroller uses very little, four LEDs can eat into that)

The primary design constraint is the size of the EEPROM into which the data is stored (512 bytes). Although the AT Mega 8 has 2kB of SRAM, the operation mode for this device has it powered down between connection with the battery under test and re-energised (perhaps days or hours later) to connect to a computer. There are several trade-offs possible – the sample rate for instance varies for the pre-test, test, and recovery phases deliberately to balance maximum information at interesting times with sample period length. Only 8 bit data is stored, and the voltage is scaled before storage to maximise resolution, based on an assumption of allowable values. The firmware had to be changed once I discovered it was not safe to assume that a new battery would not exceed 12.5V unloaded.

During the actual test period, the device measures current as well as voltage. As there are spare ADC lines, I also recorded the voltage across the heating element during this period (i.e. excluding any voltage drop across the solenoid) at the expense of the need for some more storage, but this turned out to not differ significantly from the full battery voltage.


There are several safety issues, in addition to those already inherent in the device and working around car batteries. Notably, as a 1kW heater the device could burn people or potentially start fires. However adding an element of software control brings new problems.

I designed the main safety feature as follows. The test is initiated by closing and holding a microswitch. The microcontroller will terminate the load test after 15s, but for safety it must also terminate if the microswitch is released sooner. The important safety element of the design was to ensure that these were independent systems : it would be no use releasing the switch if this merely told the microcontroller to stop as this would leave the safety problem in software and not create an independent system. However it was also necessary for the initial press on the switch to tell the microcontroller to start; and for release to be sensed by the microcontroller so that it would not reapply the current if the switch reconnected. The solution was to tie the FET gate to 12V via a 10k resistor. The microswitch then connects the gate to a lower voltage derived from a pin on the microcontroller and potentially overpowers the first resistor, but with the microswitch open, the microcontroller gets no vote. Initially this pin on the microcontroller is set to be an input, without an internal pull up. Hence it senses when the microswitch operates, but the FET is not activated. The microcontroller switches the pin to be an output, but leaves it high (5V) which still does not activate the FET. The recording cycle starts, and at the appropriate point the pin is driven low, activating the FET. The solenoid has a convenient 12V output when activated, allowing a LED to indicate the test is underway, and a separate input on the microcontroller to sense this fact. Since releasing the microswitch will unilaterally close the FET, this second sense input allows the microcontroller to cancel the cycle (preventing restart) in this abort condition. Altogether this should ensure the device can always be stopped safely without ever requiring the clamps to be released under load with the associated spark hazard.

A significant safety issue is that, while the original metal box is insulated from both battery poles, the use of a metal starter solenoid whose case was connected to its earth made it necessary to earth the tester’s metal box (as the solenoid was too large to be isolated away from the box, indeed it required some metal cutting to fit). This increases the risk that the positive pole might short to earth; but also has the particular problem that if used to test a battery in a car with a positive earth (unusual, but not unknown) there would be a great risk that the tester case would touch bodywork and short. The solution was simply to only connect the case to earth via a fuse of high enough value to allow the solenoid to operate, but low enough to blow otherwise. 10A was suitable.

Possibly unnecessarily, but I protected every microcontroller input with a tranzorb spike suppressor of 4.7V. They are cheap, and it was not clear how switching 100A in close proximity would affect the controller. A 15V transorb protects the whole device (in parallel across the 12V input), as in series does a 1A blade fuse and a diode to protect against reversed connections. Despite all this, I believe it is wise to enforce a prohibition about connecting the device to a computer while the test is on going, relying instead on storage.


The functionality of the machine is probably fairly clear from the instructions now printed on the faceplate (below) and the graph of outputs.


IoT Clamp Meter

Maplins sell a cheap clamp meter that fits neatly in the palm of your hand. However a much more useful device would be a network connected meter that could read both current and waveform information, therefore being a ‘smart meter’ that is part of the Internet of Things. One application would be to record a time trace of current for a given domestic appliance, for example a dishwasher through its operating cycle, aiding diagnostics for repair, especially if a previous trace exists of the machine working correctly.

Hardware Design

The block diagram of the adapted system is as follows:

Block diagram

This is produced by removing the existing circuit board from the clamp meter (only retaining the clamp sensor itself and the case) and filling the remainder of the case with a micro-controller and an Ethernet board. There were very few steps in the physical circuit, with most functions now in software. The physical circuit used an Op Amp to amplify the initial signal; the micro-controller (an Atmel AT Mega 328P) recording the voltage with one of its integral ADC lines; and an Ethernet interface (based on an ENC28J60) connecting the machine to the outside world. It no longer has a local display, although an added LED returns some status information. The In-system Programmer pins are available via a socket, allowing easy firmware changes. The link to the Ethernet is also via the same SPI interface used by the programmer.

These are some before and after pictures:

Before and After.png

Safety point. I believe the pick-up coil is a current transformer and this does mean some counter intuitive points for those used to more usual voltage supplies. For a voltage transformer, one expects to increase a resistance to decrease current and so limit things to safe values. A current transformer will instead endeavour to drive a constant current, and hence connecting it across a higher resistance (and an air gap can qualify as a high resistance) will generate more heat, not less (see the Safety section of the Wikipedia article)

In particular, using a current transformer from an older, non-digital meter seems likely to have a lower turn ratio and hence more dangerous secondary. You should be familiar with these effects before implementing something.

The initial pick up involved passing the transformed current through a resistor and using an Op Amp to sense the voltage drop across that resistor. The Op Amp was chosen to be a single-, rather than split- power device (in this case a LM358N) to allow the shared use of a 5V DC supply to power it and the micro-controller. The bias and gain on the Op Amp were set (via resistors) to achieve a clean waveform with nearly full scale deflection (i.e. not quite clipping at either end) for an input of around 80 Amps to the sensor. This is a credible figure to cover the range over which the main supply to a house might vary. Using a clamp meter on an individual appliance is not normally possible, because the current enters and returns in a single lead carrying both Live and Neutral. This is actually an opportunity however, because by implementing a short extension lead whose Live and Neutral are passed in multiple loops in opposite directions through a short loop of conduit which the clamp meter can encircle, one effectively makes an amplifier.


Three wires in each direction creates a x6 amplifier, which means that a full scale deflection of 80A corresponds to about the 13A of a standard switched appliance, allowing more accurate measurements of individual appliances. Further this design means the meter need not itself physically switch scales, which is advantageous in avoiding an air gap for the current transformer (see the Safety point above).

The microcontroller needs very little ancillary hardware; mainly just capacitors, to stabilise the power supply and reset pins, and the status LED. The ENC28J60 provides a 25MHz clock, so the microcontroller does not need its own crystal circuit, but does divide that clock by two to operate within specification at 12.5MHz. Most of the microcontroller pins are unused. Given that there are several unused ADC pins, an obvious enhancement would be to provide mains-synchronised low-voltage AC power to the device, which it could rectify for its own power, but sense via a spare ADC channel to derive phase information to compare with the current traces.

Since the ENC28J60 was a 3.3V device, a voltage level shift was required between it and the micro-controller. In hindsight it would have been better to design it to use 3.3V throughout.

A particular problem with the specific ENC28J60 module I used was that it appeared to be mis-wired on the Ethernet side. Some Googling (now a dead link) suggested this was not an unknown problem, and in my case it was solved by producing a mis-wired Ethernet cable to compensate. Specifically I swapped wire 1 with 2 and wire 3 with 6 (a normal cross-over cable switches wires 1 with 3 and 2 with 6). Although modern self-sensing switches will correct such things, the direct connection to a PC (see below) may require it to be right : but other ENC28J60 modules may be correct anyway.


The microcontroller is programmed in C. I had previously produced a full stack of TCP/IP/Ethernet code (on which I will blog later) for the AT Mega supporting various protocols. However only ARP, ICMP, DHCP and UDP are needed in this application. Although I had written a driver for a legacy ISA card for the data link layer (based on ideas from David Clausen), an ISA card was far too physically large for this device and I had to use the ENC28J60 for which I used Guido Socher’s driver (from Tuxgraphics). I would note that Tuxgraphics and David Clausen’s work were the primary inspiration for this device.

The adapted clamp meter uses a locally administered MAC address (as the ENC28J60 card does not come with a global one assigned) although any MAC address could be set in the software. It will seek a DHCP server over the Ethernet link and accept whatever IPv4 address it is given. If it does not find a DHCP sever, it can be setup to also use a defined, static, IP address on the LAN or to assign itself a known IP address in the APIPA range (169.254.x.y), which is the same behaviour as, for example, a Windows machine that cannot find a DHCP server. On this basis it can be used directly connected to a PC or laptop without a LAN, or can be used across a LAN supported by DHCP. To assist setup, it will respond to a ICMP PING (and, less human-friendly, an ARP packet) once it has an IP address.

The work specific to the meter application is relatively trivial. A bespoke UDP packet (i.e. with appropriate magic number) directed at the device will cause it to respond with a packet containing a set of samples from the ADC spanning one 50Hz cycle and a summed current value. Only one return packet is required as there are around 200, 16-bit samples. For memory related reasons the code limits packets to 536 byte payloads which, when combined with a 20 byte UDP header and a 20 byte IP header corresponds to the 576 minimum datagram size required for IPv4 compliance (RFC 791) without fragmentation. UDP packets can be transmitted in quick succession (<1s spacing) to obtain a real-time trace of current consumption.

Although it would likely be well within the capability of the AT Mega, any further processing can take place at the receiver end where far more compute power is likely to be available. For future enhancement, the packet specifies which ADC pin (from the choice of 0 to 5) the microcontroller should read, enabling perhaps voltage-phase information to be returned.

Since the clamp meter uses a 12.5MHz clock and the AT Mega can achieve its maximum 10 bit ADC resolution only at sampling rates below 200kHz, the sampling rate needs to be reduced and the AT Mega prescaler is used at its maximum setting (which allows the full voltage resolution) as well as taking groups of three samples but only recording one from each group. On this basis, 188 samples were found to correspond to a full 50Hz cycle.


In principle, using items from the Internet of Things on your home network is the IT equivalent of allowing people into your house to rummage unsupervised. However the benefit of producing your own IoT devices is that you have tight control of their behaviour (the device will silently drop all packets that are not ARP; PING; expected DHCP responses; other UDP packets without the magic number or with malformed checksums etc). The code is also relatively short and easy to check. Importantly, and unlike many other devices such as home routers, the device cannot be re-programmed through the Ethernet interface. Instead it is flashed through the out-of-band SPI system (although the ENC28J60 is attached to SPI, it does not control the necessary reset line to initiate programming).

The microcontroller with relatively limited computing power will have no significant resistance to a DoS attack, and anyone who knows the magic number can determine your power consumption trace, but these are hardly material threats behind a firewall and possibly not even so if the device is directly connected to the Internet.


Monitoring the main feed to the house shows both waveforms and current draw very clearly The main graph shows current draw over time, and the insets show the current flow over the AC cycles.

Trace 1

Initially there is low current background (probably mainly CFL lights), with a heavily distorted current spectrum. Although the cycle is clear, it is patently not sinusoidal. Adding significantly larger and mainly resistive loads of heating elements (kettle, dishwasher and (tungsten filament) security light) draws notably more current (enough that their individual switch on times can be seen) and this now approximates a sinusoid.

A second set of results show the pattern of the dishwasher heating element over time and the sinusoidal addition of a kettle. But at one point the microwave is used alone (other than background) and has a very distinctive current draw of its own.

Trace 2

Overall this should be a useful diagnostic tool.

Hacking a Digital Photo Frame as a World Clock

So, exploiting these ideas I hacked a Kitvision digital photo frame.  Cut each of the RGB lines on the board and inserted switches (74HCT4053).  Hooked it up to an AT Mega 328P microcontroller running code derived from Peter Duffett-Smith’s Practical Astronomy with your Calculator and therefore calculated the daylight terminator across the Earth that matches a photograph of the Earth displayed on the frame.  By cutting some of the RGB signal at the right moments you get the following :


The trick is to do the calculation during the flyback period, and use interrupts to do the time critical cutting of the picture.  The AT Mega has no trouble keeping up – the quantisation of the jagged terminator line is however the timing fidelity driven by the clock.

I did this in 2010.  I have forgotten some of the details – I think it was cutting the R of the RGB that got the impressive night-time effect.  I also got the eclipse shadow calculations working on a PC but was having trouble shoe-horning that into the AT Mega’s 32k code limit, so left it at that point.  This may inspire someone else.