Sunday, December 20, 2015

Home-brew J1772 EVSEs

I've spent some time this morning and looked at some of the videos on YouTube of people showing off their home-brew J1772 charging stations. I have some concerns about a lot of them.

Now, my criticism doesn't apply to all of them. Quite a few of them are based on OpenEVSE, which does include all of the checks. In fact, an OpenEVSE based design recently obtained full UL approval. That said, there are some things I would change about OpenEVSE's design, and those things wound up being the design for OpenEVSE II.

The most frequent deficiency I see is a lack of a ground-fault interruptor (GFI). A GFI is particularly important in EVSEs for two reasons. One, the business end of the EVSE is intended to be used in all weather conditions. Two, the car itself sits on four rubber tires, which prevent the frame from being grounded other than via the ground connection of the J1772 cable. A ground fault in the vehicle potentially could energize the entire chassis.

The second deficiency I see often is a lack of ground continuity monitoring (GCM). In the above case, where a ground fault energizes the chassis of the vehicle, a proper ground connection would overload the circuit breaker feeding the EVSE if the GFI didn't stop the current flow first. If the ground fault in the vehicle existed and the ground connection was poor (and the GCM didn't detect that), then there would be no ground fault current for the GFI to detect until a circuit to ground was established - likely through the next human to touch the vehicle. Now, the GFI will trip, but that takes some time, so the human will still get a brief shock, which could have been prevented.

Lastly, the specification requires a stuck-relay test. This test insures that when the relay or contactor is switched off that there is no voltage present on the hot lines of the J1772 cable. If the relay fails in a manner where it's stuck closed, then all of the other safety systems are completely moot. A proper EVSE should at least produce a warning so that power can be removed and the unit repaired.

There is also the pilot diode test. The diode test allows the EVSE to tell the difference between a vehicle and a bucket of salt water. Obviously, turning the power on when the handle is "plugged in" to one of the latter would be a bad thing. This is accomplished by testing for both the maximum and minimum voltage seen on the pilot line while the pilot is oscillating. The maximum voltage is used to detect J1772 state transitions, but the minimum voltage should be (close to) -12 volts.

So, yes, you can just charge a car by making a 1 kHz square wave with variable duty cycle and turning a contactor on and off, but there's more to it than that. You don't have to go get your home-brew J1772 EVSE UL approved, but you need to at least be aware of what UL wants to see and why before you play with 7.2 kW or more of power.

Saturday, October 17, 2015

Making clocks - accuracy counts

Because of the widely publicized incident of the young Texan clock maker being arrested for bringing his creation to school, there has been a surge of interest in designing and making clocks. And that's awesome. Clocks are well known, and it's particularly easy to make them with microcontrollers (far easier than with discrete logic, but something can be said for the awesomeness of doing something the hard way). But clockmaking is deceptive. It's easy to make a clock that's functional, but if it's so inaccurate that you have to reset it frequently, then it's not very useful. And it turns out that achieving a useful level of accuracy is not trivial.

A clock fundamentally has two parts: a counter and an oscillator. The counter assumes that the oscillator operates accurately at a known frequency and displays the current cycle count, calibrated as a time. Some clocks use AC line frequency as their oscillator. Doing so outsources the problem, and is actually a good move (it should be mentioned that if you want to make a line-powered clock, you should buy yourself a UL approved low voltage AC transformer "wall wart" to do so. You shouldn't mess with AC line voltage directly, and for a clock there's certainly no need to do so), but more on that later.

There's very little to say about the counter portion of a clock. It's really all about the oscillator. Oscillators can be characterized by two factors - their accuracy and their stability. Put simply, accuracy is the difference between their actual frequency and their expected frequency and stability is the rate of change of accuracy over time.

There are lots of choices available for oscillators, but for amateur clockmakers, the only two worth seriously considering are AC line frequency or crystals.

Put simply, AC line frequency is very accurate, but highly unstable. You can count on a line frequency driven clock to be very accurate over a long term, but in the short term, there's no point in attempting to display seconds, because there can be multiple seconds of drift before it's corrected. But it is corrected eventually - the electric grids are typically disciplined so that in the course of a day the correct number of cycles take place.

If you want a battery powered clock, then you'll need to use a crystal. For the purpose of this discussion, crystals are quite stable, but their absolute accuracy is relatively poor. When I discovered this, it came as quite a shock. I thought that if I bought a crystal with a 10 ppm tolerance that that meant that I could count on the frequency being within 10 ppm. In fact, what that specification means is that if you buy a pile of that type of crystal, they will all be within 10 ppm of each other. And that's not the same thing at all.

A typical arrangement for a crystal clocked modern microcontroller is a crystal wired to two pins of the controller, with a loading cap on each lead to ground. The crystal will have a characteristic loading capacitance. The two capacitors, the PCB traces and the controller will all contribute capacitance. But what's the impact of that?

If you plot a crystal's frequency against the total loading capacitance, you get an inverse logarithm. That is, with no or low capacitance, the frequency will be too high. As you increase the loading capacitance, the frequency will drop precipitously at first, but then it will flatten out. Too much capacitance will eventually swamp the oscillator, but that happens much further on.

What the crystal manufacturers do is design and trim the crystals so that the desired frequency (within the tolerance, at least) is achieved with a particular capacitance value. And that value typically is far enough along the inverse log curve that it's somewhat flat, but not so far along that it can't still be pulled slower. The manufacturers choose this because they know that designers are going to want to engineer in the ability to fine tune the frequency, so there has to be room to pull the frequency lower, but at the same time, you want to reduce the sensitivity of the crystal by having the "sweet spot" be on a flatter portion of the curve.

So if you do the math correctly and pick the theoretically correct capacitor values - even if you take all of the parasitic capacitance into account - and then build your clock using a crystal with a 10 ppm tolerance, you still might find that it's 20 ppm slow. That's 12 seconds a week. The crappiest dime store digital watch can do far better than that. What happened? Well, if you were to build a dozen of them, what you'd find is that all of them would be within 10 ppm of each other, centered around some value. Given our single sample, we'd expect the center to be between 10 ppm and 30 ppm slow.

What happened is that the various component tolerances all contributed error. In the case of my crazy clock design, I tried crystals from three different manufacturers. With the same loading caps and same circuit, each wound up having a different batch center frequency with the three batches spread over a 20 ppm range! Altering the loading cap values gave even more points. I wound up going with a particular crystal and an loading cap value pairing that yielded a batch that averaged 5 ppm fast, ±10 ppm. That was the best I could do.

If you were building just one, then the best idea would be to substitute a variable capacitor for one of the loading caps. You could then trim the frequency manually. If you noticed the clock was running slow, you could just tweak it a little and it would come back into line. But if you're building a bunch of clocks, that's impractical. Much better would be to add the ability to "trim" the oscillator in software. That's what I did for the crazy clock.

It's not that hard to do. Out of every million oscillator cycles you need to either add or subtract "n" of them to effect an "n ppm" trimming. Or if you look at it another way, if you take one million and divide it by "n," then you need to add or remove a single cycle after counting that many.

The crazy clock works by arranging for one of the controller's timers to generate 10 Hz interrupts. It does this by performing a fractional division system. The software trimming simply counts how many cycles have been counted and increments or decrements the current cycle's count for one interrupt whenever the trimming counter overflows. What that allows me to do is write into EEPROM a trimming value. At startup, the math is done once and the trimming counter initialized appropriately.

That's as much as you need to do to just make a clock. Going further you can delve much more deeply into crystal stability factors, which will lead you to temperature stability, aging, and lots more.

Sunday, September 20, 2015

FE-5680A Breakout board users guide

This is the permanent home for the user's guide for the FE-5680A breakout board.

The FE-5680A is a Rubidium frequency standard widely available used on eBay. It has a DB-9M receptacle as its interface to the outside world and requires +15 VDC @ 1A and +5 VDC at ~100 mA to operate. This breakout board supplies both of those from a 20+ watt 16-24 VDC input - easily obtainable from a surplus laptop power adapter.

In addition to the 2.1mm barrel connector for input power, there is a two pin SIP header footprint on the bottom of the board which can be used as an alternative. There's also a 2 pin SIP header on the top of the board with the RF output, and a 4 pin SIP header that carries the PPS and RS-232 signals. Lastly, there is an LED in the corner of the board that indicates that the module has obtained a physics lock.

The 2 pin and 4 pin SIP headers bring the respective interface pins from the module directly out with no conditioning or other circuitry. The LOCK LED is buffered by a transistor so as to not unduly load the respective module pin (doing so can prevent the PPS signal from working). The pinouts of the various models of FE-5680A vary quite significantly, and the pin labels are nominal ones for the most frequent case.

Some 5680As do not require an external 5 volt power supply. If yours is one, then take an Xacto knife and cut the trace running between the two pads of the solder jumper immediately adjacent to the interface connector. Be careful to not cut any adjacent traces on the board. Keep the knife blade only between the jumper's pads.  If you need to re-enable the +5 supply you can solder the jumper closed again.

Note that both the 5680A and portions of the breakout board (particularly around the +5 LDO) will get quite hot during operation. This is normal. In particular, the module is internally heated to insure stability of its internal oscillator. Attempting to dissipate this heat will simply make more work for the oven.


Not all FE-5680As have the same pinout (the one indicated is the most common, so far as we are aware). Please carefully check your particular model against the pinout below to insure your unit is not damaged by improper connections. Before connecting your breakout board to your FE-5680A, please power it up and verify that the correct voltages appear on pins 1 (15V) and pin 4 (5V) relative to pins 2 and 5 (ground).

DB-9 pinout

  1. +15 V supply
  2. ground
  3. !LOCK (low means lock achieved)
  4. +5 V supply
  5. ground
  6. 1 PPS
  7. RF out
  8. RS-232 serial in
  9. RS-232 serial out


Sunday, July 26, 2015

GPS Disciplined Oscillator User Guide

This is the permanent home for the GPS Disciplined Oscillator User Guide. More information can also be found at the project page.

  • v1.0 - original prototype design
  • v1.1 - Change from an ATMega328p controller to an ATTiny4313
  • v1.2.1 - Add a buck converter to replace the LDO regulator
  • v1.4 - Numerous power bus cleanup and stabilization fixes, the return of the LDO, and change the buffer amp to an inverting compression amp to increase DAC granularity.
  • v1.5.3 - Redesigned to fit in new extruded aluminum enclosure
  • v1.6.2 - OH300 variant
  • v1.7.2 - Change to a 20 MHz oscillator, 5 volt logic system. Derive output from controller timer, use 2 DIP switches to select output frequency from four options.
  • v1.7 - OH300 variant for 1.7.x
  • v2.2 - Go back to a 10 MHz oscillator, but add a phase comparator system, a separate high precision LDO for the DAC reference, an extra LC filter on the 3.3v supply output, remove the output frequency selection infrastructure, switch to an ATTiny841 controller, remove the battery clip and add a mini-DIN 4 diagnostic connector on the back panel.
  • v2.2.1 - DOT050V variant for v2.2.
  • v2.4.1 - Add JFET to increase phase detector voltage linearity. Add pi network to one output for +13 dBm sine. Change ext ant jack to board-mount SMA.
  • v2.5.1 - DOT050V variant of 2.4.1.
The GPS Disciplined Oscillator board is an extremely accurate source of a 10 MHz signal. The signal is available either as a 5V square wave or a +13 dBm sine wave (both with 50Ω impedance). This can be used as a calibration source or an external reference for any number of different pieces of lab equipment, or can even be used as a master clock for microcontroller projects that require extreme clock precision.

At the heart of the board is a VCTCXO that has an inherent short-term stability of ±1 ppb or a VCOCXO that has a short-term stability of ±100 ppt. However, the fixed frequency variants of these oscillators only have an initial accuracy of ±1 ppm. For applications where both the accuracy and stability are important, using a "steerable" oscillator with feedback from an external reference is preferable. GPS offers an extremely accurate and cost effective synchronization source, however typically only a 1 PPS signal is available (though that 1 PPS signal is within ±10 ppb). This board uses a microcontroller to observe both the oscillator output and the PPS signal and tune the oscillator so that it emits as closely to an exact 10 MHz as can be measured. In addition, there is a phase discriminator circuit that will give additional phase correction information to the controller, approximately at nanosecond resolution.

The power supply should be 5 volts DC and capable of supplying at least 1W for the TCXO variant and 5W for the OCXO variant. There are three LEDs on the bottom right corner of the board. They are labeled FIX, 0 and 1. The FIX LED comes straight from the GPS receiver. At startup, or if the fix is lost, it will blink once per second. When a fix is (re)acquired, it will begin to blink once every 15 seconds. The 0 and 1 LEDs will blink back and forth when the GPS fix is lost. If they're not blinking, then they form a binary number 0-3, which correspond to the PLL operating mode. 0 (no LEDs on) corresponds to the coarse tuning mode, 1 (LED 0 on, 1 off) the fine tuning mode and 2 (LED 1 on, 0 off) the "run" mode. In general, with good GPS reception, the unit should arrive at the run mode within an hour. It's in this mode that you should expect to achieve the expected performance. If the GPS fix is lost, the unit will free-run until it returns, then re-enter the coarse, fine and then run modes.

There are two independent output ports. Each outputs a separate copy of the same signal. One output is a sine wave with approximately +13 dBm level, the other is a 5 volt, 50% duty cycle square wave. This output can be fed, if desired, into 50 ohm coax.

The GPS module has an internal patch antenna, but there is an external antenna connector on the board if you need to connect an external antenna. Depending on your board version, it is either a U.FL connector or an SMA edge-mount connector. The antenna will be fed 3.3 volts at up to 25 mA. In order for the external antenna to be recognized, it must present a DC load of at least 200 Ω. If you buy your unit in an enclosure, the internal patch antenna will not be useful because of the shielding provided by the enclosure, so an external antenna is required.

The operating temperature range of the board is 0-70°C. Rapid temperature swings should be avoided for best frequency stability.

If you need to upgrade the firmware, there is a 6 pin AVR ISP connector on the edge of the board. For board versions before v1.7, the programmer must be able to program at 3.3 volts with the target powered. DO NOT APPLY 5 VOLTS TO THE PROGRAMMING PORT OR PROGRAM WITH 5V LEVELS! You will likely irreparably damage either the oscillator or the GPS module (the two most expensive components). Programming the OCXO variant must take place with the board powered with its normal power supply, as most programmers will not be able to supply sufficient power for the oscillator to operate normally. For versions 1.7 and beyond, you should use 5 volt programming, but the recommended method is to always power the board with its own power supply and use a programmer configured for target power.

There is a mni-DIN 4 pin diagnostic connector on the board. It has a ground pin, two 3.3v async serial lines and a PPS output. One of the serial lines is the transmit data pin from the GPS module, the other is the transmit data pin from the controller. The controller transmit pin is tied to the GPS module receive pin (and vice-versa) as well as the diagnostic port. With normal firmware, the controller will not transmit anything. The GPS data will be at 9600 bps and can be tapped for other purposes, if desired. The PPS output is buffered. The rising edge will, in principle, be synchronized to the GPS second, but the output buffer will introduce a few ns of latency. It's recommended, therefore, that this be only used as a frequency standard, rather than a timing output (the latency should be fixed length given a fixed load).

When the "run" lock indication is present on the LEDs, you can expect the Allan deviation for the DOT050V variant for all tau to be 1e-9 or better. Typical performance levels are between 6E-11 and 9E-11 for tau 6E-1 through 3E+3, and then proceeding downwards from there. No representation or assertion is made about the phase of the output relative to GPS, only the frequency. You can expect the OH300 variant to be around 7E-12 for tau 1E0, rising to around 2E-11 at tau 3E+3 and then proceeding downwards from there.

After power is applied, it may take the GPS receiver up to a minute (assuming good GPS reception) to obtain a 3D fix (as indicated by the change from once-per-second blinking of the FIX LED to once every 15 seconds, plus the 0 and 1 LEDs changing from blinking back and forth to extinguishing). Once a GPS lock is indicated, it will take anywhere from 20 to 40 minutes for the coarse mode to bring the frequency within approximately 1E-9. The fine mode should take a few minutes more, and then the run mode should turn on and stay. If the GPS lock is lost, the unit will free-run until GPS is re-acquired, and then the startup process will repeat (but should be much faster, as the free-running frequency should be much closer to the target).

Note that the oscillator is sensitive to movement. If you move it while it's operating, you can expect phase disturbances that the PLL will have to correct. While each output is isolated, large changes in load can do the same. After changing output connections, or jostling the unit, you should give the oscillator a few minutes to settle.

The coarse mode implements a basic FLL that attempts to get close to center as quickly as possible. Once there, the FLL is maintained until the phase drifts close to the phase discriminator center point (for a maximum of 20 minutes). The coarse PLL mode operates with a time constant of 50 seconds, and the fine PLL mode with a time constant of 200 seconds.

Theory of operation

At the heart of the system is a voltage controlled, temperature compensated crystal oscillator or oven controlled crystal oscillator running at 10 MHz. The voltage control pin has a range of 0.3-3.0 volts and swings the output frequency either ±10 ppm (for the TCXO) or ±0.4 ppb (for the OCXO). This voltage must be kept as linear, stable, and noise-free as possible. The output of the DAC is fed into a resistor divider network. The resulting transfer equation is Vout = -n*(Vin-1.65) + 1.65, where n is roughly 0.5 for the TCXO and 0.8 for the OCXO. This results in a range of 0.825 volts (DAC value 0) to 2.476 volts (DAC value 0xffff), for a tuning range of roughly 12 ppm in 200 ppt steps for the TCXO, or a range of 0.2475 volts (DAC value 0) to 3.0525 volts (DAC value 0xffff), for a tuning range of roughly 800 ppb in 15 ppt steps for the OCXO. The DAC is a 16 bit serial DAC. Its default power-up state is to output a mid-range voltage. To insure that the DAC is not accessed while the controller is being programmed, there is a pull-up resistor on the !SYNC line (which is effectively a chip-select line). This is necessary because during programming the output from the controller will be floating.

The output of the oscillator goes into a 1:4 fan-out buffer (with a loading capacitor to bring the load on the oscillator to its rated requirement of 15 pF). One of the outputs of the buffer goes into the clock input line of the ATTiny841. Another goes into the input of a divide-by-10 chip, and then to the phase discriminator. The other two are presented as outputs, after going through an impedance resistor (to absorb reflected power from impedance mismatches). One of those two has a simple pi network low-pass filter to convert the output to sine.

The phase discriminator is a 4046 PLL chip. The VCO section is disabled by pulling the INH pin high. The signal pin is fed from the 1 MHz clock from the divide-by-ten. The reference pin is fed from the GPS PPS pin. As a result, the PD3 output is a positive-going pulse anywhere between 0 and 1 µs wide. This output is fed through a Schottky diode into an RC network with a time constant of 680 ns. The result is a voltage between 0 and approximately 4 volts roughly proportional to the width of the pulse. A 10 MΩ resistor across the cap yields a discharge time constant of 6.8 ms, which insures that the cap is discharged before the next PPS pulse arrives. The output of this arrangement is fed into an ADC input pin of the controller. The PPS interrupt will cause the ADC to be read, resulting in a value between 0 and 1023 that roughly corresponds to a phase shift of -512 to +512 ns. The arrangement is not tremendously precise, but it doesn't need to be - the important part is the rate at which the phase changes, not what the absolute phase actually is. The software will lock the phase to what amounts to a totally arbitrary - but constant - value.

The ATTiny841 is directly clocked from the oscillator. Its internal timers are therefore clocked at this frequency. The ATTiny841 has an input capture capability, where the present value of the 16 bit timer can be "captured" on a rising edge of its ICP pin. This also causes a capture interrupt. The ICP pin is fed from the GPS module's PPS pin. The firmware will effectively count how many cycles of the 10 MHz oscillator output occur between each PPS rising edge. A single count delta in one seconds represents ±100 ppb, which when averaged is used by the "coarse" tuning mode to get the frequency within 1 ppb or so, which means the phase shift will be slow enough for the PLL to be able to lock without having to unwrap the swings.

The serial port of the GPS module is also connected to the controller. The controller watches for NEMA $GPGSA sentences and looks for an indication of a proper 3D fix. If the GPS is not 3D locked, then it will be ignored and the system will hold-over until it comes back.

There are four separate power supply systems. First, 5 volts comes in from the external power input. There is a TVS diode to serve as a crude over-voltage and reverse polarity protection, and a tantalum cap to act as a noise filter. This is the primary source of 5 volt power for the other power supplies. For the digital section, a 47 µH inductor provides isolation from noise imposed by the digital circuitry. From the digital 5v bus, a dedicated LDO supplies 3.3 volt power for the GPS module.

From the 5v input bus, a 3.3 volt oscillator supply is derived using either an LDO for the TCXO variant or an SC189Z buck converter for the OCXO variant. The buck converter has an extra LC added onto the output to form a pi filter to further reduce noise and ripple.

Also from the 5v input bus, a separate high precision 3.3 volt regulator supplies the reference voltage for the DAC and also the supply voltage for the compression amp and the virtual ground voltage divider.


Thursday, July 23, 2015

A GPS disciplined oscillator

I've started a new project over on Hackaday... It's for a GPS disciplined OCXO. What it does is make a 20 MHz LVCMOS square wave that you can use as a reference for other projects or devices in your lab. Although I went with 20 MHz, a lot of lab test equipment works better on 10 MHz, so I plan on building at least a variant (if not the only version) that outputs 10 MHz.

Check out the work in progress over on!

Saturday, July 4, 2015

Accurately measuring low frequencies

When I discovered the Crazy Clock accuracy problem, one thing I needed to come to grips with in a hurry was exactly how to characterize the accuracy of the clocks.

The fundamental nature of all measurement is that it's relative. If your universe is confined to two points, you have no way to describe the distance between them. It requires a third before you can say that the distance between A and B is a certain fraction of the distance from B to C. Our definition of time is the best we can do - it's effectively defined as the frequency of the photons emitted by a particular atomic transition. Meaning that our "yardstick" for time is a basic property of the universe. But even so, we can only measure time by comparing the frequency of occurrences against each other, just as we use a yardstick to measure the length of a span by comparison.

So the first task when setting out to characterize the accuracy of a clock is to obtain a standard to which one can make comparisons. For that, the best bang for the buck available for the hobbyist is GPS. GPS receiver modules have PPS outputs whose rising edges are accurate to within 0.01 ppm (that is, ±10 ns). Moreover, they are constantly disciplined by the USAF to insure that whatever drift - however minuscule - they might show is eliminated. The downside is that the PPS output is the only accurate time signal available. The serial timecodes typically are not transmitted with any particular synchronization mark (and for the purposes of accurate time measurement they take a substantial amount of time to transmit), and even if that weren't the case, the typical serial I/O libraries don't do a good job of recording synchronization of incoming characters. And while the PPS signal is very accurate, the fact that it's only 1 Hz also raises some issues.

There are two ways to accurately measure the frequency of a square wave (we'll assume for the moment that the frequency being measured is stable, that we're only interested in the rising edge, so the duty cycle is not relevant, and that the combination of the rise time and our hysteresis of measurement places any jitter well inside our measurement tolerance). You can either accurately count the amount of time between adjacent rising edges, or you can count the number of rising edges that occur over an accurately measured time span.

If the GPS module output was, say, a hyper accurate 10 MHz signal, then we could conceivably count the number of rising edges of the 10 MHz clock between adjacent rising edges of the frequency being measured. If you're measuring a 32.768 kHz square wave, you'd expect to get 10,000,000 rising edges of the timing signal after measuring 32768 rising edges of the sampled signal. Any deviation from that 10 million would be a tenth of a ppm error in the frequency being measured, and you could take that measurement (and average it) every second.

Alas, the output of the GPS module is only one accurate pulse every second. Given that, it's much easier to count the other way - count the number of rising edges of the sampled signal between a certain number of rising edges of the timing signal. The two methods are, in fact, almost the same - you're using one signal as a stopwatch and counting occurrences of the other. Unfortunately, to be able to obtain an accuracy of 0.1 ppm, it takes a great deal longer when counting such a low frequency signal.

In fact, although the original crystal frequency is 32.768 kHz, we can't measure it directly for fear that the measuring apparatus would alter the circuit enough to skew the results. We must use the actual microcontroller in the circuit - running under exactly the same conditions we expect in normal operation - to output a proxy waveform. And the best option we have for that is to have it toggle a pin with every clock pulse. The result of that is a 16.384 kHz square wave. It takes 10:11 (611 seconds) to do enough counting to obtain a confidence level of 0.1 ppm.

But there's a problem there. On the actual clock board, the 32.768 kHz crystal not only supplies the timekeeping synchronization, but it also supplies the microcontroller's execution clock. That means that the program that's measuring the accuracy of the clock actually causes errors, because every instruction takes at least one cycle to process. The ATTiny45 processor can't separate the two, so we have no choice but to attempt to remove the error by using the timer prescaler to desensitize our measurements from the slop introduced by the code execution. In introducing a divide-by-8 prescaler, the measurement now takes more than 40 minutes. This also assumes that the code slop caused in our timing is within 8 instructions on the two paths - one that starts the timing and one that stops it. In practice, I compared the results on the same board between dividing by 8 and the next option of dividing by 64 (which took a bit more than 5 hours and 20 minutes), and the results were within my desired margin of error (0.5 ppm).

So that works, but 40 minutes isn't very efficient. It'd be much better to get back up to the 10 minute measurement theoretically possible. This, however, requires using a faster controller so that the code slop doesn't cause timing problems. A 16 MHz part would be able to run nearly 1000 single-cycle instructions between rising edges of a 16.384 kHz signal. So using a separate processor is clearly the way to go. And because we're using an external reference (the GPS PPS signal), the clock frequency of the controlling processor isn't at all critical. It merely needs to be fast enough to insure that an interrupt service routine has enough time to accurately count both sources without missing any.

The downside of using an external jig is that it won't be able to record the result directly in the target device (in actual fact, it's conceivable that the jig could perform an AVR ISP operation to write the result directly to EEPROM once it's done. A future jig might include this). So we need to output it in some way. A 2x16 LCD will do nicely. The completed jig will have an LCD display, a "start" button, a 2.1mm barrel connector for 6-12 volt power, the GPS module, along with an LED for the "FIX" line so you can see at a glance that the GPS is locked, a u.FL jack for an external GPS antenna, and a 3 pin test clock terminal with 1.8 volt power (to simulate a AA battery), the sampling pin and ground. You connect the clock up to it, press start, and 10 minutes later, the display will show the error in ppm and as a two byte correction factor ready to be programmed into EEPROM. Just to hedge my bets, I'm going to connect the serial lines of the GPS module up to the serial port of the ATMega. This way, if there's any programming that becomes necessary for the GPS module, I could upload a sketch to perform it.

Wednesday, June 24, 2015

Crazy Clock accuracy problems

I've discovered a design flaw in the Crazy Clock. The result of this flaw is that the clock fairly consistently gains time at a rate of ~120 ppm. That's around ten seconds fast per day. The clock is supposed to stay within 10 ppm - more than an order of magnitude better than that.

Fortunately, the error is consistent in the samples I've taken, and can be corrected in software.

If you've got an affected clock, there are two ways to fix it:

1. If you're very confident in your surface mount soldering skills, you can add a 12 pF capacitor between each lead of the crystal and ground. I do not recommend attempting this, as there's very little room on the board, and almost no margin for error. If you ruin your board attempting this, I won't replace it.

2. The new SW_TRIM facility can be used to trim the clock frequency to compensate for the error. To do this yourself, fetch the firmware from github, compile it with -DSW_TRIM and reflash the controller. After doing that, you'll also want to set the trim factor in EEPROM. It's located at address 4 and is a two byte, two's compliment, little endian integer representing the amount of adjustment in tenths-of-a-ppm. Positive values slow the clock. The standard correction factor for this error is 0x490, or 116.8 ppm slower. The avrdude argument to achieve this is "-U eeprom:w:0xff,0xff,0xff,0xff,0x90,0x04:m". If you do this, you'll wipe out the PRNG seed at locations 0-4, so if your clock has random behavior, you should replace each of the '0xff' in that command with four random numbers from 0-255. There's no harm in not doing this, really, but your random number generator will wind up starting from a "standard" state, resulting in repeated behavior the first time you power the clock up. Don't forget that the system clock speed is 32.768 kHz, so your programming SPI clock must be no faster than 4 kHz. Achieve this by adding either -i 125 or -B 250, depending on your programmer.

If you have an affected clock, you may ship it back to me and I will apply the fix and return the clock to you for free (including shipping to get the clock back to you). If you bought a complete movement, return just the movement - keep the hands and face and stuff. If you bought a controller only, then please return just the controller. In both cases, you'll get a replacement, not necessarily the same one you send. Please be sure to indicate which firmware style you wish. To proceed, contact me with the contact form and I'll send you the address to ship your movement or controller.

Friday, June 19, 2015

Sidereal clock movements

The Crazy Clock has been out there for a while, and one of the firmware options for it for almost as long has been the Sidereal clock. In looking around the Internet, I've found sort of a background rumble of interest in Sidereal movements for astronomers.

For those who aren't aware, the 86,400 second long "day" we know is more precisely a "tropical" day. It's the amount of time (roughly) it takes for the sun to go from the local meridian (the north-south line passing through the zenith - the highest point it reaches) on one day to return to the meridian on the next day. A sidereal day, on the other hand, is the amount of time it takes a star to go from the meridian on one day to the meridian the next day. The two are not the same amount of time, because at the same time that the earth is rotating on its axis, it is revolving around the sun. Over the course of a tropical year (the time it takes for the Earth to return to the same point in its orbit), the revolution adds an extra rotation. So a sidereal day is 1/365.2425(ish) shorter than a tropical day. That works out to 3 minutes, 56 seconds (that's not exact, but it gets us to inside of the 10ppm tolerance of the clock movement, which is enough).

If you combine a 24 hour clock movement with a sidereal controller, you wind up with a very special clock for astronomers. If you superimpose a star chart for your hemisphere, centered on the pole, the hour hand will always point to the star or constellation passing through the meridian (as long as you set the clock to local apparent sidereal time). It's this property that makes 24 hour sidereal movements valuable for building things like automatic astrolabes.

So for those looking, pre-built, ready-to-use 24 hour sidereal clock movements are available from my Tindie store. Just select the pre-built 24 hour movement with the sidereal firmware. They're in stock now!

Wednesday, June 10, 2015

AVRDUDE with linuxgpio and least privilege: don't sudo

The principle of "least privilege" is a valuable practice. Far too many people just put "sudo" in front of everything when they're using *nix - particularly on the Raspberry Pi, which is often thought of as a sort of throw-away computer.

Fortunately, the Raspberry Pi folks were thinking ahead a bit and created the "gpio" group and rules in devd to set the ownership of the GPIO nodes in /sys so that you don't have to be root to use them - you just have to belong to the correct group.

There is one "gotcha" to this, however. To understand it, we need to look at how GPIO functions on the Raspberry Pi.

In /sys, there is a GPIO class - that is, a directory - at /sys/class/gpio (that's not actually where it is, but there's a symlink there, so for our purposes, we'll just say it's there). Inside that directory, there are two nodes "export" and "unexport". To take control of a GPIO pin, you open "export" and write the pin number there. When you do, a new directory will show up named "/sys/class/gpio/gpioX/" where X is the GPIO number. Inside that directory will appear a bunch of nodes that will allow you to take control of the pin.

The gotcha, however, is that the kernel driver doesn't know anything about the "gpio" group. It sets the ownership of all GPIO nodes to "root:root" and "rw-r--r--" (0644). devd comes along at some time after the nodes are created and resets the permissions so that the nodes are writable by the gpio group. Normally this isn't a big deal because most of the nodes in /sys are created when the driver is probed, usually at boot. But in this case, avrdude attempts to export the GPIO pins, and then immediately set their direction. If it does so too quickly, it will get EACCESS attempting to open /sys/class/gpio/gpioX/direction.

People have so far worked around this by simply running avrdude as root - either by prefacing it with "sudo" every time or by making the binary suid as root. These are bad ideas. If for no other reason, if you ask avrdude to read from the chip and write to a new file, that file will be owned by root, rather than by the user running avrdude.

One quick and dirty solution to the problem is to introduce a short delay between the export operation and the rest of the initialization. But more to the point, the delay must also yield the CPU so that devd gets a chance to run. To that effect, my patch just uses "sleep(1)". It's probably too long a delay, but it works consistently.

Another way to go is to remove the export and unexport operations from avrdude and instead leave the pins permanently exported, exporting them from some sort of script possibly run at boot. This is safe to do, since the linuxgpio driver in avrdude is careful to set all the pins as input before exiting, which will return them to high impedance state. I haven't implemented this change, but it would allow avrdude to run faster since there would not be a 1 second delay every time.

To proceed, download AVRDUDE 6.1 and apply this patch. Then build as usual. Having done so, you can now either make avrdude sgid and set its group to gpio, or - probably better - add yourself to the gpio group. No more sudo!

Sunday, June 7, 2015

Crazy Clock contest!

Have you built a clock with the Geppetto Electronics Crazy Clock movement? Then here's your chance to win a free $25 gift code to OSHPark! Just tweet a picture or video of your creation to @nwsayer #CrazyClock any time before July 1st, 2015 (midnight, Pacific Daylight Time). To be eligible, the clock movement must contain a Crazy Clock controller, and you must live somewhere where it's not illegal for you to participate in the contest. Entries will be judged on creativity and humor, and the winner will be announced on July 4th, 2015. The gift code will be presented to the winner via Twitter DM.

Monday, June 1, 2015

AVR ISP Pi Cap user guide

This is the permanent home for the user guide for the AVR ISP Pi Cap.

This board provides level shifting and voltage protection (including hot-plugging) for AVR programming via the GPIO pins on a Raspberry Pi. It allows you to select the target power supplied to the target as either 3.3 volts, 5 volts or no power (meaning that the target is self-powered). The programming pins for the target will be level-shifted to whatever voltage is supplied to or by the target when programming is taking place, and will be high impedance otherwise. The buffer chip protects the Pi's GPIO pins from any invalid excursions. An AP2331 hot-plug protection chip protects the Pi from shorts and hot-plugging voltage sags.

The board comes with the stacking header (for the Pi) and the shrouded DIP header (for the target) uninstalled. It is strongly recommended that you install the stacking header first so that the shrouded DIP header doesn't get in the way of your soldering iron.

The GPIO pins selected are the MOSI/MISO/SCK pins for SPI port 0, however !RESET is connected to GPIO pin 25 rather than using one of the SPI CE pins. This allows !RESET to be asserted in a separate operation rather than being asserted and deasserted with every SPI operation performed during a single programming session. With this configuration, you have a choice of using the "linuxgpio" driver built-in to avrdude version 6.1, or the higher performance native SPI driver.

To use bit-banged GPIO, configure AVRDUDE for the "linuxgpio" programmer. Add this section to your avrdude.conf file:

    id = "pihat";
    desc = "Use the Linux sysfs interface to bitbang GPIO lines";
    type = "linuxgpio";
    reset = 25;
    miso = 9;
    mosi = 10;
    sck = 11;

Having done that, you should be able to use the -c pihat argument to avrdude to program a target. If it doesn't work, make sure you have an avrdude binary compiled to include the "linuxgpio" programming driver. AdaFruit has a guide that shows how to build avrdude 6.1 to include that driver. The LED will light when the !RESET gpio pin is brought low, and the bus buffer chip will bring the target !RESET pin low and assert the ISP signals on their relative pins.

Note that as of 6.1, there is an issue with the linuxgpio driver in avrdude. There is a race condition between avrdude writing to the GPIO "export" node to export the GPIO pins, and udev setting the permissions properly on the newly created nodes. The only workaround (at present) is to patch avrdude to add a delay between the export and the rest of the operations. Here's a patch.

If you are used to using -B to slow down the SPI clock, you can still do so, but the correct argument is -i instead (with the same numeric value).

To instead use the SPI driver, you'll need to apply a patch to avrdude to add the "linuxspi" driver (TBD).

Sunday, May 31, 2015

Crazy Clock: Reverse engineering the Quartex movement

The Crazy Clock is a pretty good product, but what it needs to take it to the next level is a manufacturing partner to actually make movements with the crazy clock built in in place of the boring controllers that are normally used.

So far, I have been taking Quartex Q-80 movements apart, cutting the traces on the board, and wiring the crazy clock into place. That works acceptably, but the retrofit operation is very fiddly. There has to be a better way.

So I sat down and attempted this evening to reverse engineer their enclosure and board.

The gear assembly with the original controller attached

The space in the chassis where the assembly sits

Here's what we have to work with. The metal contacts from the battery holder at the top (in this picture) of the chassis mate with the contact patches at the bottom of the board. The large "hump" at the bottom right mates with the large square cutout in the board. The hole at the bottom left mates with the pin that comes through the board at the top left. The other holes and slots in the board accommodate pins and protrusions from the gear case, and the single screw that holds the assembly together. In the upper right corner of the chassis and to the left of the board space at center, there are two small spacing pins that are meant to rest against the gear case assembly.

The board

The board can be removed from the gear train simply by removing the single screw at the bottom between the contact patches and desoldering the two coil pins. The board simply lifts off the gear case. Note that the screw holds the two halves of the gear case together. I made no attempt to open the gear case, as it's entirely likely that the gears would be difficult to reassemble if they fall out of place. Since there's no need to access the gears, there's only a downside to attempting to get in there.

Carefully measuring the location of the features of the original board led to this design (seen here as rendered by OSHPark):

Note that the space at the bottom left is dead space to accommodate the spacing pin that's in the upper right corner (as shown) of the chassis. Immediately to the right of the ISP header is the cut-out. One of the goals of the design is to make sure that the ISP header is available for programming even with the board assembled in the movement. That will make reprogramming it easy (or at least easier).

There are, at this point, still some important unknowns around the physical tolerances - particularly in terms of depth. The original board is thinner than the boards from OSHPark, and the original board had only the bonded and potted chip rather than a collection of traditional surface mount parts. I did, however, hold an original crazy clock board in place in the bottom of the chassis and it did appear to be flush with the spacing pins, which suggests that it will work. No way to know for sure until the prototypes come back in a week.

If this works, then it will make the process of retrofitting the Quartex movements much easier. The risk, however, is that if I order a ton of them and then Quartex redesigns their movements, I'll have a completely worthless inventory.

Thursday, May 21, 2015

Tiny Blinky user guide

If you were at MakerFair Bay Area 2015, you may have seen (or hopefully even purchased) a pair of little round blinking earrings from us.

I've finally gotten around to fulfilling the "open" part of "open hardware" - this page.

The circuit is simplicity itself: An Attiny84 with 8 LEDs, an SMD pushbutton and a CR1220 battery clip. The only other component is a 10k pull-up resistor on !RESET. The series resistors for the LEDs are present, but it turns out that 0 ohms is the best value to use.

Normally, it's always a good idea to add a 0.1 µF bypass cap close to the Vcc pin of any logic component. In this particular case, however, we can get away with omitting it because the ATTiny is the only load, and the battery is so physically close.

If you push the button briefly (<250 ms), it will change the pattern (remembering the selected one in EEPROM). If you push the button longer (>250 ms), it will power the blinky off. While it's powered off, the battery will last "indefinitely" (limited only by its own shelf life). While it's running, you can expect it to last for an evening or so (we had better luck at Maker Faire - they lasted the whole weekend, albeit powered off overnight).

There isn't a lot to say about how it works. The one thing of note is that the ISP programming pins should not be used for LEDs, since there are no series resistors. Programming could possibly wind up pushing too much current through them. MOSI and SCK are therefore connected only to the ISP header, and MISO is used only for the button (so don't push it while programming is in progress).


The firmware is available on GitHub

OpenEVSE II update

OpenEVSE II is for sale, and the design is more or less finalized at this point.

The most recent fiddling I've been doing has related to the pilot generator. While the old one was operating within the J1772 specification for the slew rate, it was barely doing so. One thing I learned the hard way was that resistors slow things down. But more so, in the original design, there was a tension between the primary transistor pair base bias resistors and the pull-up. In order to insure that both transistors are always in either one state or the other, the pull-up resistor has to overcome the bias path from +5 through the -12V primary transistor, to its base, through its base bias resistor, through the +12 primary transistor's base bias resistor, and then through the base-emitter junction to ground. In order to make that work, the pull-up had to be one tenth of what the base bias resistors were. The latest design was 10k base biasing and 1k pull-ups, but again, that was barely fast enough. The only improvement would have been to use 4.7k base biasing and 560 or 470 ohm pull-ups. But with that, you'd be sinking way more current through the microcontroller when it's pilot output was low. It just wasn't reasonable.

The solution was to change out at least the primary pair for MOSFETs. MOSFETs don't have a conduction path from their gate to drain, as there is in BJTs from their base to emitter. So the base bias can be 0 ohms and the pull-up can be 10k. The secondary pair can either remain a pre-biased BJT pair (47k emitter to base and 10k base to input), or can be also swapped out for a MOSFET pair, but with source-to-gate biasing of 2.4k and gate-to-input biasing of 2.4k (this is only necessary to reduce the gate voltage swings. Otherwise the -12 secondary gate will see a gate voltage of 17 volts, which is quite a bit). Either way, the slew rate is around 1 µs, which is half of the spec maximum of 2 µs.

If there is a next thing in the design to tackle, it would be to attempt to further increase the sensitivity of the GCM. Right now, it's on the order of around 50k or so, but the spec demands a trip point of 100 ohms per volt (so 12k for L1 and 24k for L2). Figuring out how to achieve that reliably is going to be a tough tuning task, but it still shouldn't result in any incompatible design changes at this point.

The next step will be to update the design of the Hydra to include all of the lessons learned. Stay tuned.

Tuesday, May 19, 2015

Important safety update for Toast-R-Reflow controllers

Everyone who has a Toast-R-Reflow model I or model II controller should obtain the latest firmware from GitHub and install it. The latest version for model I is 0.5, and for model II it's 1.2.

The change adds support for the AVR watchdog. The Toast-R-Reflow installed at The Hacker Dojo had some unknown event happen that wedged the controller with one of the elements switched on. This is obviously an undesirable outcome. It's unknown whether the watchdog would have been effective or not, but it certainly isn't effective if it isn't used.

If you are unsure how to update the firmware or have any questions, please feel free to contact me and I'll be happy to help. If you have no other way to apply this update, you can mail your controller back to me and I will apply it for you.

Sunday, May 17, 2015

Bay Area Maker Faire 2015

Well, Bay Area Maker Faire 2015 is just wrapping up. I'd like to say a special thank you to the folks at Steamy Tech for partnering with us to make the blinky earring/pendants that we were selling. I'd also like to thank all of the people who stopped by. An awesome time was had by all.

Special thanks to the folks at OSHPark for supplying us the boards and Small Batch Assembly for their sponsorship.

If you got our business card and have landed here, then you can see our products in our Tindie store. If you need help or support with a product that you purchased there, you can contact me using the contact form on the right side of this page or at Tindie.

If you bought a blinky earring/pendant, I am going to put up a page soon with the schematics and a github link with the firmware source code - that will make it Open Hardware.

Thanks again, and hope to see you all again next year!

Saturday, May 9, 2015

Lessons learned: The dangers of hidden licensing requirements

There was quite a kerfuffle this morning, and I won't say that it wasn't at least partly my fault for escalating it before the true nature of the request that was being made was made clear.

The nice folks (and there is no sarcasm there - they really are nice) at AdaFruit wrote me this morning to request that I license the use of their USB VID/PID for the USB µISP. Their request caught me quite off guard, as I was using the source code not from AdaFruit's site, but from the original developer, Dick Streefland. I could never recall any mention anywhere on either AdaFruit's site, or on Dick's that said that the USB VID/PID was anything other than free. In fact, the license for the source code is the GPL 2. It seemed to me at the time as if what was going on was that this was a hidden licensing trap, and that put me very much on the defensive.

Since then, things have become much more clear. AdaFruit has put a prominent notice on their site that while the source code for the USBTiny is open source, that does not convey a license to use their VID/PID without permission. And, at the present (and at the risk of speaking for them), it appears that their permission is relatively easy to get. And I do believe that those who have been allocated USB VIDs (and IEEE MAC address blocks, PCI vendor IDs and similar allocated identifiers) do and should have the right to govern how their identifier space is used.

For my own part, the lesson is that even code under an open source license can have licensing surprises in it. I think it's particularly incumbent on both rights holders to make their requirements clear to everyone so that there are no surprises, and on those who release open source software to insure that everything in their source code is covered by the rights their license grant implies.

Friday, April 17, 2015

EVSE Tester user guide

EVSE Tester on the Geppetto Electronics Tindie store

This page is the permanent home for the EVSE Tester users' guide.

The EVSE Tester allows you to exercise an electric vehicle charging station (EVSE) in various ways, and will display the state of the pilot signal, including the J1772 ampacity indication.

To assemble the quick kit, first install the three through-hole components on the board. Start with the 2x3 pin shrouded DIP header. It goes in the ISP socket. Be sure to mount it with the open side facing pin one, which has the square pad. Next, install the 2 pin screw terminal in the pilot block. Be sure to mount it with the openings for the wires facing outwards. Lastly, install the DIP switch block. It should be mounted with "ON" being down, though this is optional depending on how you want the switches to work.

Once all of the rest of the through-hole components are mounted, it's time to mate the display to the board. Start by laying the display face down on the workbench. Install the 16 pin SIP header, but do not solder it yet. Lay the logic board on top with the pins of the SIP header protruding from the back side to the component side of the board. Again, do not solder the SIP header yet. Next, lift the logic board slightly at each corner and place a spacer. Install a 2-56 nylon bolt into each corner hole so that it passes from the front side of the display, through the display, the spacer and the logic board. Secure each with a nut. Once the display is physically attached to the board completely, make sure the SIP header is positioned so that each pin is all the way in both boards you can solder each pin to both. Assembly is now complete. Apply power and adjust the contrast pot so that the LCD text shows up the best. The correct position will be close to, but not quite at one end of its turning range.

The EVSE Tester requires 6-12 VDC @ 200 mA supplied via a center-positive 2.1mm barrel connector. The power supply is required for the display only. Using the DIP switches to simulate the states of an electric vehicle alone does not require power.

The two pin screw terminal at the bottom center of the back connects to the ground and pilot terminal of a J1772 EVSE plug. The ground terminal is the large connector at the bottom. The pilot is immediately to the right of the ground, when looking into the plug.


Do not attempt to connect anything to the J1772 connector hot lines, which are the two large pins at the top (opposite end from the ground) of the plug. You must assume that 240 VAC power may appear on those pins at any time - possibly as a result of a malfunction. Contact with the hot lines while energized may result in serious injury or death.

Before attempting to connect the EVSE tester to a J1772 plug, switch the four DIP switches to their off position.

Connect the pilot and ground terminals to the EVSE using 22 gauge stranded wire. On the J1772 end, strip about a half inch and twist the strands tightly to avoid frayed endings. Bend the ground wire back on itself where the bare strands emerge from the insulation and insert into the ground pin. Insert the pilot line into its pin without bending. Some electrical tape can be used to secure the leads if necessary.

At this point, the EVSE should be in an idle state, with no indication that a vehicle is present. The tester display should show 0 Hz and a +, indicating that the pilot is pinned to a continuous +12 volts. If the display shows - instead, then it is possible that the EVSE is in an error state (with a -12 volt pilot signal) or is not connected properly.

Flip the "A" DIP switch on. The EVSE should indicate that a vehicle is present, but is not requesting charging. The display should change to show 1000 Hz (possibly +/- 20 Hz) along with a duty cycle and amp rating that corresponds with the expected value from the EVSE in question.

Flip the "B" DIP switch on. The EVSE should indicate that the vehicle is requesting charging, and will energize the hot lines. WARNING - As stated above, the J1772 plug is in a potentially hazardous state when the power is turned on, but the plug is not inserted into a vehicle. Do not attempt this function in inclement weather conditions or with anything inserted into the hot line pins at all. The display should not change.

Flip the "C" DIP switch on. The EVSE should react as appropriate for a ventilation request. What this means will depend on the EVSE. Most will indicate an error. Some will do nothing differently at all (particularly if they're intended to be mounted only outdoors).

Note that it is incorrect to ever have the "C" switch on if "A" and "B" are not also on. Similarly, it is incorrect to have "B" on if "A" is not also on. Always turn on the A-C switches in order and turn them off in reverse order. Doing otherwise won't damage anything, but will expose your EVSE to out-of-spec state transitions.

At any time (other than when all of the A-C switches are off), you may flip on the "D" switch to simulate a "missing" pilot diode. The pilot diode is a safety feature that allows the EVSE to distinguish between a vehicle and simply dropping the plug into a bucket of salt water. Flipping the "D" switch on should result in an immediate error condition on the EVSE. If it was supplying power, it will stop.


If the display is dim, adjust the contrast knob with a small screwdriver. The correct setting should be near, but just short of one end of its rotational range. If that doesn't fix it, check that the input DC voltage is between 6 and 12 volts. While the EVSE tester runs internally on 5 volts, the power supply is dropped to that level by an LDO on the input which requires 6 volts or more to function properly.

Theory of operation

The pilot terminal is connected to the A-C DIP switches and then to the three state resistors. The three state resistors are then connected to a diode and then to ground. The D switch connects across the diode, to short it out, removing it from the circuit.

The incoming pilot signal also is fed through a second diode with a 100K pull-down resistor into a LM393 comparator. The diode is necessary to protect the comparator from the negative excursions of the pilot signal. The incoming pilot signal is compared to a 1 volt reference from a voltage divider. The comparator output is fed into the controller.

The controller is an ATTiny84 clocked at 16 MHz (it is crystal controlled not because it needs to be fast, but for maximum measurement accuracy). It is connected up to 6 pins of the LCD display and the comparator. Three of the display pins are shared with the AVR ISP programming interface. There are 1K protection resistors in front of the display to insure it cannot interfere with programming.


Wednesday, April 15, 2015

See you at Bay Area Maker Faire

I'll have a table at the Bay Area Maker Faire May 15-17. I'll be giving live demos of hobbyist reflow with my own Toast-R-Reflow oven. I'll be making little 1" round earring/pendants with blinking LEDs in your choice of color (red, green, blue or white). If you wish, you'll be able to take those over to the SteamyTech booth and get a laser-cut enclosure for them. I'll also be making and selling Toast-R-Reflow controllers and power board kits and will have crazy clock and USB µISPs and Pi Powers on hand for sale as well.

I've got Square, so credit cards and cash will be accepted.

Wednesday, April 8, 2015

OpenEVSE II / Hydra developments

It looks like the pilot generator that I've been using for OpenEVSE II and the Hydra isn't always 100% reliable. My guess is that the biasing I am doing is too near the edge of the tolerances of the parts and some transistors work and some don't.

To fix this, I'm going to change out some of the parts. To follow along, look at sheet 2 of whatever schematic you like.

The pilot generator has two pairs of transistors, an output pair that switch +12 or -12 to the output, and an input pair that switch the output pair on and off depending on the state of the logic level output from the controller.

The resistors from the emitter to base of each of the output pair will change from 1k to 47k. The resistors from the base of the output pair to the collector of the input pair will remain at 10k. The resistors from the base of the input pair to the pull-up will change to 10k, and the pull-up will change to 1k.

This will result in a decrease in the collector current of the input pair coupled with an increase in the base current. The hoped-for result will be a more solid, assured entry into saturation for the input pair. My thinking is that the problems some folks are having are centered around incomplete turn-on of the input pair, which results in nothing on the output pair for either + or - 12, which winds up causing diode check errors or invalid states, or cars being upset with the pilot or what-not.

Additionally, I have a new design which will replace the four transistors and their bias resistors with two pre-biased complementary pair transistor modules. The whole thing will shrink down to 2 TSSOP-6 packages and a single pull-up resistor.

Also, another revision I've decided to make is to go back to the 20k (instead of 16k) resistor value for the low side of the voltage divider for the GFI comparator. But I'm also going to add a 10k bleed resistor in parallel with the peak-hold cap so that the self-test settles much faster after completion. I'm going to remove the peak-hold cap entirely. Since the GFI signal simply interrupts the controller anyway, there's really no reason to hold onto the peak value. The downside is additional interrupts, but those extra interrupts effectively do no harm, since all they'll do is turn the relays off again. I'm also removing the diode and pull-down from the output of the comparator. Since the LM358 is being fed with the 5 volt (and ground) supply, there's no need to protect the controller from negative excursions.

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.