Bad things happen when programmer finds a soldering iron

CAN Bus Decoding Using PicoScope

Illustration

When it comes to CAN bus protocol decoding, beating PicoScope is hard considering that even the cheapest 2000 series member has full support for it. Converting such scope to one with the floating ground is as easy as unplugging your laptop (or running your desktop of an UPS’ battery). However, there are a few issues you might want to avoid.

The very first step would be to properly trigger on the CAN bus message. Reasons for this are twofold. If there is any issue with your signal, this will allow you to catch it early so you can sort out basic electrical stuff before going on the higher level. Secondly, reliable triggering will help software decoder properly detect message start.

While exact trigger level might depend on the exact use case, in 95% of cases we are talking of 5V differential signal. Roughly speaking, your CAN L (low) signal will be either at 2.5 V or 0 V logical level and your CAN H (high) signal will be at either 2.5 V or 5 V level. Since signal between those two lines is mirrored, you only need to probe one of those two lines. I usually select L but that’s just because I already have cable made for it. All instructions are essentially the same whichever polarity you select. Good starting trigger level for low line is 2 V (3 V for high line). If your resting signal is further away from 2.5 V that would either point to termination issue or gross impedance mismatch and you should sort “electricals” first before continuing further.

Illustration

I like to set pre-trigger level to 5% as it allows me to use most of the screen for actual signal. To receive the maximum screen real estate you might be tempted to use 0% pre-triggering but I find seeing a bit of signal before my CAN message does help if you have a busy bus. Even better, this also allows you to ignore trigger edge setting completely (should be falling for low line).

Only once you can reliably catch your CAN signals, you can add serial decoder - Tools / Serial Decoding / Create / CAN. After selecting channel with your signal (named Data on this form), you will reap the benefits of getting triggers right. First and foremost, you should have bitrate set correctly as soon as channel is selected. More over, your threshold level should be automatically calculated from the signal. Yes, you can manually set it to 2 V but Murphy says you’ll forget it and then be confused as why decoding has errors or even misses a message completely. Lastly, you select High or Low setting appropriately depending on the line you are probing.

Congratulations! If all went good, you have just successfully decoded CAN bus message.

Ideal Multimeter

Illustration

If you are into electronics, probably the first test device you’ll own will be a multimeter. Not only you can get it for dirt cheap - my first multimeter was less than $10 in today’s money - but you can also do a lot in digital electronics with multimeter alone.

As I pawed my road to electronics with quite a few good and bad multimeters, I want to share my thoughts on what is important for a decent general purpose multimeter. I will stick to Agilent/Keysight U1232A and EEVBlog 121GW for most of my comparisons as these are two multimeters I use these days. However, principles are general and can be applied to any multimeter.

The very first thing I need of multimeter is to be safe. When I just started with electronics I didn’t care about that because I worked with low DC voltages only. However, sooner or later I would measure something on 240 V line. And not all multimeters would survive - some failing spectacularly. Having kids of curious age I like to have all my meters CAT rated and UL listed. And most of good meters will not die even if you do something utterly stupid like connecting to line voltage while in current range. Higher cost does offer higher survivability.

The next thing I find very important is speed. Having a high digit count is nice but it usually comes at the cost of speed. I find that 6000 count on my Agilent is much more comfortable for general measurement than 50000 counts EEVBlog has to offer. Yes, high digit count is important for certain scenarios and it’s not too bad to have one such meter available. But, if I had to choose one multimeter, I would go for a faster one. That said, don’t go under 6000 counts.

Illustration

In regards to speed, a special attention should be shown toward continuity check. Regardless of the display update speed, continuity tester must be fast and latched. Even the most minute contact between probes has to result in the (low volume, please) beep or flash. While most people prefer beep, I find backlight flash really great but that might be due to most of my work taking place during night when flash is easily visible and laud noises are not really desired. Speaking of flash, I love option to turn backlight with a single button. If you ask me, I would set all my multimeters to have backlight by default - battery life be damned - but I will be OK if I can turn light on easily.

I prefer when each measurement is a separate selection on a range switch as it makes switching between them a breeze. Multimeters with a lot of options tend to have just a few ranges but with Mode button switching between them. 121GW is specially nasty in this area as, not only it requires mode button but it also remembers the last mode selected. While this sounds like a good idea, it ensures that I need to check every time by looking onto display (that requires long press for backlight) before doing any work. This alone is probably the major reason why my Agilent sees much more use despite 121GW having more functionality and better specs.

Speaking about more functionality, I found 121GW’s mV range a real gem. If your multimeter gives you decent resolution it can pretty much substitute measuring current altogether. Just measure voltage drop over a resistor (or fuse) and you have all that’s needed to calculate current. Much easier than switching to current range and inserting multimeter into the circuit. Yes, this won’t work if you need precise and/or low-current measurement, but it works well to get ballpark figure and that’s often all that’s needed anyhow.

And order of measurements on the range switch is equally important. I prefer my order to be Low-Z voltage measurement, Off, DC voltage, AC voltage, other voltage related measurements, current, and finally the second off position. While this does prevent me from easily turning off multimeter by just moving switch into the far left position, it enables me to setup all on board and go into voltage measurement directly without traveling through Low-Z mode. While I love low-Z mode, I do not like when I have to go over it from off position (Agilent did this beautifully). Speaking of low-Z, idiotic restrictions like 12V minimum voltage for it to work 121GW has make it more nuisance than an useful range.

Illustration

If you are into temperature measurement, you will want support for standard K-type probes. Agilent here fails miserably as it requires special adapter to do it. My personal opinion is that, if any special adapter is required for measurement, that functionality might as well not exist.

Functionality I found awesome but it’s rarely implemented these days is a simple frequency counter. Yes, both U1232A and 121GW can measure frequency but range is laughably small (up to 100 kHz and 1 MHz respectively). When you deal with PWM circuits or you just want to check clock lines, a decent frequency measurement (like UT71C has - up to 40+ MHz) means you don’t need to pull out the scope most of the time.

Having the low burden voltage is an excellent thing in theory as it can mean a difference between being able to measure circuit’s current or not. In practice it depends on your use case. For me, working on 3.3V and 5V circuits, there is more than enough margin to handle any drop multimeter brings in.

Diode measurement should be a separate range so LED (or any other diode) polarity can be tested without much effort. If you are dealing with LEDs a lot, investing in multimeter that supports higher test voltage (like 15V on 121GW) does come in handy.

Other features worth mentioning include True RMS and auto-hold functionality. I found that not having either is not a breaking deal but they do come in useful once in a while.

Illustration

I do require support for either AA or AAA batteries in any multimeter I use. Not only 9V has generally inferior capacity but it’s also something I don’t ever have when I need it. There is simply no justification this day and age why standard batteries shouldn’t be used. And battery compartment should have a captive screw unless you want to spend 15 minutes searching for it every time you change the batteries.

Every decent multimeter will have a way of connecting to the computer for logging purposes. While bluetooth seems like a good idea, I found it lacking in practice as I would often find something would go wrong with it overnight. A nice physical cable is my preferred solution here.

In regards to the probes I find silicone is a must as stiff probe cables will be a hindrance. Tips have to be sharp and ideally their CAT III/IV insulation should be removable. Fully insulated probe is fine when dealing with high voltages or narrow spaces but often more exposed metal makes for easier measurement.

Unfortunately, finding the multimeter with all these features is hard if not impossible. Every multimeter - regarless of the price range - will have something missing. However, with two multimeters you can come darn close.

PS: Notice I haven’t spoke about precision at all as needs are highly dependent on the exact use case. For me 1% on DC is OK and this is something easily found in any decent multimeters.

PPS: One enjoyable thing you cannot really know until you see it also how multimeter fits in its carry case. Agilent is perfect here as you have range switch, all buttons, and probe holes reachable without ever getting it out.

Random on 8-bit PIC

When dealing with 8-bit microcontrollers one doesn’t always have all facilities taken for granted on a computer. One such example is a simple random number. While all computers can easily provide you with random number at will, unless you have a heavily specialized PIC, real random numbers are out of your reach. However, there is a way to get sufficiently close to make it work for most non-cryptographic purposes.

The answer is in linear-feedback shift registers. Assuming polynomials are carefully chosen, it is relatively easy to get non-repeating 255 byte sequences on 8-bit PIC. Yes, they are not random but for the most purposes they are random enough.

There are many types of LFSRs, Fibonacci’s being the most famous and probably the one implemented most often due to its simple hardware structure. However, for the PIC device, Galois has similar enough properties with a much simpler software structure.

General Galois function might looks like this:

#define GALOIS_POLYNOMIAL 0b11010100; //x^8+x^7+x^5+x^3+1
uint8_t randomState;

uint8_t getRandomByte() {
    unsigned bit = randomState & 0x01;
    randomState >>= 1;
    if (bit) { randomState ^= GALOIS_POLYNOMIAL; }
    return randomState;
}

This function essentially takes whatever data has in previous step and, using one of the maximum sequence length polynomials, calculates the next random byte. However, if you run it as such you might or might not get anything other than 0. Why? Well, pesky sequence has one blind spot - number 0. You can get any 255 byte sequence assuming it does not contain 0. If data becomes 0, it will stay 0.

Knowing this, one might be tempted to simply initialize data to some number and call it a day. Indeed, that would work for many applications that use 8-bit PIC. However, there are two things to have in mind: sequence will repeat every 255 bytes and random number sequence will be exactly the same on every startup.

To deal with the issue of repeating sequences, we need a counter that will simply reset the sequence after it “runs out of bytes”. As LFSR “circles” back to the original value after going thru all permutations (assuming polynomial is selected well), the easiest approach is to remember first value and reinitialize inner state once that value comes up again.

Second problem is a bit harder but not impossible. While the hardware random source would be nice, we can also do without it. My favorite approach is to have 8-bit timer running (e.g. TMR4) and then execute something that doesn’t have deterministic time - for example any user interaction (e.g. button press), writing to EEPROM (if PIC has one), or just waiting for PLL lock:

//setup unused timer that runs of the clock
T4CONbits.T4CKPS = 0; no prescale
T4CONbits.T4OUTPS = 0; //no postscale
T4CONbits.TMR4ON = 1; turn on timer 4 (or any other timer)

PLLEN = 1; //enable PLL
while (!OSCCONbits.OSTS); //wait for PLL lock

If function takes a slightly different amount of clock cycles every time, your timer will be in reasonably random state every time you check it and you can use it as a seed for generating random sequence - just don’t forget to ensure it is not zero.

Thus, our simple generator of random numbers could look something like this:

#define GALOIS_POLYNOMIAL 0b11010100; //x^8+x^7+x^5+x^3+1
uint8_t randomState = 0;
uint8_t randomStart = 0;

uint8_t getRandomByte() {
    if (randomState == randomStart) {
        randomState = (randomState ^ TMR4 ^ polynomial) | 0x80; //ensure non-zero at the cost of LSB
        randomStart = randomState;
    }

    unsigned bit = randomState & 0x01;
    randomState >>= 1;
    if (bit) { randomState ^= GALOIS_POLYNOMIAL; }
    return randomState;
}

If you run it for a while, you’ll notice something a bit disturbing. While start of the sequence is random, sequence is always the same. We need a way to make the sequence a bit more random. The cheap way to change this is to simply loop through all maximum length polynomial terms and thus extending our sequence from 255 to 4080 bytes.

Or, to break a pattern, you can even make switches in middle of sequence to make it a bit less obvious:

const uint8_t POLYNOMIALS[] = { 0x8E, 0x95, 0x96, 0xA6, 0xAF, 0xB1, 0xB2, 0xB4,
                                0xB8, 0xC3, 0xC6, 0xD4, 0xE1, 0xE7, 0xF3, 0xFA };
const uint8_t POLYNOMIALS_COUNT = 16;
uint8_t polynomial = 0xB8;

uint8_t randomState = 0;
uint8_t randomIndex = 0;

uint8_t getRandomByte() {
    if (randomIndex == 0) {
        randomIndex = (TMR4 >> 6) + 1; //generate number 1 to 4
        randomState = (randomState ^ TMR4 ^ polynomial) | 0x80; //ensure non-zero at the cost of LSB
        polynomial = POLYNOMIALS[TMR4 & 0x0F]; //select next polynomial
    }
    randomIndex--;

    unsigned bit = randomState & 0x01;
    randomState >>= 1;
    if (bit) { randomState ^= polynomial; }
    return randomState;
}

Realistically, there is only so much you can do without any random entropy while keeping function reasonably fast and I think this final function gives a reasonable result.


PS: Again, do not use this for anything security related - for that you need real random numbers, not pseudo-random sequences.

PPS: Jason Sachs has a nice article going a bit deeper in details about LFSRs.

PPPS: If you really want to expand random sequence, think about using 16-bit state and polynomial. Albeit the price of 16-bit computations on a 8-bit microprocessor is non-negligible (albeit not devastating), your use case might warrant such step.

EEPROM Access Routines For PIC18

While I was playing with CAN bus, I needed to write something to EEPROM memory - to keep it safe between reboots. Imagine my surprise when calls to eeprom_read and eeprom_write returned errors:

warning: unsupported: The Read_b_eep routine is no longer supported. Please use the MPLAB X MCC.
warning: unsupported: The Busy_eep routine is no longer supported. Please use the MPLAB X MCC.
warning: unsupported: The Write_b_eep routine is no longer supported. Please use the MPLAB X MCC.

It seems PIC18 series doesn’t support old EEPROM routines that worked on PIC16 but, at the same time, my PIC is old enough not to be properly supported in the suggested MCC. I guess it was time to write PIC18 version of these functions myself.

Reading over documentation for PIC18F25K80, I was pleasantly surprised that EEPROM writing hasn’t really changed. My assembly code I wrote back in PIC16F84 days was quite close to what’s needed these days too. The only significant change was expanding EEADR to allow for more than 256 bytes. Yes, there are some shenanigans with setting EEPGD/CFGS bits but that’s done only once.

My replacement for eeprom_read function was similarly named eeprom18_read and it’s really a drop-in replacement. Not to be the one to dwell in past, I opted to change my ASM code to XC8 flavored C. It’s essentially just setting up EEPROM address, followed by read request, a short pause to get the data, and then reading the data itself.

unsigned char eeprom18_read(unsigned int offset) {
  EECON1bits.EEPGD = 0; // accesses data EEPROM memory
  EECON1bits.CFGS = 0;  // accesses data EEPROM memory

  EEADRH = offset >> 8;
  EEADR = offset;

  EECON1bits.RD = 1; // initiates an EEPROM read
  Nop();             // it can be read after one NOP instruction

  return EEDATA; }

Writing was a bit more involved but not too much so. After setting EEPROM address and data, it was important to allow EEPROM write and disable interrupts as ancient EEPROM unlock sequence (0x55 0xAA) must not be interrupted. After write is initiated, code will wait for it to complete and then restore interrupts. For safety it will also disable further writes to EEPROM until it’s needed again.

void eeprom18_write(unsigned int offset, unsigned char value) {
  EECON1bits.EEPGD = 0;  // accesses data EEPROM memory
  EECON1bits.CFGS = 0;   // accesses data EEPROM memory

  EEADRH = offset >> 8;
  EEADR = offset;

  EEDATA = value;

  unsigned char oldGIE = GIE;  // interrupts be disabled during this code segment
  GIE = 0;

  EECON1bits.WREN = 1;  // allows write cycles

  EECON2 = 0x55;  // write sequence unlock
  EECON2 = 0xAA;  // write sequence unlock

  EECON1bits.WR = 1;     // initiates a data EEPROM erase/write cycle
  while(EECON1bits.WR);  // waits for write cycle to complete

  EECON1bits.WREN = 0;  // disable write
  GIE = oldGIE;         // restore interrupts
}

PCBWay

Illustration

Creating hardware projects usually involves a lot of time spent creating PCB design and then even more deciding which prototype service to use. When PCBWay approached me to consider their service, all I could say is heck yeah. :)

The first thing you’ll experience ordering boards from them is a page full of options. While you can select a few simplified “deals” from main page, they will all bring you to this page for customization. And you can customize a bunch. It’s like a prototype service on steroids.

You can select number of layers (up to 14), material (including flex construction), board thickness (0.4 to 2.4 mm), copper thickness (1 to 4 oz), and surface finish (including hard gold - great for edge connectors). Yes, not all combinations are supported at the same time - for example you cannot have 14-layer aluminum board) - but there is enough choices to make you happy and/or crazy.

You can also select track/spacing (up to 4/4 mil) and hole size specification (0.2 mm) with or without plugged vias (great for BGA work). If you click on special option you can further select castellations, edge plating, impedance control, blind vias, the list goes on and on. If you need it, chances are you can order it. A more “standard” customization of solder mask and silkscreen color almost goes unnoticed.

All these options do come at price. Not only the cost of board can go into hundreds of dollars but it also makes the whole process way more complicated than what you’ll need 99% of time. Clicking on various options can get you so sidelined that you’ll forget about the most basic stuff.

For example, I managed to order all my boards without ENIG finish (immersion gold) just because I somehow missed that option. I would kill for a few simple templates with the most logical options preselected (e.g. ENIG for surface-mount soldering) and with only limited customization allowed (e.g. solder mask and silkscreen color). Yes, there are “specials” available but they still end at the same overly-complicated page.

Upload process is rather pain-less and even supports my favorite RAR format. I used the exactly same files I usually use with OSH Park and PCB:NG service without any issue. Unfortunately, there is no gerber preview here so you might be up for a surprise if something goes wrong.

As one has to define size for board during upload, I intentionally selected a smaller size for one of them. Person doing verification caught it and corrected both board size and the price. This gives me hope that any gerber errors might be caught too but note that such manual review will probably happen a few hours after the upload. This means delay for any issue not easily correctable. I would consider first uploading gerbers to OSH Park and using their awesome preview to perform a sanity check.

Combined with overly extensive customizations, lack of preview makes service much harder for hobbyist (such as myself) to use and I believe even professionals don’t care/need about most of these options on a regular basis. Even when such extensive customization is needed, I doubt one would prefer to go from scratch each and every time.

It takes a few (five in my case) days for boards to get produced but then comes the longest part - shipping. As PCBWay is in China, this means that any cheap shipping will take a while. The cheapest option actually took 2 weeks to arrive, making it slightly slower than US-based competitors. Of course, this assumes you are in States. For international customers timeline might not differ as much. Moreover, there is option for courier shipping but at a significant premium.

Once boards arrived, I found a few things in common to all - most noticeably v-groove routing for external edge. It makes board much cleaner and without any sharp edges to deal with. Boards themselves come either vacuum packed or in a baggie for the small sizes. While vacuum packing might be a bit annoying to open, it does protect the boards quite well in transport.

I immediately hated the addition of order number to the silk screen. While it seems engineer took care to place it underneath big components where it wouldn’t be visible, it’s kinda lottery if you need a really clean look (e.g. customer facing panel). If you note where their number can and cannot go on the silk screen in the comment field, I am reasonably sure they will cautious. However, such instructions are an extra step you need to remember and there is still some risk the number will be written right where you don’t want it.

Testing consisted, as usually, of hand-soldering the boards using Hakko D-888 soldering iron. As I use lead-free solder, the temperature was set to (rather low) 350 °C most of the time. All fine-pitch soldering was done by flooding all pins with solder and then wicking the extra away.

Illustration

First board I got to solder was TmpUsb. It’s a small board with all SMD components and white solder mask did look awesome initially. As I went soldering, I noticed a residue forming whenever I touched the solder mask. Not only this sticky residue was ugly to see but it also stuck to the tip. As this was actually my first board with white solder mask, I am not sure if this is something common for that color or PCBWay uses a formula that’s not particularly heat resistant. In any case, not ideal for soldering iron work.

Second board was for Binarko. Not only this board has a fine-pitch component (0.2 mm TQFP-48) alongside quite a few 0603 passives but it’s intended to be press-fit mounted into the case. The good news is that fit is as close to perfect as it gets. Use of v-groove also means there are no breakout tabs to get rid of resulting in much cleaner look. Since I forgot the HASL coating, getting microcontroller aligned was a bit of challenge. Interestingly, the black solder mask handled high temperature much better than it’s white counterpart making much less mess.

Fine-pitched PIC meant I had to use solder wick a lot and that has shown another issue - it’s really easy to lift a trace. When it happened the first time I played around a bit and noted this seems to be related to the temperature. While I didn’t seem to have issues dragging 300 °C tip, at 350 °C dragging soldering tip was much more destructive.

The final board was of UsbAmps. With 0.25 mm pitch TQFP-44 package, it was a bit easier to solder. It’s green solder mask did its work well and I haven’t noticed any heat-related residue. However, sensitivity of traces to heat/dragging remained.

To conclude: If you are still using lead solder or you do reflow soldering, there are no major downfalls considering this service. While it might not be as cheap as OSH Park or PCB:NG for smaller boards (especially considering shipping is not free), it does get better with larger sizes. If board color or a bit more involved customization is necessary (think filled or buried vias), suddenly this service makes real sense. Yes, you are paying a bit (sometime quite a bit) extra but you do get something not commonly found in prototype market.

Default selection of lead HASL finish and paying extra for lead-free or ENIG is a bit of nuisance for me as I prefer poisoning my self with more fancy stuff but it’s probably not a problem for many considering the love hobbyist market still shows toward the good old 60/40.

There is quite restrictive service offered by OSH Park and PCB:NG where selection of anything other than 2 or 4 layer process is simply not possible but you get your board quickly and at a reasonable price. On the other hand there is almost infinite possibility of customization PCBWay embraces but not without the cost.

Now, only if they would stop adding their numbers to boards…

PS: I was given boards for free by PCBWay. I don’t believe that affected my review, but I believe it’s fair to disclose. :)

[2018-08-16: It seems that PCBWay decided to add extra $3 charge if you use PayPal and you will only see it on the last page. Not nice… :(]

[2019-11-24: At this time PCBWay asks you to pay extra $3 if you want your boards without their custom number. Essentially you are paying for them not to deface your board. Nickel and diming…]

Average Number of Lighted Segments on 7-Segment Display

For a project I am doing with kids we decided to use 3-digit 7-segment display. As we intended to video the project (eventually), it was easy to make decision that we’re gonna drive every digit fully - no multiplexing. Not only that simplifies programming logic but it also makes display rock steady during video - no flickering here.

However, with so many pins to drive, I got a bit scared about maximum power consumption MCU would need to deal with. Assuming we go with 10 mA per LED, what is actually the maximum current we’ll need?

The easy answer is 7x10 = 70 mA per digit, bringing it to 210 mA total. Assuming all digits are fully on (we haven’t used decimal point - otherwise it would be 8) we would indeed need that much current. However, realistically, are we always going to have number 8 on display?

For this purpose, we’ve gone and created a table - how many segments we actually use for each digit:

DigitSegmentsCurrent
0660 mA
1220 mA
2550 mA
3550 mA
4440 mA
5550 mA
6660 mA
7330 mA
8770 mA
9660 mA
Median550 mA

As you can see, the most common result ended up 5 segments being lighted. This tells we actually can usually count on 150 mA of precious current needed.

But wait, since our project will count from 0 to 255, we actually won’t have all our digits on all of the time. We need to calculate how many segments we actually have lighted for numbers that we need. An eternity in Excel later we’ve found that median current needed (assuming random distribution) was 120 mA. Maximum was 180 mA (darn 208!) and minimum was 20 mA.

While 180 mA is not trivial, it is definitely less than 210 mA we originally had to count.

100 MA Is a Myth

A lot of electronics ends up being connected to USB - whether they need computer or not. USB and its 5 V has became an unofficial standard power supply for the world. And thus it makes me crazy when I hear from people that you can only draw 100 mA from USB without going through USB enumeration else something horrible is going to happen. And that is bullshit.

Yes, there is such a thing as USB negotiation where each device can request certain amount of current from its host. Older USB devices could ask for up to 500 mA (in units of 100 mA) while USB 3.0 devices have maximum of 750 mA (in units of 150 mA). If you go higher than that, you get into the category of USB Power Delivery 3.0 and the beauty of multiple voltages we’ll conveniently ignore here, and deal only with 5 V requirements.

A misconception when it comes to USB negotiation is due to ability of USB devices to self-report their maximum usage and likewise the ability of chipset to say no if multiple devices go over some internal limit. Ideally, if you have four USB ports on the same power bus with total of 1 A available and you connect four devices using 300 mA each, three would get positive response and fourth one would get their request denied.

What might not be completely clear from this story is that bus has no means to either measure current or to enforce device’s removal. This whole story depends on the device accurately reporting its (maximum) usage and actually turning itself off if it receives “power denied” response. And yes, this self-reporting works as well as you can imagine it. As there is no way for computer to ensure either accuracy of data or device’s compliance everybody simply ignores it.

Computer manufacturers decided to save some money and not verify device’s consumption. So what if device that reported 300 mA is using 350 mA? Should you disconnect the device just because it uses lousy cable with a big loss? Why would you even care if that is the only device connected? What to do if that device just goes to 500 mA for a fraction of second? What to do with devices reporting nothing (e.g. coffee heaters)? Is nitpicking really worth bad user experience (my damn device is not working!) and is it worth extra cost to implement (and test)?

While there were some attempts at playing “power cops” in the early days; with time all manufacturers decided to over-dimension their power bus to handle more power than specification requires and simply placed cheap poly-fuse on it to shut it down in the case of great overload.

Such friendly behavior has culminated with each port of any laptop made in the last five years being capable of 1 A minimum. And you can test it - just connect data lines (or use UsbAmps’ high-power option) - and you will see you can easily pull 1 A out of something officially specified for half of that. And that is without any power negotiation - courtesy of the USB Battery Charging specification.

This leniency from manufacturers in turn generated a whole category of completely passive devices. Why the heck would USB light have a chip more expensive then all other components together just to let computer know its power usage? That is just wasting money if you can get power out of it whether you inform it or not.

Devices that have to communicate with computer over USB kept their self-reporting habits just because they had to use a bit smarter chips to interface the USB. And all those chips had to have power negotiation built-in to be certified. There was literally no cost in using this feature.

And even then they would fudge the truth. Quite often an external CD drive or hard disk would actually need more than 500 mA to spin up. And there was no possibility in the early days to specify more than 500 mA. So they lied.

Such (lying) behavior was essentially later approved with the USB battery specification that uses not an USB message but voltage levels as a limiting factor. It essentially says that you can pull as much as you want while voltage levels are high enough. Once voltage starts dropping, ease off a bit. This point can happen at 1 A, or 1.5 A, or 2 A - it all depends on power source/computer you are using.

Device manufacturers have become quite verse too. Since USB battery charging specification was done is hardware friendly manner, there was no extra cost to bear. Only task was to determine if computer supports the, then new, specification. If yes, pull current until voltage start dropping. If not, limit yourself to 500 mA. How do they recognize it? You’ve guessed it - by shorting the data lines.

Due to the powers of backward compatibility you can pull essentially as much current as you want from your PC. Yes, you are still limited by fuse (quite commonly 2 A or more per port pair), you still have thin USB cables and their voltage drop (with accompanying losses) to deal with, and yes devices - especially phones - will still self-limit to avoid tripping aforementioned fuse. But otherwise it is a wild west.

Unless you are making device that has to be certified, stop worrying about the power negotiation. If your device already has an USB transceiver onboard and you need to program it anyhow, go for the standard and configure current you need. But if you don’t have such chip or programming is just too much of a hassle, simply ignore it and world is not going to self-destruct. I promise.

RetroHat

Illustration

Raspberry Pi is often used for retro-arcade machines. It really fits well there: low power usage, reasonable emulation software support (it is based on Linux after all), more then capable processor, and really cheap price ($35). It is hard to beat this.

What surprised me is that I couldn’t find proper Raspberry Pi HAT that could be used to treat buttons as a keyboard. Yes, there are guides how to setup buttons, but they don’t do auto-detection and require a bit too much setup for my taste.

There are also USB devices to which you can connect buttons but I find them a bit annoying to deal with in physical sense. While they do offer huge amounts of buttons, them sticking out of Raspberry’s side is always ugly to see.

What I wanted to build was maximum amount of buttons I can get away with using only natural HAT connections and without the need for any driver not available out-of-box. Of course, it should be a proper HAT with EEPROM, auto-configuring everything needed as soon as machine is booted.

First of all, with number of available pins on HAT connector it became clear there is a hard maximum at 24 buttons. Assuming 2 players, that comes to a joystick and 8 buttons (A, B, X, Y, L, R, Start, and Select) per player.

As HAT gives you quite respectable surface to work with, connectors for these buttons could also include a LED support at the cost of few resistors. Moreover, a discrete (fused) connector for both 5 V and 3.3 V rail was added. While neither is intended for heavy use, it comes in handy for powering various extra components in your retro-cabinet.

For keyboard emulation, this HAT uses a built-in support for GPIO keys. As long as you connect momentary button between GND (-) and pull-up input (S) it will detect each press as the transition from high to low and simulate the appropriate button. Default keyboard configuration is selected in such manner that player 1 configuration matches default RetroPie settings while all keys for player 2 are assigned numbers 0 to 9.

Of course, you can configure all this just by modifying retrohat.dts, a file whose creation took probably more time than board design, soldering, and everything else. But it was worth it to get auto-configuration running once EEPROM is programmed. To get more information on how to program the auto-configuration EEPROM, you can either go over read-me file or check how I did it for Cananka.

In any case, check project’s page for a short description and to find link to source files so you can build your own.

OshPark Vs PCB:NG

For feeding my electronics addition I mostly use OshPark. They have quick turnaround, excellent user service, and price is quite acceptable.

However, they are not the only game in town. Probably the best alternative if you are willing to wait a bit is unsurprisingly in China. Yes, I am speaking about Seeed Studio’s Fusion PCB. It is not exactly comparable to OshPark but it is close enough for many purposes. And it is excellent choice if you need different PCB colors - something OshPark doesn’t offer.

But times are changing and there is a new challenger on US soil - PCB:NG. They are PCB assembly house - something that is a bit too pricey in low quantities and something I personally never needed. But they do offer a possibility to order only PCBs.

PCB specifications are quite high-end: ENIG finish (I love this), 4/4 mil traces (vs 6/6 for OshPark), 8 mil vias (vs 13 mil), and they generally support cutouts and slots (although no promises here). As I generally don’t go lower than 8/8, I find them working equally well for my use case.

Price is $6 per inch for 6 boards, compared to $5 per inch for 3 boards OshPark offers - quite similar if you only need a few but PCB:NG wins at higher quantities.

Order process is simple enough and I had no issues with DipTrace 3.0 produced gerbers - something that might fail occasionally with OshPark (e.g. my PCB bear). I would say parser is definitely more forgiving with PCB:NG. I kept all file names setup as for OshPark and there were no issues. Your mileage might vary but I don’t expect anything unsurmountable as you can correct auto-detection yourself. And no, neither PCB:NG nor OshPark support RAR.

First thing you’ll notice when you get a board is attention to packing. There is a nice layering of red paper between each board and there is virtually no chance of them scraping one another. While I am not sure that matters as I never had any issues with loose boards arriving from OshPark, this does look a bit nicer.

What you will see after unpacking is a dark red colored board. I have ordered two within a few weeks and shade is a bit different. It is similar experience to year’s back when OshPark was testing other factories - I am sure shade will become constant very soon if it is not already. Just be mindful if you need exactly the same shade to order all boards at the same time.

All boards come fully broken out - unlike with OshPark where you can still see breakout tab pieces. Tabs themselves seem nicely defined and PCB:NG puts less of them than OshPark. Generally I have less work filing the rough edges then with OshPark. Somebody less nitpicky would be able to use them without filing altogether.

Silkscreen is not bad but white on red makes it less visible than white on dark purple OshPark uses. If you need good silkscreen visibility (e.g. user visible panels) you should probably go with OshPark.

I am not sure whether it was a fluke or standard practice but PCB:NG placed their custom markings on my silkscreen. This is something done by Seeed Studio and most low-cost services as it makes their process a bit easier. OshPark doesn’t do it and I was surprised when I saw PCB:NG doing it. However, on my second board I had no custom markings so they seem to have abandoned this vandalism.

When it comes to copper quality I can really say nothing bad about either PCB:NG or OshPark. Both have nice ENIG finish, neither had issue with traces or solder masks, both can handle hand lead-free soldering without much trouble. If there wasn’t a color difference, I wouldn’t be able to tell them apart.

For me it comes to two things. If board is meant for user visible panel (e.g. end panel for plastic enclosures) I find purple, almost black, OshPark gives fantastic look to a final device.

Where PCB:NG wins is price. As soon as you go over 3 boards OshPark offers, you are better off using PCB:NG. And, if you want some assembly, there is no content at all. PCB:NG is the one that offers low volume assembly.

As I usually do extremely low volume orders (often making just one or two devices) I will probably stick with OshPark. There is something to be said about familiarity. However, PCB:NG is a high-quality contender and worth trying out (remember 4/4 mil traces) - even at a fraction higher cost for a small volume.

Cananka, the Raspberry Pi HAT: Problems

Illustration

[This the last post in the series.]

Mistakes? I’ve made a few…

The very first one was noticed after I’ve already sent order to OSH Park. For back-powering isolation where 2 A are needed, I used the same footprint as for 100 mA DC-to-DC voltage regulator. There is no chance of getting a part that would support 2 A in such a small package. I’ve replaced it with properly sized 1x1" isolated voltage regulator and contacted OSH Park support. As my original order was not sent to fabrication facility yet, I got it swapped with a new design without any additional cost. OSH Park support rocks!

While waiting for a board, I continued going over the design and thus I’ve noticed I’ve forgotten to pull-up the reset line. Uncaught it would cause chip not to function so respin was definitely needed. Additionally I’ve changed layout of board a a bit alongside making a slightly bigger cuts to allow for official case to carry the board. I find it amusing that HATs made in accordance with official specification don’t fit the official case. :)

What I didn’t catch was that my new DC-to-DC brick needs a bit bigger holes. It was possible to get DC-to-DC converter in the board but with a lot of elbow grease. Definitely not what you would want. I also didn’t notice I had damn pinout backward on one side of the chip. And guess what, since I’ve already sent for revision B to be manufactured, I couldn’t change it before revision C.

I did try to mod-wire the revision A of the board but important traces to cut were under the DC-to-DC brick itself so there was no approaching them - not with tight drill holes I had. Fortunately I was able to jump the missing reset line and thus have a proof of concept all is working well.

Revision B arrived when I was already preparing for next revision due to already mentioned faults and thus I have just populated the “cheap” part of the board. It made no sense to mount $25 DC-to-DC voltage regulator if I know it is not going to work. Revision C did have few other changes to silk-screen and other minor changes. Most notable change, outside of DC-to-DC pinout correction, was changing EEPROM to be write protected when WP jumper was soldered over.

Original suggested EEPROM circuit makes write-protection to be default. This means you need to connect the jumper to write chip and then desolder it later to make it read-only. I find it much easier on me if all chips start with being writable and then you make solder bridge to make them read-only. Additionally, as chip has internal pull-up, this means you save a resistor. :)

As revision C came, all seemed great until I tried power-back circuit - it didn’t work. Short troubleshooting later I’ve noticed my reading of remote on/off functionality was lacking a bit and thus I was missing connection of that pin to ground. With that single change power-back started working perfectly. Of course that meant revision D had to be made.

D? No issues what-so-ever. :)