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.

Safety

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.

Operation

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

Faceplate.png

Cisolate : PCB construction

I have the greatest respect for the Visolate program, currently available at GitHub. It produces Voronoi Isolations of PCB traces enabling PCBs to be produced on a CNC mill. The milled paths are centralised in the available space thereby maximising current carrying capacity and allowing a single milling pass to separate two traces.   However Visolate was initially a research project and unsupported for a while. As that time, I started to develop an alternative, based on a Cellular Automata approach, which also met my needs by performing some optimisation of the cutting paths (in order to reduce milling time) and producing a (likewise optimised) list of drill points as a G-code file. As this program is based on a Cellular Automaton, rather than a Voronoi approach, I have always called it Cisolate (although actually it may just be a different way of producing Voronoi diagrams). Cisolate is also available on GitHub. Here is an example of some of Cisolate’s output for the test PCB used by Visolate:

Results.png

On the left is the board with the isolation paths identified in green. In the middle is the automatically identified set of drill positions and an approximation to the optimum order in which to drill them. On the right is again the isolation paths, but in red are the unnecessary transits (where the mill lifts off the board and moves to a new location). The quality of the optimisation is indicated by the limited number of red paths.

On this particular example, all processing was complete in 10 seconds on a not especially recent machine, although note that the code operates in parallel using multiple threads (configurable) and can therefore use all available processors. Significantly more complex boards are still analysed in minutes, with the majority of the work being in the optimisations.

While having no wish to criticise Visolate, I think Cisolate offers the following advantages

1. Cisolate uses native Java libraries, so there is no need to install anything beyond the JRE (This was a design intent)

2. Cisolate operates purely from an image, so can be used in various situations where a Gerber file is not available, including potentially repair after scanning a PCB image. This is paired with the weakness that it cannot directly use Gerber files as input, but other programs will convert Gerber files to images.

3. Cisolate undertakes optimisation of the G-code so that it produces far fewer transits (for reduced manufacture time and less wear-and-tear) and shorter code.

4. Cisolate automatically produces a G-Code Drill file (as well as a G-Code mill file and/or an etch image). Likewise there is a disadvantage that a PCB image must include the drill points : not having drill points does not just mean there is no drill file, it means traces are not anchored and are seen as dead ends that the process removes.

There are two other interesting outputs from Cisolate as shown below:

Others.png

On the left is the automatic determination, based on the Cellular Automata output, of which points are three-way intersections (blue) or four-way intersections (magenta) in the milling path. This enables the extraction of individual line segments that can then be combined in an optimum order. I was especially impressed with the CA, which produces highly robust results. The lack of any need to process special cases was notable making the coding much easier. On the right is a ‘heat map’ which indicates the generation of the CA by which a given point had been determined. The benefit of this heat map is that it allows the later path optimiser to have an idea of the freedom it has to smooth or move a path. Black indicates original copper and may not be encroached upon. The more white the area, the greater freedom there is to change (with white itself being the original ‘watershed’). White dots are drill points and cannot move as they are surrounded by copper.

Methodology

The overall process is for a Cellular Automata to thin the areas between the copper tracks to their median positions. The advantage of the CA is that its output is kingwise-connected pixels such that the nodes of the diagram are clearly identifiable via certain pixel patterns. One-way intersections are points – ipso facto drill locations. Three- and four-way intersections are also robustly determined (diagram above). Given the identification of the nodes, this makes it easy and unambiguous to extract the individual lines between nodes as individual paths to mill. There are now three optimisations. The order in which the drill points should be drilled is a classic travelling salesman optimisation. The mill traces are similar – but note they are lines not points, and only the transits between the start and end of the lines are optimised at this point. There may also be a need to reverse the order in which a line is traversed. Finally the milling lines themselves are optimised (smoothed) by attempting to fit circular arcs to them subject to the heat map information. This minimises the number of individual G-code lines, within certain constraints. It leads to huge reductions in file size and probably allows much better look ahead optimisation by the ultimate cutter, at the expense of slightly worse fit to the exact solution

The core engine implements a cellular automata method, derived from that due to Guo and Hall (Parallel Thinning with Two Sub-iteration Algorithms, Communications of the ACM 32(1989) 359-373,759) also described in Knuth TAoCP 4A (7.1.3) for thinning an image. I had to add some further cells (shown below) to remove dead-ends (you do not want to waste time milling an electrical isolation path that doesn’t reach another path as it won’t isolate anyway). Note however that this is the reason that drill points must be marked on the image (see above). The lack of a drill point makes a pad look like a needless salient that can be removed, whereas the drill points anchor it.

Extra cells

The optimisation currently uses simulated annealing and seems to work well, although SA always has more tuneable parameters than I really like.

In the absence of a standard pattern, Cisolate uses the following design pattern for the Travelling Salesman optimisations, which separates the Optimiser (currently Simulated Annealing) from the Seeker (that records the current result and provides alternative perturbations to try) and provides an Optimee function as a metric to optimise against. The whole is a Runnable, as optimisation is a slow process so the ability to pass it to parallel threads is desirable.

Optimisation Pattern

This pattern is not used for the G-code smoothing optimisation as that just conducts an exhaustive search based on the fact that G-code only allows straight lines or circular arcs. Hence these are the key primitives. Arbitrarily, allowable arcs are constrained to a fixed set to ease computation. Again, arbitrarily, the radii of this set follow a geometric progression. The largest radius is set s.t. w.l.g. it may be considered a straight line. Hence, during the computation, only ‘circular’ arcs are considered, some of which are later assigned as straight lines when the G-Code is written.

There is a ‘de minimus’ concept in the optimisation to decide whether it is worth worrying about differences, which allows a reduction in the number of different sequences on this basis.

The process is to first determine fixed control points and then, subject to avoiding copper traces, conduct a greedy optimisation to find the best (closest fit to original curve) arc through each pair of consecutive control points. Then again greedily, join adjacent control points that have identical radii between them. The process continues by merge further adjacent curves if a compromise radius does not violate a de minimus setting and then jitters control points to facilitate further merger.

This screenshot of the program shows the effect of optimisation on the G-code after the curves have been straightened (note especially the situation near the top right). The individual tabs (Board, Isolations, Drill, Drill Path …) show different views of the situation (as used for illustrations throughout this blog) and they are all linked together, so that pan and zoom affects them all at once and the views can be tabbed between.

Sceeenshot

Finally, for a more complex board, this is this board from an individual’s projects on the web to prove that Cisolate can just work with an image directly.  After a small amount of tidying (there is no point in ‘isolating’ text or keeping orphan pieces of copper). After processing for fewer than 5 minutes, these are the results (you may need to zoom in):

drillPaths

milling.jpg

Status

Having tested on about twenty boards, I am confident that the technical processing is correct and that a GUI and command line version are working so that I can use them. At the moment however the system is not user friendly – for instance only 24-bit bitmaps are accepted and some parameters (etch width, drill plunge depth) are hardcoded.

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.

Adapter.png

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.

Software

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.

Security

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.

Results

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.