Tuesday, March 31, 2015

Repurposing the Crazy Clock as a phonograph strobe

So, I don't know what made me sit down this evening and do this, but it occurred to me that the n/n+1 fractional arithmetic timer stuff I had done for the Crazy Clock could be put to another purpose - generating 60 Hz for a phonograph strobe.

The Crazy Clock hardware is pretty well suited to the job - any 1-3 volt power source can be turned into 3.3 volts by the built-in boost converter, and I use LEDs in the test harness, so I know it can successfully drive them.

Getting 120 Hz (since we want the light to blink at 60 Hz, we want to toggle it at 120 Hz) from the 32.768 kHz crystal is simply another exercise in the n/n+1 fractional division machinery that already drives the Crazy Clock firmware. And by toggling them both out of phase, we can ignore the polarity of the LED when we hook it up.

Setting the timer prescaler to 8 yields 4.096 kHz. Divide that by 120 and you get 34 + 2/15. 34 * 13 + 35 * 2 = 512, and 512 divides into 32768 evenly. Some of the light pulses will be 244 µS longer than others, but the 60 Hz average should still be within 10 ppm otherwise, which is the tolerance of the crystal.

Here's a 240 fps slow motion video of the strobe:


 Phonograph strobe generator for Arduino
 Copyright 2015 Nicholas W. Sayer

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along
 with this program; if not, write to the Free Software Foundation, Inc.,
 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

 * This is intended to run on an ATTiny45. Connect a 32.768 kHz crystal and fuse it
 * for the low frequency crystal oscillator, no watchdog or brown-out detector.
 * Connect PB0 and PB1 to an LED. Either orientation will work. The two pins will
 * alternate polarity. When this firmware is loaded into a crazy clock, it will
 * just work - the flyback diodes will serve no purpose and the two series resistors
 * wil be correct for an LED.

#include <avr/io.h>
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/interrupt.h>

// 32,768 divided by (8 * 120) yields a divisor of 34 2/15
#define CLOCK_CYCLES (15)
// Don't forget to decrement the OCR0A value - it's 0 based and inclusive
#define CLOCK_BASIC_CYCLE (34 - 1)
// a "long" cycle is CLOCK_BASIC_CYCLE + 1

// LED pins. So that we don't have to remember which is which, we'll always make one
// the opposite of the other.
#define P0 0
#define P1 1
#define P_UNUSED 2

  // Do nothing - just wake up

void main() {
  ADCSRA = 0; // DIE, ADC!!! DIE!!!
  ACSR = _BV(ACD); // Turn off analog comparator - but was it ever on anyway?
  TCCR0A = _BV(WGM01); // mode 2 - CTC
  TCCR0B = _BV(CS01); // prescale = 8
  TIMSK = _BV(OCIE0A); // OCR0A interrupt only.

  DDRB = _BV(P0) | _BV(P1) | _BV(P_UNUSED); // all our pins are output.
  PORTB = 0; // Initialize all pins low.

  // Don't forget to turn the interrupts on.

  unsigned char lastTick = P0;
  unsigned char cycle_pos = 0xfe;
  while(1) {

// This will alternate the ticks
#define TICK_PIN (lastTick == P0?P1:P0)

    // Toggle the two pins back and forth.
    lastTick = TICK_PIN;
    PORTB &= ~ _BV(TICK_PIN);

    if (++cycle_pos == CLOCK_NUM_LONG_CYCLES)
    if (cycle_pos >= CLOCK_CYCLES) {
      cycle_pos = 0;


Wednesday, March 25, 2015

Raspberry Pi - transitioning between SD cards

When you want to swap out a Raspberry Pi model A for, say, a B2, one issue you are going to run into is that they moved to a µSD card holder. If your old A is using a regular SD card (that is, not a µSD in an adapter), then you're going to need to forklift the contents of your card over to a new one.

Well, that shouldn't be a big deal, right? All that's required is copying the filesystems from one to the other.

That's true, to a point... but what about when the target SD card is slightly (or vastly) smaller? I ran into this. I had a 16G SD card and bought a 16G µSD card and it was a few megabytes smaller.

Fortunately, I had a second Raspberry Pi and a USB SD card reader.

Take the old card and put it in the USB reader.

use "dmesg" to see where the SD card landed. If you have no other disk devices, then it likely will wind up as "sda".

As root, do a "resize2fs -M /dev/sda2"

This will shrink your Linux filesystem down to the bare minimum. When it's done, take note of how small it got. Add 500M as a safety margin to that and then as root run "fdisk /dev/sda"

Once there, use "p" to print out the filesystem. Then "d" and then "2" to delete the Linux partition. Yes, that's scary to do. Don't worry, we'll put it right back.

Next, do an "n" to create a new partition. It's a primary partition, and it's number 2. Use the same value for the start of the partition as was listed in the "p" printout earlier. For the ending, use "+" and then the augmented size you figured out earlier. When you're done, use "w" to write the partition table back out.

Next, do a "resize2f /dev/sda2"

This will expand your filesystem by the extra padding you added, filling out the now smaller partition you just created for it.

Once you're done with this, you can use 'dd' to make a disk image of the card. Eject it and insert the new card. Use 'dd' to write the image to the new card, ignoring any errors you get near the end (since the new card is too small). Those errors will be harmless, since we shoved the Linux partition close to the beginning of the card.

Once it's done, boot the new card and run raspi-config and tell it to expand the filesystem. When you reboot, the filesystem will be resized to fit the rest of the space on the card.

Once you do all this, the old card can be reformatted back to FAT32 and used for whatever you like. I use mine as a "sneakernet" drive for scanning stuff on our printer. It's easier than trying to use the network to do it. :)

Saturday, March 7, 2015

High power system design

I'm not going to pretend to be an expert, but I think a lot of makers out there want to design for high voltages but are afraid to. Others don't give the topic the respect that it deserves. I'd like to believe I'm somewhere in the middle. And for what it's worth, I'd like to offer my own perspectives on how to make PCBs that will handle high power safely.

First, we need to agree on what constitutes a high voltage. Once upon a time, I was doing some telephone wiring (this was back in the old days of analog POTS lines. Some of you youngsters will never have experienced a phone that had a cord that did something besides charge the battery). I had my fingers on the wires at the exact moment the line started ringing and I got a nasty buzz from it. Someone smarter than I was would have taken the phone off-hook before working on it. The take-away is twofold: high voltages are lower than you might think. Even without the 90 VAC RMS 10 Hz ring signal, POTS lines when on-hook were 48 VDC, which is just under what is often used as the 50 volt (peak) threshold for "high voltage." The second take-away is that you need take into consideration every possible state the line could be in. The on-hook voltage of a POTS line may be low enough to work with, but watch out when it rings! So for the purposes here, I'm going to take as my delineation a 50 VDC peak threshold. If at any time a signal is anticipated to have a voltage higher than that, then it's high voltage.

High voltages are hazardous because very small currents can be very powerful. The guiding principle, therefore, is to insure that any high voltage conductor is well isolated from anything else. If it's a wire in air, that means that its insulation must be rated to withstand the working voltage of the wire inside. For a PCB trace, that means that it must be separated from any other trace by enough space such that neither the air, nor any foreign matter that might be on the surface of the board, might cause an arc. In PCB design terms, this is called the creepage distance, and it is the distance between two adjacent conductors measured along the surface of an insulating material between them. A related term is clearance distance, which similarly is the distance between two conductors measured straight-line through air. Clearance applies, for example, to the uninsulated portion of two wires that are entering two adjacent pins of a screw terminal. Creepage applies two two traces on the board.

At this point, It's important to interject an important note. Soldermask is not an effective insulator. Soldermask's purpose is to prevent solder from bridging two adjacent traces and to protect the bare copper from corrosion from flux residue or the like. It's not there to impact creepage or clearance distances. For one thing, Soldermask is easily abraded or scraped away, and you obviously can't count on it having any insulating properties if it's not there. For HV circuit design, conservative engineering dictates that you pretend for the purposes of creepage and clearance distance measurements that the soldermask just simply isn't there.

By contrast, PCB material is a very effective insulator. Creepage distances do not count when traces merely pass over each other on opposite sides of the board. Effectively utilizing both sides of the board is an excellent way to help you achieve proper creepage and clearance. However, if you do put HV traces on the bottom of the board, then you must pay close attention to how you intend to mount the board in its enclosure once you're finished. You must insure that proper clearance is maintained with the bottom of the board. If you have no HV traces on the bottom, then in principle, you would not need to worry.

When designing for HV, proper design always begins with the schematic. Let's take a look, for example, at the HV Contactor board for OpenEVSE II:

Note the broken grey line that forms an area on the left side of the schematic. That area is the designated "high voltage" portion of the circuit. Think of the HV part of your circuit and the rest as being in two different countries. That line represents the border. And nothing is allowed to cross that border at all except for special isolated parts. In this design, there are 7 points where the border is crossed. One is an isolated AC/DC power supply module. One is an opto-isolated triac driver, four of them are standard opto-isolators, and the last is a ground connection that requires separate discussion. In all of those cases (except the special one), the components offer galvanic isolation between the two separate sections. This isolation is a basic safety requirement. The HV wiring is effectively a contaminant that you must keep completely boxed up and away from any possible human contact. It's only via galvanically isolating components that any indirect contact can be allowed. If you follow this basic rule, then in principle, the rest of the circuit can be deemed as safe and need not have special safety precautions taken.

There is one exception in this circuit to the "border" principle, and that is that this circuit includes a ground impedance monitoring function. A small, carefully limited current is allowed to leak from the HV supply to ground, and is measured on its way there. Normally such a situation would be an error, but in this case, it's a carefully constructed exception case to the rules of HV isolation. Exceptions to any rule can sometimes be made when other considerations demand them. They just must obviously be done with great care and thought.

Now, let's look at the board:

See that white line about 3/4 of the way up from the bottom? That line is the exact analog of the grey dashed line on the schematic. It's the border between the "safe" and "HV" sections of the circuit. Note that in the safe section, there's a floated ground plane, but there is none in the HV portion. This is simply because ground planes are an anathema to maintaining creepage distances. HV wiring should generally be kept clean and simple, and I can't imagine a circumstance where floating a ground plane through HV would be necessary or desirable. Note also that the only parts that are allowed to "straddle" that border are the galvanically isolating ones we pointed out in the schematic (the four opto-isolators are, in this case, actually four modules in a single component - the gull-wing SMD DIP-16 in the center. Note also, that it's actually drawn on the silkscreen as two duals rather than one quad, but it still works). Also, note that those parts don't straddle the line evenly. They're off-centered in a way that shoves the HV wiring as far away from the border as practicable. This is good for creepage to the ground plane.

OpenEVSE II actually consists of two boards. The second board is a logic/display board. In my design, one of the goals was to separate the HV and logic as much as possible. You can see the result of that in the design of the HV board above. There's as little circuitry as possible on the HV board, with the hopes that the design will need little, if any, troubleshooting. This is another hallmark of good HV design - KISS. Any time you need to poke at an HV circuit while it's powered up you're taking your life in your own hands. The less of that you have to do, the better. You can poke at the logic board all you want. In fact, because it's a separate board, you can have it sitting on the bench outside of the closed chassis that houses the HV board, which makes live testing reasonably safe.

Another good idea for design is to try and place some sort of safety device immediately inside of the ingress of HV, if possible. In this case, the AC in lines each terminate immediately in fuses before hitting the AC/DC converter. Additionally, the hot line hits another fuse before going to the contactor triac circuitry. The hot line of the relay test and the AC in also hit two large 150K resistors. Those resistors are spec'd as flame-proof resistors, meaning that they act somewhat like fuses when stressed and burn themselves to open circuits to protect the rest of the system. Note that, in principle, on the far side of the resistors, the voltage will be much lower, so we can get away with somewhat reduced creepage distances in the area around the opto-isolator pins, but having a respectful creepage distance to the ground plane section of the board is still a good idea.

The other part of high power is high current. High current is relatively easy to deal with. The guiding principle is simply P = I^2 * R. In this case, the power of interest is not the power of the current flowing through the conductor (based on its voltage), but the power that's lost as it flows through. That power will be lost due to the conductor's resistance, and will largely be transformed into heat. Heat is particularly pernicious because a heated conductor's resistance will increase, which leads to a positive feedback loop that will result in failure, quite possibly of the spectacular variety. If you have a circuit that draws 30A (typical for an EVSE - an electric car charger), and then introduce a resistance of a tenth of an ohm, the power dissipation over that resistance will be 90 watts - three times the power of a typical soldering iron you might use for PCB assembly!

This PCB trace width calculator is particularly helpful to figure out the balance of current flow, voltage drop, temperature rise and the like. Just keep in mind that at some point, if want to deal with really high current, you're going to find that PCB traces just aren't the right tool for the job.

Anyway, this is just my own observations and experience from the high power designs I've done so far. I don't claim to be an expert, and if anyone sees anything in the above that's in error, please let me know. I welcome all corrections - it's always a learning opportunity.

Monday, March 2, 2015

OpenEVSE II and Hydra status reports

The first batch of final boards for OpenEVSE II and the Hydra will arrive today. The designs for both were successfully prototyped already, so I have no doubt about the viability of these boards.

OpenEVSE II will be available in two formats, which differ only in the HV boards. One is intended for use with a line powered contactor, and the other with either a single DPST or two SPST 12 VDC coil relays. The contactor variant will only be usable at a single voltage, since contactors aren't typically agile from 120 to 240 VAC. But contactors are typically capable of switching much higher current. By contrast, the relay variant will work at any supply voltage from 100-240 VAC, but relays are typically only available up to around 30A.

Both HV boards are intended to fit in the OpenEVSE chassis available in the OpenEVSE store. You just need to drill new mounting holes, as the boards are slightly different sizes than the original OpenEVSE board.

Both variants include the full compliment of UL required safety checks. Of particular note is that the GMI test is now continuous while charging is in progress, and the ground current is limited to a maximum of 1 mA, which means it should not trip a normal household GFI.

The logic board now includes a standard OpenEVSE i2c header for further future expansion. It also has a RTC and a temperature monitor chip to measure the ambient temperature inside the chassis.

For the Hydra, there is a single HV board that supports only contactors (the case for an L1 capable Hydra is not compelling). It also now performs ground impedance monitoring and relay tests as well as a GFI self test whenever charging begins. It is available both as a standalone EVSE with a RTC, and as a splitter to facilitate sharing an existing EVSE.

All of the above are available for purchase right now at http://store.geppettoelectronics.com/ .

Wednesday, January 21, 2015

Final designs for OpenEVSE II & Hydra 4.0 are on their way

I've placed the order for what I hope will be the final versions of the OpenEVSE II and Hydra boards. I'm taking a bit of a chance in ordering them both at once, since I had planned to use one to validate the design of the other. But I've done enough testing with the OpenEVSE II prototype (0.3) boards that I'm fairly confident at this point.

New for the Hydra 4.0 design is ground impedance monitoring and relay testing. This brings the Hydra if not into full UL compliance, then at least asymptotically close. Originally, I had intended to leave the GMI system out of the "splitter" variant, but in adding a 1 mA current limit to the ground monitor circuit, I'm fairly confident that the test can be present and still not trip the GFI in the host EVSE - even if it's the ultra sensitive 5 mA type. If it turns out to be problematic, it can always be a "no-stuff" option on the AC board. Unlike OpenEVSE II, there won't be a voltmeter in the Hydra. There simply aren't any remaining analog pins on the controller. Even if that weren't true, there isn't enough room on the AC board for more HV components with sufficient creepage space around them.

OpenEVSE II is a reimagining of OpenEVSE. It changes completely the ADVPWR functionality. Automatic L1/L2 selection is done with an isolated analog voltmeter. The ground monitoring and relay testing systems can be done continuously rather than in isolation, as in the OpenEVSE base design.

Recent work has been done to add temperature monitoring to OpenEVSE. There isn't enough room on the logic/display board for an added sensor, but I did hedge my bets by adding an i2c header to the logic/display board. That can be used to add a remote i2c temperature sensor that can be placed in an interesting spot. But the ATMega controller chip has a built-in thermometer. It isn't tremendously accurate, and it can be affected by the controller's own activity. This has been particularly noted in testing with OpenEVSE, but in that case, the controller is mounted on the opposite side of the board from the main AC/DC power supply, which likely is responsible for quite a bit of conductive heating. OpenEVSE II's controller is well isolated from other nearby heat sources, so it should do much better. In any event, the temperature sensor is supposed to be a safety limiter rather than a critical measure of temperature (such as for a thermostat or the like), so its absolute accuracy is relatively unimportant. The real purpose is to attempt to shut down charging before the ambient temperature causes the controller to fail.

Saturday, January 10, 2015

OpenEVSE II logic/display board theory of operation

The OpenEVSE II design for the logic/display board is fairly well set by this point. All of the iteration lately has been on the feature set of the various types of HV/power boards. I thought I'd set down exactly how the various parts of the logic/display system operate.

I'll do this by showing one sheet at a time of the schematic and explaining all of what's there.

The first sheet is the power supply and GFI subsystems. The HV board has an isolated AC/DC power supply that feeds 12 volts to the logic/display system. EVSEs need +/- 12 volts and +5 volts to operate, so -12 volts and +5 are made with two DC/DC converters built from the venerable MC34063 DC/DC converter module. This chip can be used in buck, boost or inverting topologies, and we use the inverting topology to make a -12 volt supply rated for 50 mA max and the buck topology for a +5V @ 500 mA supply.

The GFI system is largely copied from a CR Magnetics application note. A capacitor is added to the amplifier stage to act as a low-pass filter, which adds some noise immunity. Rather than a second amplifier stage, the output from the first is simply fed into a comparator with a peak detector. That line is fed into an interrupt input pin of the ATMega chip that watches for a rising level. An interrupt service routine will quickly turn all of the relay output pins off.

There is a GFI test system, which simply consists of a current limiting resistor. A wire will go from that output and take 3 or 4 wraps around the GFI coil and then connect to ground. The code will pulse this line at approximately 60 Hz to simulate a ground fault. The expectation is that during this test the GFI will detect the pulses. The software will note a GFI failure if it doesn't.

The second sheet consists of the ammeter and the pilot generation and read-back circuitry. The pilot generator converts TTL output from the controller into +/- 12 volts. It does this using two pairs of transistors that make up a modified H bridge architecture. Two transistors are used to switch +12 or -12 volts onto the pilot output, and those two transistors are themselves switched on and off by transistors that are intended to translate the TTL levels into current flow to trigger the other two. Since the circuit is acting as an H bridge, it is critical to insure that the input is either TTL high or low and never a voltage that's in between. That could result in both output transistors being switched on, which would short +12 to -12 volts. R4 acts as a pull-up resistor to protect the pilot generator whenever the pilot output pin is in a high impedance state (which happens when the controller is being programmed or during and shortly after power-up reset).

The 1k resistor on the pilot output is required by spec to set the output impedance. The three resistors after that form a feedback network that scales the +/- 12 volt pilot to 0-5 volts to feed into one of the controller's A/D pins. The firmware will use this feedback to detect a missing pilot diode and the J1772 state requested by the attached car.

The ammeter is quite simple. It's a current transformer with a burden resistor and one leg offset to 2.5 volts. This is intended to keep the entire AC signal within the controller's input A/D range of 0-5 volts. Two zener diodes form a clamp to protect the controller from excursions beyond the acceptable range. The burden resistor must be carefully chosen. Too small and the ammeter's resolution will be poor. Too large and its range won't be high enough. The capacitor to ground on the anchored leg reduces noise in the readings.

The controller/display sheet includes the controller itself, which is clocked with a 16 MHz external crystal, the real-time clock chip and its backup battery, and the display. The display is the same design as the AdaFruit i2c RGB backlit LCD Arduino shield. JP3 is a bit tricky. It's not actually a separate connector, it's just the extra two pins for the RGB backlit LCD (the standard EAGLE part library only has a standard backlit LCD, which has only 16 pins).An i2c GPIO chip is used so that the I/O pins on the controller can be dedicated to EVSE functions rather than the display. The real-time clock chip also shares the i2c bus and has a CR1220 battery to keep the clock running during power outages or storage. The SPI bus pins of the controller are unused, and so can simply be connected directly to the AVR ISP connector for reprogramming. There are two solder jumpers present, One allows selection of the polarity of the backlight common pin for the LCD module. By default it's wired for common anode backlight LEDs, but changing the jumper (and the software) can allow use of a common cathode LED backlight instead. The other solder jumper connects the serial port's DTR pin through a capacitor to RESET. Closing that jumper will mean that transitions on the DTR pin will reset the controller. This is required if you want to upload new code over serial using an Arduino style bootloader, but is not recommended in any other context.

The FFC connector to the HV board has two otherwise unused pins (RELAY_B and AUX) that can be used for additional expansion functions in the future.

Saturday, January 3, 2015

OpenEVSE II design progress

The good news is that the design of the logic/display board has not really changed significantly since July. I have moved a couple of components around very slightly, but in general the separation of functions has really been quite a boon for the design.

When I last checked in, I had decided that the relay test functionality wasn't worth the trouble, so I converted it into a ground impedance test - which I knew was required by UL. I also replaced the original OpenEVSE L1/L2 test system (which also performed the ground test and the stuck relay test) with what I hope to be a reasonable isolated voltmeter.

Chris H corrected me, however. I thought a stuck relay test was unnecessary, but he said that UL actually requires one. So it's back in play.

What I've come up with is that the ground test circuitry is going to be replicated for a relay test line. The difference is that, while the ground test circuit has two diodes from each hot line and runs to ground, the relay test will simply run between the two hot lines on the load side, much like the voltmeter does on the line side of the relays/contactor.

OpenEVSE II relay board. This board works on both 120v and 208/240v, but is only rated for up to 24A charging.

OpenEVSE II contactor board. This board uses an external AC line powered contactor. The only limit on charge current is the contactor, but contactors generally only work at either L1 or L2 (not both).

Both variants have an isolated AC/DC power supply to produce 12 volts for the entire system. The relay variant has a 10 watt module and the contactor version has a 3 watt module. The difference is that the two relays draw 2 watts from the 12 VDC supply when energized, while the contactor is the equivalent of just an LED on the low voltage side.

Both the ground test and relay test hardware is nothing more than a comparator that feeds into a very basic peak-hold circuit so that the AC zero-crossing intervals don't count as "failures." The ground test is designed to insure that current will flow from at least one hot line to ground (for hot-neutral systems one of the hot lines will actually be a neutral line, so current flow will not be expected in that case). The test is a little trickier than it sounds. You can't naively put a pair of optoisolators in place - one for each hot line - from the hot line to ground, since a circuit path would exist from one hot line through its optoisolator to ground, and from there through the second optoisolator to the opposite hot line. That test would "pass" regardless of whether the ground impedance is high or low. You can, however, use a pair of (beefy) diodes so that, effectively, only one hot line at a time is presented with an opportunity to conduct through the optoisolator to ground.

The optoisolators are LTV-844S, which have AC emitters - each of the 4 independent optoisolators has a pair of diodes in inverted parallel (this is not shown in the schematic, which shows the unidirectional LTV-846S instead). Effectively, this means that the transistors see light proportional to the absolute value of the input voltage. The series resistors chosen are intended to try and keep the optoisolators in their linear range (if possible), and are also sized based on the power equation: P=E^2/R. Note that for the ground-fault system, the math is deceptive. The actual voltage is never more than 120 volts because the measurements are always relative to ground. In addition, each resistor only gets a 50% duty cycle, as the negative half of the cycle is blocked by the diode. For the 91k resistors, the worst case is 240 volts, which comes out to just under 2/3 watt. Lastly, all four resistors are flame-proof, so that they act like fuses and burn themselves out harmlessly if stressed.

The output side of each optoisolator is set up, more or less, with a classic voltage divider configuration. For the ground test and relay test systems, the result is simply compared to 1 volt by a comparator and peak-hold circuit. For the voltmeter, the result is fed into a non-inverting amplifier. As supplied, the amplifier is configured as a voltage-following buffer (unity gain), but gain can be added by altering the components without re-spinning the board.

The relay board has a simple common emitter switch with a flyback diode to switch the relay coils on and off. The contactor board has an optoisolated triac that's used to drive a (slightly) larger triac to switch the contactor on and off. Both the main triac and the driver triac are provisioned with snubber circuits which serve the same purpose as the flyback diode on the relay board: they provide a path for the coil collapse voltage to go when the contactor is switched off.