Bad things happen when programmer finds a soldering iron

Adding USB to A-BFastiron SS-305MP

Illustration

I needed a cheap power supply for a project and it was easy to find a nice one in A-BFastiron SS-305MP. It was small enough, looked good, and had shiny display. What could man want more?

Well, when I got it and saw cutout for USB, I know what more I wanted. An USB port.

And strangely enough once you open the power supply, you’ll find connector providing about 8.2 V already there without anything to plug into. It’s almost as if somebody placed it there to be an input for 5V linear voltage converter and then later figured electronics and heatsinking would cost too much and covered the hole. And yes, it’s a proper hole cover that you can remove - no drilling necessary.

If you open power supply you will even find standoffs already in place. It’s simply begging to have PCB mounted in.

First thing to figure out was which USB connector will fit. Searching on DigiKey found quite a few of them roughly matching the dimensions. So I just selected the cheapest one that matched standard footprint. And yes, looking on side you might find it protruding a bit too much but not criminally so. It might be original designers were fine with this or the had a custom length connector in mind. For me this was as good as it gets.

With connector found, it was time to figure PCB. And I decided to keep it really simple. The whole setup would revolve around VXO7805-1000. It’s a nice DC-DC switching regulator that will take any input higher than 8 V and drop it down to 5 V with some efficiency. In its pinout it emulates beloved LM7805 but at 90% efficiency and without all the heat.

Regulator itself requires just two capacitors and I decided to go just with them. I was tempted to add a smaller 1 µF capacitor to output and maybe even a 100 nF one for decoupling purposes but decided against it. Due to wide variety of cables and outputs USB device might face, all of them already have more than sufficient decoupling and adding more wouldn’t really do anything. So why waste a component.

The only really unneeded components would be an LED and its accompanying resistor. While they serve no function, I really love to have an indicator of output. If there was ever an issue, looking at LED would at least tell me if power is going out. And quite often that’s quite a big help.

Speaking of power going out, I don’t consider a fuse optional. It’s a minimum you need in this setup. Another thing I would consider bare minimum for power supply would be a short-circuit detection but that’s fortunately already a part of voltage regulator. And yes, I could have gone further, especially by adding reverse polarity protection to the input and I was tempted but in reality you’ll just connect this thing once and leave it connected. As long as you connect it correctly the first time, you’re good.

Illustration

Connecting all this to the power is entrusted to any JST-XH 2-pin cable - 10 cm in length. Just make sure that the negative wire is going next to COM marking on the power supply motherboard. If in doubt, just double-check with voltmeter.

And that’s it. For a few bucks more and some extra soldering, we have a nice 500 mA USB port at the front of the power supply. Just in case we need it.

On GitHub you’ll find source files and releases with gerbers and part list.

Changing A-BFastiron SS-305MP Binding Posts

Illustration

I needed a cheap power supply for a project and it was easy to find a nice one in A-BFastiron SS-305MP. It was small enough, looked good, and had shiny display. What could man want more?

Well, how about proper binding posts?

And no, I am not only talking about quality albeit one coming with it are quite flimsy and it already arrived with one cracked. I am talking about spacing. I simply hate when binding posts don’t observe standard ¾" distance between them.

And this power supply almost had it right. I measured spacing to be a smidgen over 20 mm while standard would call for 19.05 mm. With such a small difference, there was literally no reason to go non-standard. But non-standard they went.

If you open the power supply, you’ll see that binding posts are held by the PCB in the back. Thick wires are soldered onto it and nuts are used to connect to posts themselves. So the whole operation can be done with a simple PCB update with correct spacing. Only thing needed extra is a bit of filing action and you can reassemble it all.

However, since my binding post was already cracked, I decided to swap them for Pomona 3760 (black and red) set. But that brought another issue - panel cutout for them is completely different. And yes, a patient man might shape it enough, but for those with 3D printer there’s an easier solution.

Illustration

To mount it all, I used some nice red MH Build PLA to print really tight mounting base and spacer for posts.

After filing plastic a bit to expand holes toward each other, I placed binding posts into the printed base, pushed it through the hole, used another 3D printed spacer on inside and added some more height to set using spacers that came with binding posts themselves. Then in goes the custom PCB and finally all can be fastened using lock washer and nut that cane with posts.

Result are nice binding posts at proper spacing. :)

On GitHub you’ll find source files and releases with gerbers and part list. 3D model can be found on TinkerCAD.


PS: The only downside of Pomona is that it uses ¼" imperial nuts while the power supply originally had 7 mm nuts. So, in addition to metric socket set you already have, you’ll need a witchcraft-sized set too.

Well Grounded

Playing with electronics as a hobby has its advantages. Most notably, I don’t need to deal with high-speed signals or EMC most of the time. However, in the days of faster and faster I/O, high-frequency content “sneaks in” whether you want it or not. Just because your microcontroller works at 48 MHz, that doesn’t mean your I/O edge is not (much) faster. And sorting out those issues is hard.

Fortunately, there are many “rule-of-the-thumb” guides out there, but I found none better than Rick Hartley’s. Well worth the watch.

DKRed

Illustration

While I use OSH Park most of the time, I always like to look at different services, especially if they’re US-based. So, of course I took a note of DigiKey’s DKRed. Unfortunately, review will be really short as I didn’t end up using it.

On surface it looks good. Board requirements are reasonable. If you want to use DKRed service you need to have your design fit 5/5 mil minimum - more than sufficient for all I do. While more detailed specifications are available for other PCB vendors on their platform (albeit Royal Circuits has a bad link), there’s nothing about DKRed itself. Yes, I know DKRed might use any of manufacturer’s behind the scene but I would think collating minimum requirements acros all of them should be done by DigiKey and not left to a customer.

And not all limitations are even listed on that page - for example, fact that internal cutouts are not supported is visible only in FAQ and whether slots are supported is left as a complete secret. Compare this to OSH Park’s specification and you’ll see what I mean.

But ok, I went to upload one small board just to test it. And I was greeted by error that length is shorter than 1 inch. As I love making mini boards smaller than 1", I guess I’m out of luck. But specification page did correctly state that fact so I cannot be (too) angry. Never mind - I’ll try a slightly bigger board. Nope - it has to be more than 4 square inches in area. Something that I didn’t find listed anywhere.

Well, I had need for one board 65x72 mm in size - that one would work. And yes, DKRed finds that board OK. But cost is $43.52. OSH Park charges $36.25 for the same board. And yes, DKRed gives 4 boards ($10.88 per board) while OSH Park only provides 3 ($12.08 per board) so it’s slightly cheaper if you really need all 4 boards. If you’re hobbyist requiring only 1 board like me, you’re gonna pay more.

And this is where I stopped my attempts. Breaking deal for me was the minimum size as this makes it a no-go for most of my boards. And cost for just a prototyping is just too high. Mind you, it might be a good deal for people regularly working with bigger boards at a small quantity. But it’s not for me.

Randomness in 8-bit Microchip PIC

Generating pseudo-random (or even fully random) numbers on desktop computers is mostly a solved problem. However, what if we need to generate random numbers on much smaller devices? For example, on Microchip’s 8-bit PIC16F1454 microcontroller?

Good news first, mersenne twister is no longer the only player in town. These days we have a whole family of both faster and more random algorithms courtesy of Guy Steele and Sebastiano Vigna. Their xoshiro / xoroshiro generators cover essentially any combination of speed and memory needs. They are probably a pinnacle of randomness quality you can fit in such a minimal space.

Since I did need a minimal footprint, I first selected xoroshiro64**.

uint32_t rotl(const uint32_t x, int k) {
    return (x << k) | (x >> (32 - k));
}

uint32_t s[2];

uint32_t next(void) {
    uint32_t s0 = s[0];
    uint32_t s1 = s[1];
    uint32_t result = rotl(s0 * 0x9E3779BB, 5) * 5;

    s1 ^= s0;
    s[0] = rotl(s0, 26) ^ s1 ^ (s1 << 9);
    s[1] = rotl(s1, 13);

    return result;
}

This code will generate random numbers that pass vast majority of DieHarder randomness tests and all that just in 58 bytes of data memory and 365 words of program memory (freeware XC8 2.31, with optimizations).

While this is probably as small as a good random number generator can reasonably get on a microcontroller, Microchip PIC is an 8-bit device at heart and dealing with 32-bit values doesn’t come naturally. Fortunately, xoroshiro algorithm family scales reasonably well and one can “borrow” the setup.

Here is my stab at making xoroshiro a bit more 8-bit friendly.

uint8_t rotl(const uint8_t x, int k) {
    return (x << k) | (x >> (8 - k));
}

uint8_t s[2] = { 0, 0xA3 };

uint8_t next(void) {
    uint8_t s0 = s[0];
    uint8_t s1 = s[1];
    uint8_t result = s0 + s1;

    s1 ^= s0;
    s[0] = rotl(s0, 6) ^ s1 ^ (s1 << 1);
    s[1] = rotl(s1, 3);

    return result;
}

Now, this is a simplified version and definitely not as random as the full implementation. Obvious change is in a state variable size (16 instead of 64) and calculation is taken from xoroshiro128+ so that multiplication can be avoided. There are no multiplication circuits in 8-bit PIC microcontrollers and thus this makes code much smaller and faster.

Lastly, the half of initial state is fixed to 0xA3. When dealing with such a small state, not all combinations of initial state are valid nor they produce equally long period and this is essentially just a workaround to keep numbers coming.

This simplified version needs 10 bytes of data memory and takes only 65 words of program memory. A great improvement (more than 5x in both data and program memory) albeit at significant randomness cost. First of all, you essentially only get 256 seeds with large enough period (64897 bytes). Secondly, the whole space can be only 16-bits to start with. While this might barely pass a few DieHarder tests (e.g. birthdays, 2dsphere, dab_dct, and rgb_permutations), it won’t come even close to the full xoroshiro64** in terms of randomness quality. And let’s not even mention higher state size algorithms.

That said, if you just need random numbers for a game or something similar on a highly constrained device, I would say that quality trade-off is worth the speed and memory usage improvements.


PS: If you initialize random number generator with static values (which is perfectly valid), you will always get the same set of random values. Sometime that is a desired feature (e.g. during debugging) but we usually want something more unpredictable. Assuming you’re using the chip with a separate low-frequency oscillator (LFINTOSC), you can rely on a drift between it and a high-frequency oscillator to get a reasonably random seed.

void init(void) {
    // setup timer if not already in use
    T1CONbits.TMR1CS = 0b11;
    T1CONbits.T1OSCEN = 1;
    T1CONbits.TMR1ON = 1;

    _delay(4096);  // just to improve randomness of timer - can be omitted

    // initialize using timer values (ideally you would wait a bit after starting timer)
    s[0] = TMR1L;
    s[1] = 0x2A;  // important to get high periods and to avoid starting from 0x0000
}

PPS: No, xoshiro algorithms are not cryptographically secure. If you need to generate keys on microcontrollers, look into specialized hardware. These algorithms are intended for general-purpose randomness.

PPPS: Code is available for download. It will use 10 bytes of data memory and should fit into 82 words of program memory with initialization from LFINTOSC.

Storing Settings on PIC16F1454

As I was playing with PIC16F1454, I came to the point where some configurability would be in order. You know how it goes with PIC microcontrollers - just write it in EEPROM and you’re good. Unless there is no EEPROM like there is none for PIC16F1454.

Never mind, I had this issue before, so I can just copy my own code (ab)using program memory for the same purpose. Guess what? There are some issue with this too.

The first of all my old code was for different microprocessor. While principle is the same, it’s not an exact match. The second reason was changes to XC8. My old code doesn’t properly compile on XC8 2.00 - they changed how location is defined. The third (and the last) reason is high-endurance flash that PIC16F1454 supports. Unlike normal flash that’s rated for 10K writes, last 128 of this PICs program memory is rated to 100K. Albeit 10K is nothing to frown about, 100K is much nicer - especially if I end up changing data a lot.

Second and third reason share the same fix. Memory definition looks like this:

#define _SETTINGS_FLASH_RAW { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                              0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
#define _SETTINGS_FLASH_LOCATION 0x1FE0

const uint8_t _SETTINGS_PROGRAM[] __at(_SETTINGS_FLASH_LOCATION) = _SETTINGS_FLASH_RAW;

This will use the last 32 bytes, starting at 0x1FE0. This address is conveniently 32 bytes before end, falling without issues within “the last 128 bytes” high-endurance category. Now, if you need more memory, just make the array bigger and move it more forward. Just remember to do so in 32-byte increments as this is the block size for flash erase operation. If you don’t reserve all that memory, you might end up erasing your code and we wouldn’t want that. I personally never had need for more than 32 bytes of memory (i.e. one flash page) but your use case might differ.

All settings can be held in structure. Here I will have two settings - Address and DisplayHeight:

typedef struct {
    uint8_t Address;
    uint8_t DisplayHeight;
} SettingsRecord;

SettingsRecord Settings;

To read these settings, we just need to copy our reserved data (seemingly in _SETTINGS_FLASH_RAW variable) into the structure:

uint8_t* settingsPtr = (uint8_t*)&Settings;
for (uint8_t i = 0; i &lt; sizeof(Settings); i++) {
    *settingsPtr = _SETTINGS_PROGRAM[i];
    settingsPtr++;
}

Writing is a two step process. It starts by erasing the WHOLE 32-word/byte block. Following that, we get to write each byte separately:

bool hadInterruptsEnabled = (INTCONbits.GIE != 0);
INTCONbits.GIE = 0;
PMCON1bits.WREN = 1;  // enable writes

uint16_t address = _SETTINGS_FLASH_LOCATION;
uint8_t* settingsPtr = (uint8_t*)&Settings;

// erase
PMADR = address;         // set location
PMCON1bits.CFGS = 0;     // program space
PMCON1bits.FREE = 1;     // erase
PMCON2 = 0x55;           // unlock flash
PMCON2 = 0xAA;           // unlock flash
PMCON1bits.WR = 1;       // begin erase
asm("NOP"); asm("NOP");  // forced

// write
for (uint8_t i = 1; i &lt;= sizeof(Settings); i++) {
    unsigned latched = (i == sizeof(Settings)) ? 0 : 1;
    PMADR = address;            // set location
    PMDATH = 0x3F;              // same as when erased
    PMDATL = *settingsPtr;      // load data
    PMCON1bits.CFGS = 0;        // program space
    PMCON1bits.LWLO = latched;  // load write latches
    PMCON2 = 0x55;              // unlock flash
    PMCON2 = 0xAA;              // unlock flash
    PMCON1bits.WR = 1;          // begin write
    asm("NOP"); asm("NOP");     // forced
    address++;                  // move write address
    settingsPtr++;              // move data pointer
}

PMCON1bits.WREN = 0;  // disable writes
if (hadInterruptsEnabled) { INTCONbits.GIE = 1; }

The first and last step is dealing with interrupts. During write interrupts must be disabled. Code will disable them before writing and re-enable them afterward if needed.

Erase is easy enough. Just set FREE bit in the PMCON1 register followed by magic incantation (0x55, 0xAA, WR=1) and wait for a millisecond or two. Do note that NOP instructions are mandatory due to how self-writing program memory works. It’s one of the rare instances where NOP actually serves a purpose in C code.

To write data, process is close enough. Load all the bytes you wish to write using PMADR and PMDAT registers to set address and data. All bytes except the last will have LWLO bit set and will just cause loading of data into latches. The last byte must have LWLO cleared, signaling we’re done with writing. After a millisecond or two, bytes are done.

Two things are slightly curious there. The first one is setting of PMDATH to 0x3F. This value is actually the same as for erased cell and this just means we’re not changing it’s value. Note that upper byte is not the part of high-endurance flash and only 6-bit value (words are 14-bits on this PIC). Thus we really shouldn’t use it. The second strange decision is to start loop from 1 instead of the more conventional 0. This is so that we can determine if we’re at the last byte without substracting one.

In any case, this is all you need to make your program memory work as a storage for your settings.


PS: Procedure is the same on PIC16F1454, PIC16F1455, PIC16F1459, and probably quite a few more.

PPS: Whole code is available in Git repository.

PPPS: There is quite useful application note from Microchip (AN1673A) dealing with high-endurance flash. Their code uses similar but slightly different approach. If you don’t like this code, maybe theirs will tickle your fancy.

Duplicating Non-Reentrant Functions

Illustration

As I was playing with PIC16454 using USB, I kept getting these warnings: Microchip/usb_device.c:277:: advisory: (1510) non-reentrant function "_USBDeviceInit" appears in multiple call graphs and has been duplicated by the compiler

This was due to function being called from both main function and from interrupt handler. Since function could be interrupted at any point in time, this was definitely a problem and compiler did find a valid solution. However, this was a bit suboptimal for my case.

Since I had issue with only a few functions, I decided to make use of Hybrid option is XC8 compiler stack options. With this option warnings were gone. Surprisingly, this also made my code smaller. Hybrid stack compiled into 7181 words while standard Compiled stack was 7398.

If you have reentrancy happening in just a few functions, Hybrid option might be good for you.*


* Some restrictions apply. Please contact your fellow developers if your compile lasts longer than 4 hours.

The Cost of CyberCard

After publishing text about the CyberCard project I got the question from a friend. Wasn’t it cheaper to buy Jeff Mayes’ interface driver then to build my own?

Answer is yes - at $30 that board is cheap. But that’s not all. Even the original RMCARD205 at $150 is cheaper than what I spent.

First of all, there were 4 revisions. The first revision was a bit too large. Manually filing PCB did the trick for the troubleshooting but I wanted to have revision B with the correct width. While width was now correct, I accidentally shortened it a bit. And yes, this brought me to the third revision. For that revision I also changed MCP2221A to SOIC package. It wasn’t strictly necessary but I figured having all three ICs in SOIC looked nicer than having different package styles on the same board. The last revision D was just a bit more fiddling with design without any major change. Yes, there were some other changes but this was a gist of it.

Considering each revision was around $25 in PCB cost (OSHPark) and I spent about $50 in parts for them, project was more expensive than official RMCARD205 even without accounting for my time. Since the first version was actually working, you can view all the time and money spent afterward as wasted.

But I disagree. From the moment I started working on it I knew it would end more expensive than the original part. Even for the first board I spent more money in PCB and parts than what Jeff’s adapter would cost with shipping. I found this board to be the perfect project: it would result in something useful, it was simple enough that I could work with it whenever I had some spare time, cheap enough that it wouldn’t break the bank, and an excellent chance to setup PIC16F1454 as an USB device.

I was eyeing PIC16F1454 for a few years now (I still have sample from Microchip from when it was originally announced) but I never got around to. When I first started with the board design I noticed MCP2221A USB-to-serial bridge was compatible with 16F1454’s footprint. If I was a betting man, I would have said that MCP2221A was nothing other than PIC16F1454 with the custom code. This project gave me a reason to get into this interesting PIC and do some USB programming.

I actually paid not for the final board - no matter how well it works. I paid a good money to keep me entertained and to fill my free time. And it was worth every penny.

Connecting to CyberPower OR500LCDRM1U UPS Serial Port

Illustration

To keep my file server and networking equipment running a bit longer in the case of power outage, I have them connected to CyberPower OR500LCDRM1U UPS. It’s a nice enough 1U UPS but with a major issue - no USB connection.

Well, technically there is an USB connection but it doesn’t work under anything else than Windows. If you want it working under Unix, the only option is RMCARD205, optional network module upward of $150. Essentially doubling the price of UPS.

And it’s those internal connections Jeff Mayes took advantage of for a simple serial interface. If the only thing you want is a serial interface, you might as well go with his interface driver as price is really reasonable.

However, his boards require you to either have a serial port or to have an USB-to-serial cable. What I wanted was direct USB connection. Since there was nothing out there, I decided to roll my own.

Since I had an UPS locally, it was easy enough to get physical dimensions. Unfortunately just measuring them wasn’t sufficient as they narrow as you go deeper so my first assumption of 3.1x1.7 inches was a bit off. Due to that and bottom connector that was a bit shallower then expected, the final board dimensions were more like 71x43 mm. It took a bit of probing to find the 4 signals I needed were grouped together with GND and RX on the bottom while TX and 12 V were on the top.

Connecting the appropriate serial connections to UART-to-USB converter like MCP2221A was a minimum required but I felt a bit queasy about connecting it directly to my computer. Therefore I decided to isolate the UPS interface from the computer. For this purpose I used Si8621 digital isolator offering 2,500 V isolation which was probably an overkill but allowed me to sleep better.

The last physical piece needed was a cover for card to avoid having a large opening in the back of my rack. While risk of anything getting inside is reasonably low, making a 3D printed cover was easy enough. It took a few tries to get cover design right in TinkerCAD but it avoided having a gaping hole.

If you are interested in making one for yourself, check project page for all the files.

Easy Type-C, Finally

It has been a while since USB Type-C became popular but I still avoided it for my hobby designs. It wasn’t due to its performance, oh no - performance was much better than what I needed. You see, I still use USB 2.0 for literally all my electronics projects. While not fast in the grand scheme of USB, it’s plenty fast for serial communication and that’s what I end up designing my gadgets around 90% of the time. My issues with the connector were due to soldering. Hand-soldering, to be precise.

Most of the type-C receptacle designs are of surface-mount kind. On its own that’s not an issue - I’ve hand-soldered my share of finicky narrow pitch ICs. Issue is the location of 24 pins that are needed. While 12 pins are almost reachable by a thin soldering iron, the other 12 pins are usually under the device. Not an issue if you are making them professionally or even in an oven but impossibility for soldering by hand.

And no, you cannot solder just one side of connector and be compliant. It doesn’t matter if you’re only interested in USB 2.0 as I was - you still need to connect both sides as you need to connect 5.1K resistor for device to be properly recognized. And yes, even if you fail to do that it will work with the type-A to type-C cable. It will sometimes work even with the type-C to type-C. However, things that happen only sometimes have a nasty habit of happening at the most unfortunate time.

Connectors that used a combination of through-hole design and surface-mount pads looked promising on the paper. The unreachable pads underneath were converted to pins and soldering problem got solved. Unfortunately, a lot of such connectors had a shield over the rear pads. Now rear pads became a problem. I did find a few with more open space that were easier to hand-solder but at a pricey $3.

But finally, I found the type-C connector that suits my use case perfectly - USB4085-GF-A. It’s an USB 2.0 connector that allows connection to 16 out of 24 type-C pins. The sacrificed pins mean that you won’t ever be able to use it with the high-speed devices (thus 2.0 moniker). However, the pins that remain include not only all the standard USB 2.0 power and data connections but also CC1 and CC2. These two pins are really important if you want your device to be part of the type-C universe and pull 1.5 A of current. The only thing needed in addition to the old type-A designs is two 5.1K pull-down resistors on each of those pins and you’re golden.

Mind you, the connector is not perfect. At $1.50 it’s a bit pricey but not excessively so. If you are using the standard 1.6 mm PCB, you will need to take a great care to position it flush in order for short pins to even reach to the other side. Hole spacing means you will need to use 6/6 PCB manufacturing which, while often supported, is still a bit less common than bog-standard 8/8. But these are all minor issues and hand-soldering is a breeze.

And despite all this goodness, I only used it for a few test contraptions and not in any of my proper projects. This is due to its biggest drawback - there is only one manufacturer and, outside of my initial purchase, they are pretty much on backorder the whole time. Even at the time of this writing, the quantity is 0 on DigiKey.

Once this connector becomes more available, I am looking forward to using it.


PS: For those wanting to have type-C plug directly on the board, there is a Molex 105444-0001. Just don’t forget to order 0.80 mm PCB.

PPS: For the 90° type-C connector, KUSBX-SL-CS1N14-B looks promising as it also allows connection to both CC1 and CC2 - a necessity for the proper type-C device. I haven’t tried it myself though.