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
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 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
#define CLOCK_NUM_LONG_CYCLES (2)

// 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

ISR(TIMER0_COMPA_vect) {
  // 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?
  power_adc_disable();
  power_usi_disable();
  power_timer1_disable();
  TCCR0A = _BV(WGM01); // mode 2 - CTC
  TCCR0B = _BV(CS01); // prescale = 8
  TIMSK = _BV(OCIE0A); // OCR0A interrupt only.
  
  set_sleep_mode(SLEEP_MODE_IDLE);

  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.
  sei();

  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.
    PORTB |= _BV(TICK_PIN);
    lastTick = TICK_PIN;
    PORTB &= ~ _BV(TICK_PIN);

    if (++cycle_pos == CLOCK_NUM_LONG_CYCLES)
      OCR0A = CLOCK_BASIC_CYCLE;
    if (cycle_pos >= CLOCK_CYCLES) {
      OCR0A = CLOCK_BASIC_CYCLE + 1;
      cycle_pos = 0;
    }
    sleep_mode();
  }

}

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/ .