All posts by Takaitra

About Takaitra

Matthew is a software engineer for Amazon's Cloud Drive team working with various technologies including web services, React Native and Android. His interests include motorcycling, camping, photography, small electronics and traveling. He lives in Seattle, Washington with his beautiful wife and two children.

Calibrating the PCF8523 RTC without an oscilliscope

I recently purchased the excellent PCF8523 real time clock breakout board from Adafruit for a project. It was easy to interface with using I2C and the RTClib Arduino library. It keeps the time for up to five years even with no external power by using a coin cell battery.

The only trouble was that the clock was not terribly accurate and after a few weeks was fast by several minutes. A perfect crystal would oscillate at exactly 32.768 kHz but various factors like temperature, pressure and humidity make it faster or slower. In my case, the crystal was oscillating too quickly causing the RTC to be fast by 8 seconds per day.

After reading through the PCF8523 datasheet I found that the RTC can be calibrated by setting a value in one of the device registers. Section 8.8.3 describes a way to calculate the register value.

Offset calibration calculation workflow

I do not have an oscilloscope with a high enough resolution to accurately measure the frequency for step 1. Is it possible to calculate the offset without one? The NXP application note discussing improved timekeeping has some useful tidbits beyond what was described in the datasheet. Most important is the fact that 1 second of clock drift per day corresponds to an error of 11.57 parts per million for a 32.768 kHz oscillator. By measuring the drift of the clock over a few days we can do some simple calculations and calibrate the RTC.

RTC offset calculation

Record the current time along with how it compares to the clock on the RTC. Wait a few days and do it again.22:21 on Jul 18
RTC is behind actual time by 7 seconds

19:11 on Jul 21
RTC is ahead of actual time by 18 seconds
Calculate the time between your two measurements in days3 days - 3 hours, 10 minutes
= 3 days - 0.125 days - 0.00694 days
= 2.86806 days
Calculate the amount of drift between your two measurements7 s + 18 s = 25 s
Calculate the amount of drift per day25 s / 2.86806 days
= 8.7167 s/day
Using the fact that 1 second of drift per day = 11.57 ppm, calculate the drift in ppm.11.57 ppm/day * 8.7167 days = 100.85 ppm
Use the value from the datasheet to calculate the offset register value100.85 / 4.34 = 23.234 => 23 correction pulses

What does “correction pulse” mean? The RTC will extend or reduce the amount of time required to consider that a second has elapsed. This is the value that gets placed in the first (least significant) 7 bits of the offset register.

  • If your clock is running fast you need to write a positive value to the register. This increases the number of oscillations required for a second to elapse, thereby slowing down the clock.
  • If your clock is running slow you need to write a negative value to the register, coded in two’s complement. This reduces the number of oscillations required for a second to elapse, thereby speeding up the clock.

Writing to the offset register

Since the 8th bit of the register contains the mode flag, determining the final byte that should be written to the offset register requires some bit manipulation. I’ve added a calculate method to the RTClib Arduino library that does this for you. The calibrate function can be called like this:


ZXSC380 LED Driver Breakout Board

How to design and build a breakout board for an SMD component

As electronic components become ever more integrated and miniaturized, it can sometimes be impossible to find a through-hole counterpart to an interesting SMD part. For example, I wanted to do some prototyping with the ZXSC30 LED Driver but it’s available only in a SOT23 package. With some attention to detail and the right equipment, it’s not difficult to design and build your own breakout board for such a component.


1. Design the Circuit

If you scan through the datasheet you’ll often find that this step is done for you, or nearly so. Look for a diagram called something like “Typical application circuit.” It is nice to include required passive components on the breakout board to make it as “plug and play” as possible. In this case, the only external component required beside the LED itself is a small inductor.

Typical application circuit for the ZXSC380

Load up a PCB design app like Eagle and re-create the circuit there.

Eagle schematic

The Eagle design files for this breakout board are available on GitHub.

2. Print the Circuit Boards

Oshpark is a circuit board printing service that is perfect for hobbyists. Create an account, upload your Eagle files, complete the purchase and you can expect to have perfect purple PCBs in your hand in a couple weeks. I’ve shared my board design in case you’d like to use it.

Board preview from Oshpark

and IRL

3. Create a Solder Paste Stencil

OSH Stencils is a great service to create a solder paste stencil. Again, create an account and upload your Eagle file. OSH Stencils will use the solder mask layer of your board design to fabricate a polyimide or stainless steel stencil perfectly matching your PCB.

Stencil preview from OSH Stencils

and IRL

3. Assemble the Board

Scoop up some solder paste using the squeegee provided by OSH Stencils and spread it over the aligned stencil. Then scrape over the board using an edge to force paste through the stencil. Scrape the extra solder paste back into its jar and carefully remove the stencil. If the solder isn’t lined up the way you hoped, clean it off with an alcohol wipe and try again.

Applying the solder paste

Use fine point tweezers to place the components. The pads should be somewhat aligned but do not need to be perfect. This is because once the solder liquefies, the surface tension tends to pull the component into place.

Turn on the hot air rework station and allow it to heat up. Then move the nozzle over the PCB until the solder liquefies. Probably don’t do this on your wood table top =P

4. Test

Create a simple test circuit for your PCB to make sure it works. In this case I connect a AA battery to VCC/GND and an LED to VOUT/GND. A single AA battery does not have enough voltage to power an LED on its own but with the ZXSC380, the LED lights up brightly. Neato!

micro:bit Compass

The other day I bought a micro:bit for my daughter. It’s a small computer with bluetooth, an accelerometer, light sensor, magnetometer and temperature sensor. It also has a couple of buttons for input and a matrix of LEDs for output. It’s become obvious that I’m way more interested in playing with it than my daughter is but I’m hopeful that after I show her what it can do, she’ll take an interest in writing some code for it herself.

My first small program takes the input from the compass and writes out the cardinal directions, N, S, E and W.

This is what the program looks like in Blocks

and here is the equivalent JavaScript code

Below is an emulator running this code. Drag the compass near the top and you will see the text on the micro:bit change.

Finally, here is a video of the code running on the actual device

If you’d like to play with this project yourself, you can do so here:

Fractal Design R4 Headphone Jack Repair (USB-70A AZALIA)

I’ve been using the Fractal Design R4 PC case for a number of years now. I love the design but the placement of the headphone jack leaves something to be desired. It is oriented vertically meaning that pulling on the headphone cable can easily break the port which unfortunately happened to me. Removing the front panel of the case reveals a small circuit board labeled “USB-70A AZALIA REV: A1”.

The circuit board with damaged headphone jack

Not designed with toddlers in mind

A quick search showed me that it’s not easy to find a replacement for this part so I decided to write up how it can be repaired.

The board consists of two headphone jacks and a pin header. The broken headphone jack needed to be replaced. The first step is finding the correct replacement part. Some searching reveals the CP1-3525NG-ND on Digi-Key. I always order inexpensive parts in multiples of 10 to get the price break and because it’s good to have spare parts around for future projects.

A handsome array of headphone jacks

Using a soldering iron, heat up and remove as much of the solder around the pins of the headphone jack as possible. I didn’t have much luck with soldering wick but a soldering vacuum worked well. A trick is to add a small amount of solder to the tip of the soldering iron to help quickly heat the solder in the joint.

After removing the solder, gently remove the old headphone jack.

PCB after removing the broken headphone jack

Solder the replacement headphone jack into place. Heat the pin using the iron and apply enough solder so that it flows into each via.

I ended up replacing both jacks because the replacements have a metal ring that looks more sturdy than the original.

PCB with replacement headphone jacks

Both my headphones and a microphone worked great after putting everything back together. I was initially worried that the pinout of the replacement jacks might be different than the originals but they turned out to be an exact match.

Running Python CGI Scripts on the Raspberry Pi

Python is the language of choice for controlling the Raspberry Pi’s GPIO pins. It seems only natural then that to interact with your Pi over the web it should run a web server able to handle Python CGI scripts. Following the steps below will get the lightweight nginx web server running on your Pi, handing Python requests off to a uwsgi helper process.

  1. Install nginx
  2. Add a location to the /etc/nginx/sites-available/default to pass Python requests on to uwsgi. This needs to be placed inside the “server” block of the configuration, for example right after one of the existing “location” sections.
  3. Create a Python CGI script at /usr/share/nginx/www/
  4. Start nginx
  5. Build and install the uwsgi with the cgi plugin
  6. Create the file /etc/uwsgi.ini
  7. Create the file /usr/share/nginx/www/
  8. Create an init script for uwsgi at /etc/init.d/uwsgi
  9. Start uwsgi and configure it to start on boot
  10. Open up your web browser and go to http://{your pi’s ip address}/
    If you’re using the browser on your Pi then you could instead go to http://localhost/
    If you see the message “Hello World” then everything is working.

Controlling the MCP4151 Digital Potentiometer with the Raspberry Pi

We’re going to use the Raspberry Pi’s SPI bus to control Microchip’s MCP4151 8-bit digital potentiometer.  The MCP4151 is an 8 pin SPI device that can be used to programmatically control output voltage. The GPIO pins on the pi run at 3.3 volts meaning that we can command the pot to output between 0 and 3.3 volts. However, if we instead power the pot with 5 volts then we can control a voltage between 0 and 5 volts. Note that PWM is a possible alternative to a digital pot that doesn’t require an extra chip. However, this can add  noise to the signal that wasn’t acceptable for my project.

Microchip’s datasheet is recommended reading before starting this project.

Parts List

Step 1: Configure SPI on the Raspberry Pi

Follow the first two steps in Controlling an SPI device with the Raspberry Pi.

Step 2: Wire up the components

Being a pin-limited device, the SPI input and output on the MCP4151 shares one pin. That’s not a problem in our case since we’re only interested in writing to the device.

You’ll notice that we’re powering the pot with 5 volts despite the Raspberry Pi being a 3.3 volt device. This is fine because 1) The Pi sends commands to the pot but receives nothing back. Therefore, there is no risk of overvoltage on the Pi’s pins. And 2) The pot recognizes any SPI input over 0.7 volts as a high signal. This means the 3.3 volts from the Pi is plenty to communicate with the pot.

digital pot

As you can see, the power, ground and the SPI signals take up most of the pins. The actual potentiometer terminals are pins 5, 6 and 7.

Pin Description
1 SPI chip select input
2 SPI clock input
3 SPI serial data input/output
4 Ground
5 Potentiometer terminal A
6 Potentiometer wiper terminal
7 Potentiometer terminal B
8 Positive power supply input



Step 3: Create the python script

To test out the device, we’re going to continuously loop through all the possible values for the potentiometer. This will cause the voltage at the wiper terminal grow and shrink between 0 and 5 volts. Create the following script on your Pi.


import spidev
import time

spi = spidev.SpiDev(), 0)
spi.max_speed_hz = 976000

def write_pot(input):
    msb = input >> 8
    lsb = input & 0xFF
    spi.xfer([msb, lsb])

while True:
    for i in range(0x00, 0x1FF, 1):
    for i in range(0x1FF, 0x00, -1):

Step 4: Run the script

Make the script executable and run it with the following commands.

If all goes well, you should see the LED continuously fade to full brightness then off again.

Controlling an SPI device with the Raspberry Pi

The Raspberry Pi has a Broadcom BCM 2835 chip allowing it to interface with SPI devices on its GPIO pins. There are two chip select pins meaning that the Pi can control two devices simultaneously.

P1 Header Pin Function
19 MOSI – master output slave input
21 MISO – master input slave output
23 SCLK – clock
24 CE0 – chip enable 0
26 CE1 – chip enable 1

Step 1: Enable SPI on the Raspberry Pi

  1. In your Pi’s terminal, run
  2. Go to Advanced Options > SPI
  3. Choose “Yes” for both questions then select Finish to exit raspi-config
  4. Either reboot your Pi or run this command to load the kernel module

Step 2: Install spidev

Spidev is a python module that allows us to interface with the Pi’s SPI bus.Watch movie online The Transporter Refueled (2015)

Step 3: Python script

Finally, we can write and run a python script to control the SPI device.

  1. Create a file called in your favorite editor
  2. Make the file executable and run it

Notes on spidev

Unless the spi.max_speed_hz field is a value accepted by the driver, the script will fail when you run it. The field can be set to these values on the raspberry pi:

Speed spi.max_speed_hz value
125.0 MHz 125000000
62.5 MHz 62500000
31.2 MHz 31200000
15.6 MHz 15600000
7.8 MHz 7800000
3.9 MHz 3900000
1953 kHz 1953000
976 kHz 976000
488 kHz 488000
244 kHz 244000
122 kHz 122000
61 kHz 61000
30.5 kHz 30500
15.2 kHz 15200
7629 Hz 7629

Two SPI devices can be controlled in python by creating two SpiDev objects, one for each device.

Manual WordPress Upgrade – The Easy Way

I choose to not run FTP on my server so when it comes time to upgrade WordPress, I do it manually. If, like me, you think that even the short instructions are too long, here are the even shorter instructions. These commands are done within an SSH shell on the server.

  1. Backup your existing WordPress install and database
  2. Download WordPress and upgrade using the below commands. Replace the directories with those specific to your system.
  3. Visit your main WordPress admin page at /wp-admin and upgrade the database if necessary.

Motorcycle Garage Door Opener

In the past it was a hassle to get off of my motorcycle to key in the garage door code before getting back on the cycle to pull it into the garage. Stashing a garage door opener in my jacket pocket was a little better but I still had to stop to take off my motorcycle gloves. My solution was to hack a garage door opener to activate via a switch on my handle bar. Because I do almost all of my riding in the city, I never use my passing switch so this was the one I chose to tap into. The following is a guide of how I did it and was done for a LiftMaster opener/remote. The same concepts should apply to other brands but I have not tried them.


  • A LiftMaster garage door remote. Make sure you get the correct remote for your opener (based on whether the learn button on your opener is red-orange or purple ). I used the remote with only one button to keep things simple.
  • A TO-92 (3 pin through hole) NPN transistor. I bought a pack of these from RadioShack. The specific one I used is KSP2222A but there are many equivalent part numbers that will work.
  • A 2.7M Ohm 1/4 watt resistor. If you can’t find this exact one, any resistor near this value should work. I bought a huge variety pack of resistors that included this one on eBay for only a few bucks.
  • Red and black small gauge stranded wire
  • A wiretap connector to tap into your motorcycle’s switch


  • Soldering iron
  • Flush/diagonal cutter for trimming the transistor leads
  • Solder sucker or copper braid to remove the solder from the remote’s button
  • Something to notch the side of the remote. A dremel tool works well for this.

Step 1: Remove the Push Button Switch

If you haven’t already, don’t program your remote for your opener yet. You don’t want to accidentally be opening and closing your garage door while working on this project. Begin by opening up the case of your remote and removing the circuit board.

The remote with the case opened
The remote with the case opened

You’ll see a small black and silver momentary push button switch near the bottom. Pressing down on this switch completes a circuit which activates the opener. We want to remove the switch so that we can replace it with a transistor activated by a 12V signal from the bike. Use your soldering iron and solder sucker or copper braid to remove the solder from the pins of the button.

Removing the solder from the button's pins
Removing the solder from the button’s pins

After the solder is removed, the button will easily come off of the board.

Circuit board with the button removed
Circuit board with the button removed

Step 2: Solder the transistor

Next we need to replace the button with the transistor. The transistor acts as an electronic switch. When the base of the transistor is activated by the 12 volts from the motorcycle, it will allow current to flow from the collector to the emitter. Bend up the middle lead of the transistor and insert the other two leads into the circuit board. Make sure it matches the orientation shown in the photo.

The circuit board with transistor
The circuit board with transistor

Then solder and trim the leads on the reverse side of the board.

The transistor leads soldered and trimmed
The transistor leads soldered and trimmed

Step 3: Add the Resistor

Only a very small current is needed for the remote’s circuit to consider our new switch “closed.” We’re going to solder a resistor to the base of the transistor to make sure we don’t damage it when we send it 12 volts from the motorcycle. Clip the leads short on the resistor and solder it to the remaining transistor lead.

Ready to solder the resistor with a helping hand.
Ready to solder the resistor with a helping hand.

Step 4: Solder signal and ground wires

Cut a couple feet of red and black wire and strip the ends. Solder one end of the red wire to the end of the resistor.  Solder one end of the black wire to the circuit board as shown.

LiftMaster PCB
The Modified LiftMaster PCB

Step 5: Modify the case

You’ll need to cut a couple notches into the garage door opener’s case where the wires will come out. I believe I used a dremel tool for this. When you’re done, thread the wires through the notches, and snap the circuit board back into its case.

The notched opener case.
The notched opener case.

Modified LiftMaster
With the modifications to the LiftMaster garage door opener complete, it’s ready to install on the motorcycle.

Step 6: Program and test the remote

For this step you need access to a 12 volt power source–the terminals of your motorcycle’s battery will work in a pinch. To program the remote, tap the orange or purple learn button on your opener then hold the red wire to the positive terminal on the battery and the black wire to the negative terminal for a few seconds. Your garage door light should blink when the programming is complete.

Now disconnect the remote then connect it once more. If your garage door activates, it’s working!

Step 7: Install opener on motorcycle

This is where you get to be a bit creative. I chose to tap the red signal wire into the high beam wire on my SV650, allowing me to use my passing signal to trigger the garage door opener. To do this, I made a small cut to get into the wire bundle near my steering column then used the posi-tap connector to make the connection. I then wrapped the bundle back up with electrical tape. You can either connect the ground to a ground wire on your motorcycle or to any metal part of the frame. I chose to screw it down using the screws holding down my gas tank.

Finally, you’ll need a place to stash the remote. On my SV650, I found that there was extra space underneath my gas tank in front of the airbox.

I forgot to take pictures of this step but if you think it’d be helpful let me know and I’ll post some. Have fun and enjoy your motorcycle’s new garage door opening abilities!