The personal website of Scott W Harden
December 17th, 2022

Divide 10 MHz to 1PPS with a Microcontroller

I often find it useful to gate frequency counters using a 1 pulse per second (1PPS) signal derived from a 10 MHz precision frequency reference. However, a divide-by-10-million circuit isn't trivial to implement. Counter ICs exist which enable divide-by-100 by combining multiple divide-by-2 and divide-by-5 stages (e.g., MC74HC390A around $0.85 each), but dividing 10 MHz all the way down to 1Hz would require at least 4 of these chips and a lot of wiring.

You can clock a microcontroller at 10 MHz and use its timer and interrupt systems to generate 1PPS. For example, an ATTiny202 in an 8-pin SOIC package is available from Mouser (>50k stocked) for $0.51 each. Note that modern series AVRs require a special UDPI programmer.

ATTiny202 ($0.51) ATTint826 ($0.95)

This page documents a divide-by-10-million circuit achieved with a single microcontroller to scale a 10MHz frequency reference down to 1PPS. I'm using an ATTiny826 because that is what I have on hand, but these concepts apply to any microcontroller with a 16-bit timer.

ATTiny Breakout Board

Some AVRs come in DIP packages but their pin numbers may be different than the same chip in a SMT package. To facilitate prototyping using designs and code that will work identically across a breadboard prototype and a PCB containing SMT chips, I prefer to build DIP breakout boards using whatever SMT package I intend to include in my final builds. In this case it's ATTint826 in a SOIC-20 package, and I can easily use this in a breadboard by soldering them onto SOIC-to-DIP breakout boards.

I assembled the breakout board by hand using a regular soldering iron. When working with small packages it helps so much to coat the pins with a little tack flux to facilitate wetting and prevent solder bridges. I'm presently using Chip Quik NC191. Even if flux is advertized as "no-clean", it's good practice and makes the boards look much nicer to remove remaining flux with acetone and Q-tips or brushes.

Circuit

  • FTDI breakout board for power: To test this design I'm using a FT232 breakout board just to provide easy access to GND and Vcc (5V from the USB rail).

  • 10 MHz can oscillator: It's not ovenized or GPS disciplined, but I'm using this as a stand-in for whatever high-precision 10 MHz frequency standard will eventually be used in this circuit. The important thing is just to know that it outputs 0-5V square waves at 10 MHz going into the EXTCLK pin of the microcontroller

  • UPDI Programmer: I'm using the Atmel-ICE, but a MPLAB Snap would also work here. See Programming Modern AVR Microcontrollers for more information.

  • Output: A LED on an output pin will visualize the 1pps signal

Configuration Change Protection (CCP)

Traditional AVR microcontrollers used fuse bits to set the clock source, but modern series chips can change the clock source from within code. However, modifying the clock source requires temporarily disabling the configuration change protection (CCP) system.

Disabling the CCP only lasts four clock cycles, so the immediate next statement must be assignment of the new value. I use the following function to facilitate this action.

/* Write a value to a CCP-protected register */
void ccp_write(volatile register8_t* address, uint8_t value){
    CCP = CCP_IOREG_gc;
    *address = value;
}
// Use internal 20 MHz clock with CKOUT pin enabled
ccp_write(&CLKCTRL.MCLKCTRLA, CLKCTRL.MCLKCTRLA | CLKCTRL_CLKOUT_bm);

Do not use compound statements when writing to the CCP register. The code below fails to change clock as one may expect by looking at the code, presumably because the combined OR operation with the assignment exceeds four clock cycles. Instead of direct assignment, use the ccp_write function described above.

// WARNING: This code does not actually change the clock source
CCP = CCP_IOREG_gc;
CLKCTRL.MCLKCTRLA = CLKCTRL.MCLKCTRLA | CLKCTRL_CLKOUT_bm;

Configuring the Clock Source

Internal 10 MHz clock

This is the configuration I use to achieve a 10 CPU clock using the built-in 20 MHz oscillator.

void configure_clock_internal_10mhz(){
    ccp_write(&CLKCTRL.MCLKCTRLA, CLKCTRL.MCLKCTRLA | CLKCTRL_CLKOUT_bm); // 20 MHz internal clock, enable CKOUT
    ccp_write(&CLKCTRL.MCLKCTRLB, CLKCTRL_PEN_bm); // enable divide-by-2 clock prescaler
}

External 10 MHz clock

This is the configuration I use to clock the CPU from an external 10 MHz clock source applied to the EXTCLK pin.

void configure_clock_external(){
    ccp_write(&CLKCTRL.MCLKCTRLA, CLKCTRL_CLKSEL_EXTCLK_gc | CLKCTRL_CLKOUT_bm); // external clock, enable CKOUT
    ccp_write(&CLKCTRL.MCLKCTRLB, 0); // disable prescaler
}

Configuring the 16-Bit Timer

This is how I configured my ATTiny826's TCA0 16-bit timer to fire an interrupt every 200 ms.

  • Prescale: By enabling a divide-by-64 prescaler, my 10 MHz input becomes 156,250 Hz.

  • Top: By setting the top of my 16-bit counter at 31,250, I achieve exactly 5 overflows per second (once every 200 ms).

  • Interrupt: By enabling an overflow interrupt, I am able to call a function every 200 ms.

void configure_1pps(){
    // 10 MHz system clock with div64 prescaler is 156,250 Hz.
    // Setting a 16-bit timer's top to 31,250 means 5 overflows per second.
    TCA0.SINGLE.INTCTRL = TCA_SINGLE_OVF_bm; // overflow interrupt
    TCA0.SINGLE.CTRLB = TCA_SINGLE_WGMODE_NORMAL_gc; // normal mode
    TCA0.SINGLE.PER = 31249UL; // control timer period by setting timer top
    TCA0.SINGLE.CTRLA |= TCA_SINGLE_CLKSEL_DIV64_gc; // set clock source
    TCA0.SINGLE.CTRLA |= TCA_SINGLE_ENABLE_bm; // start timer
}

Alternatively, multiple timers could be cascaded to achieve a similar effect. Modern AVR series microcontrollers have sections in their datasheet describing considerations for cascading two 16-bit timers to create a single 32-bit timer. Using this strategy one could set the top of the counter to 5 million and arrange an interrupt to toggle an LED, resulting in a 1Hz signal with 50% duty.

Configuring the Interrupt System

This method is called whenever the timer's overflow interrupt is triggered. Since it's called 5 times per second, I just need a global counter to count the number of times it was called, and set an output pin to high on every 5th invocation.

uint8_t overflow_count;

ISR(TCA0_OVF_vect)
{
    overflow_count++;
    if (overflow_count == 5){
        overflow_count = 0;
        PORTB.OUT = PIN1_bm;
    } else {
        PORTB.OUT = 0;
    }

    TCA0.SINGLE.INTFLAGS = TCA_SINGLE_OVF_bm; // indicate interrupt was handled
}

Do not forget to enable global interrupts in your start-up sequence! This is an easy mistake to make, and without calling this function the overflow function will never be invoked.

sei(); // enable global interrupts

Results

We have achieved a light that blinks exactly once per second with roughly the same precision as the 10 MHz frequency reference used to clock the microcontroller. This output signal is ready to use for precision measurement purposes, such as toggling the gate of a discrete frequency counter.

Resources

Markdown source code last modified on December 23rd, 2022
---
Title: Divide 10 MHz to 1PPS with a Microcontroller
Description: How to use a microcontroller to inexpensively scale down a 10 MHz reference clock into a one pulse per second (1pps) signal
Date: 2022-12-17 1:09PM EST
Tags: circuit, microcontroller
---

# Divide 10 MHz to 1PPS with a Microcontroller

**I often find it useful to gate frequency counters using a 1 pulse per second (1PPS) signal derived from a 10 MHz precision frequency reference.** However, a divide-by-10-million circuit isn't trivial to implement. Counter ICs exist which enable divide-by-100 by combining multiple divide-by-2 and divide-by-5 stages (e.g., [MC74HC390A](https://www.onsemi.com/pdf/datasheet/mc74hc390a-d.pdf) around $0.85 each), but dividing 10 MHz all the way down to 1Hz would require at least 4 of these chips and a lot of wiring.

**You can clock a microcontroller at 10 MHz and use its timer and interrupt systems to generate 1PPS.** For example, an [ATTiny202](https://www.mouser.com/datasheet/2/268/ATtiny202_402_AVR_MCU_with_Core_Independent_Periph-1384964.pdf) in an 8-pin SOIC package is available from Mouser (>50k stocked) for $0.51 each. Note that [modern series AVRs require a special UDPI programmer](https://swharden.com/blog/2022-12-09-avr-programming). 

ATTiny202 ($0.51) | ATTint826 ($0.95)
---|---
<img src="ATTINY202-SOIC-8.png">|<img src="ATTINY826-SOIC-20.png">

**This page documents a divide-by-10-million circuit achieved with a single microcontroller to scale a 10MHz frequency reference down to 1PPS.** I'm using an [ATTiny826](https://www.mouser.com/datasheet/2/268/ATtiny424_426_427_824_826_827_DataSheet_DS40002311-2887739.pdf) because that is what I have on hand, but these concepts apply to any microcontroller with a 16-bit timer.

![](1pps-breadboard2.jpg)

## ATTiny Breakout Board

**Some AVRs come in DIP packages but their pin numbers may be different than the same chip in a SMT package.** To facilitate prototyping using designs and code that will work identically across a breadboard prototype and a PCB containing SMT chips, I prefer to build DIP breakout boards using whatever SMT package I intend to include in my final builds. In this case it's ATTint826 in a SOIC-20 package, and I can easily use this in a breadboard by soldering them onto [SOIC-to-DIP breakout boards](https://www.amazon.com/s?k=soic+dip+breakout).

![](breakout1.jpg)

**I assembled the breakout board by hand using a regular soldering iron.** When working with small packages it helps _so much_ to coat the pins with a little tack flux to facilitate wetting and prevent solder bridges. I'm presently using [Chip Quik NC191](https://www.amazon.com/s?k=NC191). Even if flux is advertized as "no-clean", it's good practice and makes the boards look much nicer to remove remaining flux with acetone and Q-tips or brushes.

![](breakout2.jpg)
![](breakout3.jpg)

## Circuit

* **FTDI breakout board for power:** To test this design I'm using a FT232 breakout board just to provide easy access to `GND` and `Vcc` (5V from the USB rail).

* **10 MHz can oscillator:** It's not ovenized or GPS disciplined, but I'm using this as a stand-in for whatever high-precision 10 MHz frequency standard will eventually be used in this circuit. The important thing is just to know that it outputs 0-5V square waves at 10 MHz going into the `EXTCLK` pin of the microcontroller

* **UPDI Programmer:** I'm using the Atmel-ICE, but a MPLAB Snap would also work here. See [Programming Modern AVR Microcontrollers](https://swharden.com/blog/2022-12-09-avr-programming) for more information.

* **Output:** A LED on an output pin will visualize the 1pps signal

![](1pps-breadboard.jpg)

## Configuration Change Protection (CCP)

**Traditional AVR microcontrollers used fuse bits to set the clock source, but modern series chips can change the clock source from within code.** However, modifying the clock source requires temporarily disabling the configuration change protection (CCP) system. 

Disabling the CCP only lasts four clock cycles, so the immediate next statement must be assignment of the new value. I use the following function to facilitate this action.

```c
/* Write a value to a CCP-protected register */
void ccp_write(volatile register8_t* address, uint8_t value){
	CCP = CCP_IOREG_gc;
	*address = value;
}
```

```c
// Use internal 20 MHz clock with CKOUT pin enabled
ccp_write(&CLKCTRL.MCLKCTRLA, CLKCTRL.MCLKCTRLA | CLKCTRL_CLKOUT_bm);
```

**Do not use compound statements when writing to the CCP register.**  The code below fails to change clock as one may expect by looking at the code, presumably because the combined OR operation with the assignment exceeds four clock cycles. Instead of direct assignment, use the `ccp_write` function described above.

```c
// WARNING: This code does not actually change the clock source
CCP = CCP_IOREG_gc;
CLKCTRL.MCLKCTRLA = CLKCTRL.MCLKCTRLA | CLKCTRL_CLKOUT_bm;
```

## Configuring the Clock Source


### Internal 10 MHz clock

This is the configuration I use to achieve a 10 CPU clock using the built-in 20 MHz oscillator.

```c
void configure_clock_internal_10mhz(){
	ccp_write(&CLKCTRL.MCLKCTRLA, CLKCTRL.MCLKCTRLA | CLKCTRL_CLKOUT_bm); // 20 MHz internal clock, enable CKOUT
	ccp_write(&CLKCTRL.MCLKCTRLB, CLKCTRL_PEN_bm); // enable divide-by-2 clock prescaler
}
```

### External 10 MHz clock

This is the configuration I use to clock the CPU from an external 10 MHz clock source applied to the `EXTCLK` pin.

```c
void configure_clock_external(){
	ccp_write(&CLKCTRL.MCLKCTRLA, CLKCTRL_CLKSEL_EXTCLK_gc | CLKCTRL_CLKOUT_bm); // external clock, enable CKOUT
	ccp_write(&CLKCTRL.MCLKCTRLB, 0); // disable prescaler
}
```

## Configuring the 16-Bit Timer

This is how I configured my ATTiny826's TCA0 16-bit timer to fire an interrupt every 200 ms.

* **Prescale:** By enabling a divide-by-64 prescaler, my 10 MHz input becomes 156,250 Hz.

* **Top:** By setting the top of my 16-bit counter at 31,250, I achieve exactly 5 overflows per second (once every 200 ms).

* **Interrupt:** By enabling an overflow interrupt, I am able to call a function every 200 ms.

```c
void configure_1pps(){
	// 10 MHz system clock with div64 prescaler is 156,250 Hz.
	// Setting a 16-bit timer's top to 31,250 means 5 overflows per second.
	TCA0.SINGLE.INTCTRL = TCA_SINGLE_OVF_bm; // overflow interrupt
	TCA0.SINGLE.CTRLB = TCA_SINGLE_WGMODE_NORMAL_gc; // normal mode
	TCA0.SINGLE.PER = 31249UL; // control timer period by setting timer top
	TCA0.SINGLE.CTRLA |= TCA_SINGLE_CLKSEL_DIV64_gc; // set clock source
	TCA0.SINGLE.CTRLA |= TCA_SINGLE_ENABLE_bm; // start timer
}
```

**Alternatively, multiple timers could be cascaded to achieve a similar effect.** Modern AVR series microcontrollers have sections in their datasheet describing considerations for cascading two 16-bit timers to create a single 32-bit timer. Using this strategy one could set the top of the counter to 5 million and arrange an interrupt to toggle an LED, resulting in a 1Hz signal with 50% duty.

## Configuring the Interrupt System

**This method is called whenever the timer's overflow interrupt is triggered.** Since it's called 5 times per second, I just need a global counter to count the number of times it was called, and set an output pin to high on every 5th invocation.

```c
uint8_t overflow_count;

ISR(TCA0_OVF_vect)
{
	overflow_count++;
	if (overflow_count == 5){
		overflow_count = 0;
		PORTB.OUT = PIN1_bm;
    } else {
		PORTB.OUT = 0;
	}
    
	TCA0.SINGLE.INTFLAGS = TCA_SINGLE_OVF_bm; // indicate interrupt was handled
}
```

**Do not forget to enable global interrupts in your start-up sequence!** This is an easy mistake to make, and without calling this function the overflow function will never be invoked.

```c
sei(); // enable global interrupts
```

## Results

**We have achieved a light that blinks exactly once per second** with roughly the same precision as the 10 MHz frequency reference used to clock the microcontroller. This output signal is ready to use for precision measurement purposes, such as toggling the gate of a discrete frequency counter.

<video playsinline autoplay muted loop class="border border-dark shadow-sm img-fluid">
  <source src="1pps.webm" type="video/webm">
</video>

## Resources

* Full source code: [ATTiny826 1pps project on GitHub](https://github.com/swharden/AVR-projects/tree/master/ATTiny826%20Timer%201pps) and specifically [main.c](https://github.com/swharden/AVR-projects/blob/master/ATTiny826%20Timer%201pps/ATTiny826%20Clock%20and%20Timer/main.c)

* Inspecting the header file `iotn826.h` in my Program Files / Atmel folder was very useful for identifying named bit masks stored as enums. There is a similarly named file for every supported AVR microcontroller.

* EEVblog forum: [Divide by 10000000](https://www.eevblog.com/forum/projects/divide-by-10000000/)

* EEVblog forum: [Divide by 10 prescaler for frequency counter](https://www.eevblog.com/forum/rf-microwave/divide-by-10-prescaler-for-frequency-counter/)

* EEVblog forum: [10MHz to 1pps divider](https://www.eevblog.com/forum/projects/10mhz-to-1pps-divider/)

* EEVblog forum: [Easiest way to divide 10MHz to 1MHz?](https://www.eevblog.com/forum/projects/easiest-way-to-divide-10mhz-to-1mhz/)

* YouTube: [Build a DIY Frequency Divider](https://www.youtube.com/watch?v=GlKWexGWoXw)

* [picDIV: Single Chip Frequency Divider](http://www.leapsecond.com/pic/picdiv.htm) (2011)

* [PICDIV on GitHub](https://github.com/aewallin/PICDIV)

* All About Circuits thread: [How to convert 10 MHz sine wave to 1Hz TTL (PPS)?](https://forum.allaboutcircuits.com/threads/convert-10-mhz-sine-wave-to-1hz-ttl-pps.54085/)

* [10 MHz to 1 Hz frequency divider using discrete 74HC4017D stages](http://www.perdrix.co.uk/FrequencyDivider/) by David C. Partridge
December 9th, 2022

Programming Modern AVR Microcontrollers

This page describes how to program Microchip's newest series of AVR microcontrollers using official programming gear and software. I spent many years programming the traditional series of Atmel chips, but now several years after Microchip acquired Atmel I am interested in exploring the capabilities of the latest series of AVR microcontrollers (especially the new AVR DD family). Currently the global chip shortage makes it difficult to source traditional ATMega and STM32 chips, but the newest series of AVR microcontrollers feature an impressive set of peripherals for the price and are available from all the major vendors.

TLDR

  • Older AVR microcontrollers are programmed using in-circuit serial programming (ICSP) through the RESET, SCK, MISO, and MOSI pins using cheap programmers like USBtiny. However, serial programming is not supported on newer AVR microcontrollers.

  • New AVR microcontrollers are programmed using the unified program and debug interface (UDPI) exclusively through the UDPI pin. UDPI is a Microchip proprietary interface requiring a UDPI-capable programmer.

  • Official UDPI programmers include Atmel-ICE ($129) and MPLAB Snap ($35). The Atmel-ICE is expensive but it is very well supported. The MPLAB Snap is hacky, requires re-flashing, and has a physical design flaw requiring a hardware modification before it can program AVR series chips.

  • There are notable attempts to create alternative programmers (e.g., jtag2updi and pymcuprog), but this journey into the land of unofficial programmer designs is fraught with abandoned GitHub repositories and a lot of added complexity and brittleness (e.g., SpenceKonde/AVR-Guidance), so to save yourself frustration in the future I highly recommend just buying an officially supported programmer. It's also nice when you can program and debug your microcontroller from within your IDE.

  • UDPI programmers have a Vcc pin that is used to sense supply voltage (but not provide it), so you must power your board yourself while using one of these new programmers.

Blinking a LED is the "Hello, World" of microcontroller programming. Let's take a look at the code necessary to blink a LED on pin 2 of an ATTiny286. It is compiled and programmed onto the chip using Microchip Studio.

#define F_CPU 3333333UL
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
    PORTA.DIR = 0xFF;
    while (1)
    {
        PORTA.OUT = 255;
        _delay_ms(500);
        PORTA.OUT = 0;
        _delay_ms(500);
    }
}
  • PORTA.DIR sets the direction of pins on port A (0xFF means all outputs)
  • PORTA.OUT sets output voltage on pins of port A (0xFF means all high)
  • Using _delay_ms() requires including delay.h
  • Including delay.h requires defining F_CPU (the CPU frequency)
  • The ATTiny286 datasheet section 11.3.3 indicates the default clock is 20 MHz with a /6 prescaler, so the default clock is 3333333 Hz (3.3 MHz). This behavior can be customized using the Oscillator Configuration Fuse (FUSE.OSCCFG).

ATTiny826 Pinout

From page 14 of the ATTiny826 datasheet

SMT ATTiny Breakout Board

Many of the newer AVR series microcontrollers are not available in breadboard-friendly DIP packages. I find SOIC-to-DIP breakout boards (available on Amazon and eBay) to be useful for experimenting with chips in SOIC packages. Here I added extra power and PA4 (pin 2) LEDs and 10 kΩ current limiting resistors.

I power the device from the 3.3V or 5V pins on a FT232 USB breakout board. Although the topic is out of scope for this article, I find it convenient to use FTDI chips to exchange small amounts of data or debug messages between a microcontroller and a modern PC over USB without requiring special drivers.

Why is programming modern AVRs so difficult?

I'm surprised how little information there is online about how to reliably program modern AVR series microcontrollers. In late 2022 there is a surprisingly large amount of "advice" on this topic which leads to dead ends and broken or abandoned projects. After looking into it for a while, here is my opinionated assessment. Mouser and Digikey have links to expensive programmers, and Amazon has links to similar items but reviews are littered with comments like "arrived bricked" and "can not program AVR series chips". DIY options typically involve abandoned (or soon-to-be abandoned?) GitHub repositories, or instructions for Arduino-related programming. I seek to consolidate and distill the most useful information onto this page, and I hope others will find it useful.

Atmel-ICE: Expensive but Effective

After using $5 ICSP programmers for the last decade I almost fell out of my chair when I saw Microchip's recommended entry-level programmer is over $180! Digikey sells a "basic" version without cables for $130, but that still seems crazy to me. Also, $50 for a ribbon cable?

I found a kit on Amazon that sells the programmer with a cable for $126. It was hard for me to press that buy button, but I figured the time I would save by having access to modern and exotic chips during the present global chip shortage would make it worth it. After a couple days of free Prime shipping, it arrived. It was smaller than I thought it would be from the product photos.

The cable that came with the device seemed a bit hacky at first, but I'm happy to have it. The female 2.54 mm socket is easy to insert breadboard jumpers into.

I'm glad this thing is idiot proof. The very first thing I did after unboxing this programmer was hook it up to my power supply rails using reverse polarity. I misread the pin diagram and confused the socket with the connector (they are mirror images of one another). This is an easy mistake to make though, so here's a picture of the correct orientation. Note the location of the tab on the side of the connector.

Atmel ICE Pinout Programming Connection
  • Black: GND
  • Red: Vcc - This line is used to sense power and not deliver it, so you are responsible for externally powering your board.
  • Blue: UPDI pin - Although a pull-up resistor on the UPDI pin is recommended, I did not find it was required to program my chip on the breadboard in this configuration.

The AVR Ice was easy to use with Microchip Studio. My programmer was detected immediately, a window popped-up and walked me through updating the firmware, and my LED was blinking in no time.

MPLAB Snap: Cheap and Convoluted

Did I really need to spend $126 for an AVR programmer? Amazon carries the MPLAB Snap for $34, but lots of reviews say it doesn't work. After easily getting the Atmel-ICE programmer up and running I thought it would be a similarly easy experience setting-up the MPLAB Snap for AVR UPDI programming, but boy was I wrong. Now that I know the steps to get this thing working it's not so bad, but the information here was only gathered after hours of frustration.

Here are the steps you can take to program modern AVR microcontrollers with UPDI using a MPLAB Snap:

Step 1: Setup MPLAB

  • The MPLAB Snap ships with obsolete firmware and must be re-flashed immediately upon receipt.

  • Microchip Studio's firmware upgrade tool does not actually work with the MPLAB Snap. It shows the board with version 0.00 software and it hangs (with several USB disconnect/reconnect sounds) if you try to upgrade it.

  • You can only re-flash the MPLAB Snap using the MPLAB X IDE. Download the 1.10 GB MPLAB setup executable and install the MPLAB IDE software which occupies a cool 9.83 GB.

Step 2: Re-Flash the Programmer

  • In the MPLAB IDE select Tools and select Hardware Tool Emergency Boot Firmware Recovery. At least this tool is helpful. It walks you through how to reset the device and program the latest firmware.

Step 3: Acknowledge Your Programmer is Defective

Defective may be a strong word, but let's just say the hardware was not designed to enable programming AVR chips using UPDI. Microchip Studio will detect the programmer but if you try to program an AVR you'll get a pop-up error message that provides surprisingly little useful information.

Atmel Studio was unable to start your debug session. Please verify device selection, interface settings, target power and connections to the target device. Look in the details section for more information. StatusCode: 131107 ModuleName: TCF (TCF command: Processes:launch failed.) An illegal configuration parameter was used. Debugger command Activate physical failed.

Step 4: Fix Your Programmer

The reason MPLAB Snap cannot program AVR microcontrollers is because the UPDI pin should be pulled high, but the MPLAB Snap comes from the factory with its UPDI pin pulled low with a 4.7 kΩ resistor to ground. You can try to overpower this resistor by adding a low value pull-up resistor to Vcc (1 kΩ worked for me on a breadboard), but the actual fix is to fire-up the soldering iron and remove that tiny surface-mount pull-down resistor labeled R48.

Have your glasses? R48 is here:

These photos were taken after I removed the resistor. I didn't use hot air. I just touched it a for a few seconds with a soldering iron and wiped it off then threw it away.

You don't need a microscope, but I'm glad I had one.

Step 5: Reflect

You can now program AVR microcontrollers using UPDI with your MPLAB Snap! Blink, LED, blink.

Can you believe this is the officially recommended action? According to the official Microchip Engineering Technical Note ETN #36: MPLAB Snap AVR Interface Modification

  • Symptom: Programming and debugging fails with AVR microcontroller devices that use the UPDI/PDI/TPI interfaces. MPLAB SNAP, Assembly #02-10381-R1 requires an external pull-up resistor for AVR microcontroller devices that use these interfaces.

  • Problem: AVR microcontroller devices that use the UPDI/PDI/TPI interfaces require the idle state of inactivity to be at a logic high level. Internally, the AVR devices have a weak (50-100K) pull-up resistor that attempts to keep the line high. An external and stronger pull-up resistor may be enough to mitigate this issue and bring voltages to acceptable VDD levels. In some cases, this may not be enough and the pull-down resistor that is part of the ICSP protocol can be removed for these AVR microcontroller applications.

  • Solution: If most of the applications are AVR-centric, consider removing the R48 resistor as shown below. This completely isolates any loading on the programming data line. Additionally, a pull-up resistor to VDD in the range of 1K to 10K should be used for robustness. Pin 4 of J4 is the TPGD data line used for ICSP interfaces and it also doubles as the DAT signal for UPDI/PDI and TPI interfaces. The pull-up resistor can be mounted directly from TVDD (J4-2) to TPGD/DAT (J4-4). Alternatively, the resistor can be mounted on the application side of the circuit for convenience.

I feel genuinely sorry for the Amazon sellers who are getting poor reviews because they sell this product. It really isn't their fault. I hope Google directs people here so that they can get their boards working and leave positive reviews that point more people to this issue.

UPDI Programming with a Serial Adapter

There is no official support for UPDI programming using a serial adapter, but it seems some people have figured out how to do it in some capacity. There was a promising pyupdi project, but it is now deprecated. At the time of writing the leading project aiming to enable UPDI programming without official hardware is pymcuprog, but its repository has a single commit dated two months ago and no activity since. Interestingly, that commit was made by buildmaster@microchip.com (an unverified email address), so it may not be fair to refer to it as an "unofficial" solution. The long term support of the pymcuprog project remains uncertain, but regardless let's take a closer look at how it works.

To build a programmer you just need a TTL USB serial adapter and a 1kΩ resistor. These are the steps I used to program a LED blink program using this strategy:

  • Use a generic FT232 breakout board to achieve a USB-controlled serial port on my breadboard.

  • Connect the programmer as shown with the RX pin directly to the UPDI pin of the microcontroller and the resistor between the RX and TX pins.

  • Ensure a modern version of Python is installed on your system

  • pip install pymcuprog

  • Use the device manager to identify the name of the COM port representing your programmer. In my case it's COM12.

  • I then interacted with the microcontroller by running pymcuprog from a terminal

Ping the Microcontroller

This command returns the device ID (1E9328 for my ATtiny826) indicating the UPDI connection is working successfully

pymcuprog ping -d attiny826 -t uart -u com12
Connecting to SerialUPDI
Pinging device...
Ping response: 1E9328

Write a Hex File

I used Microchip Studio to compile my C code and generate the hex file. Now I can use pymcuprog to load those hex files onto the chip. It's slower to program and inconvenient to drop to a terminal whenever I want to program a chip, but it works.

pymcuprog write -f LedBlink.hex -d attiny826 -t uart -u com12
Connecting to SerialUPDI
Pinging device...
Ping response: 1E9328
Writing from hex file...
Writing flash...

Conclusions

  • The new AVR series microcontrollers have lots of cool peripherals for the price and are available during a chip shortage that threatens availability of the more common traditional microcontrollers.

  • The Atmel-ICE is expensive, but the most convenient and reliable way to program modern AVR microcontrollers using UPDI.

  • The MPLAB Snap can program modern AVRs using UPDI after a software flash and a hardware modification, but its support for AVRs seems like an afterthought rather than its design priority.

  • You can create a makeshift unofficial UPDI programmer from a USB serial adapter, but the added complexity, lack of debugging capabilities, increased friction during the development loop, and large number of abandoned projects in this space make this an unappealing long term solution in my opinion.

Resources

Markdown source code last modified on December 25th, 2022
---
Title: Programming Modern AVR Microcontrollers
Description: Blink a LED on a modern series AVR using Atmel-ICS or MPLAB Snap UPDI programmers.
Date: 2022-12-09 11:45PM EST
Tags: circuit, microcontroller
---

# Programming Modern AVR Microcontrollers

**This page describes how to program Microchip's newest series of AVR microcontrollers using official programming gear and software.** I spent many years programming the traditional series of Atmel chips, but now several years after Microchip acquired Atmel I am interested in exploring the capabilities of the latest series of AVR microcontrollers (especially the new AVR DD family). Currently the global chip shortage makes it difficult to source traditional ATMega and STM32 chips, but the newest series of AVR microcontrollers feature an impressive set of peripherals for the price and are available from all the major vendors.

<div class="w-75 mx-auto">

![](https://www.youtube.com/embed/M-myqg-2c5s)

</div>

## TLDR

* Older AVR microcontrollers are programmed using _in-circuit serial programming_ (ICSP) through the `RESET`, `SCK`, `MISO`, and `MOSI` pins using cheap programmers like [USBtiny](https://learn.adafruit.com/usbtinyisp). However, serial programming is not supported on newer AVR microcontrollers.

* New AVR microcontrollers are programmed using the _unified program and debug interface_ (UDPI) exclusively through the `UDPI` pin. UDPI is a Microchip proprietary interface requiring a UDPI-capable programmer.

* Official UDPI programmers include [Atmel-ICE](https://www.digikey.com/en/products/detail/microchip-technology/ATATMEL-ICE-BASIC/4753381) ($129) and [MPLAB Snap](https://www.digikey.com/en/products/detail/microchip-technology/PG164100/9562532) ($35). The Atmel-ICE is expensive but it is very well supported. The MPLAB Snap is hacky, requires re-flashing, and has a physical design flaw requiring a hardware modification before it can program AVR series chips.

* There are notable attempts to create alternative programmers (e.g., [jtag2updi](https://github.com/ElTangas/jtag2updi) and [pymcuprog](https://github.com/microchip-pic-avr-tools/pymcuprog)), but this journey into the land of unofficial programmer designs is fraught with abandoned GitHub repositories and a lot of added complexity and brittleness (e.g., [SpenceKonde/AVR-Guidance](https://github.com/SpenceKonde/AVR-Guidance/blob/master/UPDI/jtag2updi.md)), so to save yourself frustration in the future I highly recommend just buying an officially supported programmer. It's also nice when you can program and debug your microcontroller from within your IDE.

* UDPI programmers have a `Vcc` pin that is used to _sense_ supply voltage (but not provide it), so you must power your board yourself while using one of these new programmers.

## ATTiny826 LED Blink

**Blinking a LED is the "Hello, World" of microcontroller programming.** Let's take a look at the code necessary to blink a LED on pin 2 of an [ATTiny286](https://ww1.microchip.com/downloads/en/DeviceDoc/ATtiny424-426-427-824-826-827-DataSheet-DS40002311A.pdf). It is compiled and programmed onto the chip using [Microchip Studio](https://www.microchip.com/en-us/tools-resources/develop/microchip-studio).

```c
#define F_CPU 3333333UL
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
	PORTA.DIR = 0xFF;
	while (1)
	{
		PORTA.OUT = 255;
		_delay_ms(500);
		PORTA.OUT = 0;
		_delay_ms(500);
	}
}
```

* `PORTA.DIR` sets the direction of pins on port A (`0xFF` means all outputs)
* `PORTA.OUT` sets output voltage on pins of port A (`0xFF` means all high)
* Using `_delay_ms()` requires including `delay.h`
* Including `delay.h` requires defining `F_CPU` (the CPU frequency)
* The [ATTiny286 datasheet section 11.3.3](https://ww1.microchip.com/downloads/en/DeviceDoc/ATtiny424-426-427-824-826-827-DataSheet-DS40002311A.pdf) indicates the default clock is 20 MHz with a /6 prescaler, so the default clock is `3333333 Hz` (3.3 MHz). This behavior can be customized using the Oscillator Configuration Fuse (FUSE.OSCCFG).

## ATTiny826 Pinout

From page 14 of the [ATTiny826 datasheet](https://ww1.microchip.com/downloads/en/DeviceDoc/ATtiny424-426-427-824-826-827-DataSheet-DS40002311A.pdf)

<img src="attiny826-pinout.png" class="img-fluid mx-auto d-block w-75" />

## SMT ATTiny Breakout Board

**Many of the newer AVR series microcontrollers are not available in breadboard-friendly DIP packages.** I find SOIC-to-DIP breakout boards (available on Amazon and eBay) to be useful for experimenting with chips in SOIC packages. Here I added extra power and PA4 (pin 2) LEDs and 10 kΩ current limiting resistors.

<a href="photos/leds2.jpg">
<img src="photos/leds2.jpg" class="img-fluid border shadow my-4" />
</a>

<a href="photos/scope1.jpg">
<img src="photos/scope1.jpg" class="img-fluid border shadow my-4" />
</a>

**I power the device from the 3.3V or 5V pins on a FT232 USB breakout board.** Although the topic is out of scope for this article, I find it convenient to use FTDI chips to exchange small amounts of data or debug messages between a microcontroller and a modern PC over USB without requiring special drivers.

<img src="ft232-breadboard.jpg" class="img-fluid mx-auto d-block w-50" />

## Why is programming modern AVRs so difficult?

**I'm surprised how little information there is online about how to _reliably_ program modern AVR series microcontrollers.** In late 2022 there is a surprisingly large amount of "advice" on this topic which leads to dead ends and broken or abandoned projects. After looking into it for a while, here is my opinionated assessment. Mouser and Digikey have links to expensive programmers, and Amazon has links to similar items but reviews are littered with comments like "arrived bricked" and "can not program AVR series chips". DIY options typically involve abandoned (or soon-to-be abandoned?) GitHub repositories, or instructions for Arduino-related programming. I seek to consolidate and distill the most useful information onto this page, and I hope others will find it useful.

## Atmel-ICE: Expensive but Effective

**After using $5 ICSP programmers for the last decade I almost fell out of my chair when I saw Microchip's recommended entry-level programmer is over $180!** Digikey sells a "basic" version without cables for $130, but that still seems crazy to me. Also, $50 for a ribbon cable?

<a href="avr-ice.webp">
<img src="avr-ice.webp" class="img-fluid w-50 d-block mx-auto my-5" />
</a>

**I found a kit on Amazon that sells the programmer with a cable for $126.** It was hard for me to press that buy button, but I figured the time I would save by having access to modern and exotic chips during the present global chip shortage would make it worth it. After a couple days of free Prime shipping, it arrived. It was smaller than I thought it would be from the product photos.

<a href="photos/atmel-ice-1.jpg">
<img src="photos/atmel-ice-1.jpg" class="img-fluid border shadow my-4" />
</a>

**The cable that came with the device seemed a bit hacky at first, but I'm happy to have it.** The female 2.54 mm socket is easy to insert breadboard jumpers into.

<a href="photos/atmel-ice-2.jpg">
<img src="photos/atmel-ice-2.jpg" class="img-fluid border shadow my-4" />
</a>

**I'm glad this thing is idiot proof.** The very first thing I did after unboxing this programmer was hook it up to my power supply rails using reverse polarity. I misread the pin diagram and confused the _socket_ with the _connector_ (they are mirror images of one another). This is an easy mistake to make though, so here's a picture of the correct orientation. Note the location of the tab on the side of the connector.

Atmel ICE Pinout | Programming Connection
---|---
<a href="atmel-ice-pinout.png"><img src="atmel-ice-pinout.png" class="img-fluid"></a>|<a href="photos/atmel-ice-3.jpg"><img src="photos/atmel-ice-3.jpg" class="img-fluid"></a>

* Black: `GND`
* Red: `Vcc` - This line is used to _sense_ power and not _deliver_ it, so you are responsible for externally powering your board.
* Blue: `UPDI` pin - Although a pull-up resistor on the UPDI pin is recommended, I did not find it was required to program my chip on the breadboard in this configuration.

**The AVR Ice was easy to use with Microchip Studio.** My programmer was detected immediately, a window popped-up and walked me through updating the firmware, and my LED was blinking in no time.

<a href="photos/atmel-ice-4.jpg">
<img src="photos/atmel-ice-4.jpg" class="img-fluid border shadow my-4" />
</a>

## MPLAB Snap: Cheap and Convoluted

**Did I really need to spend $126 for an AVR programmer? Amazon carries the MPLAB Snap for $34, but lots of reviews say it doesn't work.** After easily getting the Atmel-ICE programmer up and running I thought it would be a similarly easy experience setting-up the MPLAB Snap for AVR UPDI programming, but boy was I wrong. Now that I know the steps to get this thing working it's not so bad, but the information here was only gathered after hours of frustration. 

<a href="mplab-snap.webp">
<img src="mplab-snap.webp" class="img-fluid d-block mx-auto w-75" />
</a>

<a href="photos/mplab-snap-1.jpg">
<img src="photos/mplab-snap-1.jpg" class="img-fluid border shadow my-4" />
</a>

Here are the steps you can take to program modern AVR microcontrollers with UPDI using a MPLAB Snap:

### Step 1: Setup MPLAB

* The MPLAB Snap ships with obsolete firmware and must be re-flashed immediately upon receipt.

* Microchip Studio's firmware upgrade tool does not actually work with the MPLAB Snap. It shows the board with version 0.00 software and it hangs (with several USB disconnect/reconnect sounds) if you try to upgrade it.

* You can only re-flash the MPLAB Snap using the MPLAB X IDE. Download the 1.10 GB [MPLAB setup](https://www.microchip.com/en-us/tools-resources/develop/mplab-x-ide) executable and install the MPLAB IDE software which occupies a cool 9.83 GB.

### Step 2: Re-Flash the Programmer

* In the MPLAB IDE select `Tools` and select `Hardware Tool Emergency Boot Firmware Recovery`. At least this tool is helpful. It walks you through how to reset the device and program the latest firmware.

### Step 3: Acknowledge Your Programmer is Defective

Defective may be a strong word, but let's just say the hardware was not designed to enable programming AVR chips using UPDI. Microchip Studio will detect the programmer but if you try to program an AVR you'll get a pop-up error message that provides surprisingly little useful information.

<img src="verify.png" class="mx-auto d-block img-fluid" />

> Atmel Studio was unable to start your debug session. Please verify device selection, interface settings, target power and connections to the target device. Look in the details section for more information.
> StatusCode:	131107
> ModuleName:	TCF (TCF command: Processes:launch failed.)
> An illegal configuration parameter was used. Debugger command Activate physical failed.

### Step 4: Fix Your Programmer

**The reason MPLAB Snap cannot program AVR microcontrollers is because the UPDI pin should be pulled _high_, but the MPLAB Snap comes from the factory with its UPDI pin pulled _low_ with a 4.7 kΩ resistor to ground.** You can try to overpower this resistor by adding a low value pull-up resistor to Vcc (1 kΩ worked for me on a breadboard), but the actual fix is to fire-up the soldering iron and remove that tiny surface-mount pull-down resistor labeled `R48`.

Have your glasses? R48 is here:

<a href="photos/mplab-snap-fix.jpg">
<img src="photos/mplab-snap-fix.jpg" class="img-fluid border shadow my-4" />
</a>


**These photos were taken after I removed the resistor.** I didn't use hot air. I just touched it a for a few seconds with a soldering iron and wiped it off then threw it away.

<a href="photos/scope2.jpg">
<img src="photos/scope2.jpg" class="img-fluid border shadow my-4" />
</a>

You don't need a microscope, but I'm glad I had one.

### Step 5: Reflect

You can now program AVR microcontrollers using UPDI with your MPLAB Snap! Blink, LED, blink.

<a href="photos/mplab-snap-2.jpg">
<img src="photos/mplab-snap-2.jpg" class="img-fluid border shadow my-4" />
</a>

**Can you believe this is the officially recommended action?** According to the official Microchip Engineering Technical Note [ETN #36](http://ww1.microchip.com/downloads/en/DeviceDoc/ETN36_MPLAB%20Snap%20AVR%20Interface%20Modification.pdf): MPLAB Snap AVR Interface Modification

* **Symptom:** Programming and debugging fails with AVR microcontroller devices that use the UPDI/PDI/TPI interfaces. MPLAB SNAP, Assembly #02-10381-R1 requires an external pull-up resistor for AVR microcontroller
devices that use these interfaces.

* **Problem:** AVR microcontroller devices that use the UPDI/PDI/TPI interfaces require the idle state of inactivity to be at a logic high level. Internally, the AVR devices have a weak (50-100K) pull-up resistor that attempts to keep the line high. An external and stronger pull-up resistor may be enough to mitigate this issue and bring voltages to acceptable VDD levels. In some cases, this may not be enough and the pull-down resistor that is part of the ICSP protocol can be removed for these AVR microcontroller applications.

* **Solution:** If most of the applications are AVR-centric, consider removing the R48 resistor as shown below. This completely isolates any loading on the programming data line. Additionally, a pull-up resistor to VDD in the range of 1K to 10K should be used for robustness. Pin 4 of J4 is the TPGD data line used for ICSP interfaces and it also doubles as the DAT signal for UPDI/PDI and TPI interfaces. The pull-up resistor can be mounted directly from TVDD (J4-2) to TPGD/DAT (J4-4). Alternatively, the resistor can be mounted on the application side of the circuit
for convenience.

**I feel genuinely sorry for the Amazon sellers who are getting poor reviews because they sell this product.** It really isn't their fault. I hope Google directs people here so that they can get their boards working and leave positive reviews that point more people to this issue.

## UPDI Programming with a Serial Adapter

There is no official support for UPDI programming using a serial adapter, but it seems some people have figured out how to do it in some capacity. There was a promising [pyupdi](https://github.com/mraardvark/pyupdi) project, but it is now deprecated. At the time of writing the leading project aiming to enable UPDI programming without official hardware is [pymcuprog](https://github.com/microchip-pic-avr-tools/pymcuprog), but its repository has a single commit dated two months ago and no activity since. Interestingly, [that commit](https://github.com/microchip-pic-avr-tools/pymcuprog/commit/593afdc8e089e39a4fed9f4fb19ae81f5f51e9a5.patch) was made by buildmaster@microchip.com (an unverified email address), so it may not be fair to refer to it as an "unofficial" solution. The long term support of the pymcuprog project remains uncertain, but regardless let's take a closer look at how it works.

![](updi-ftdi-serial-programmer.png)

To build a programmer you just need a TTL USB serial adapter and a 1kΩ resistor. These are the steps I used to program a LED blink program using this strategy:

* Use a generic [FT232 breakout board](https://www.amazon.com/s?k=ft232+breakout) to achieve a USB-controlled serial port on my breadboard.

* Connect the programmer as shown with the RX pin directly to the UPDI pin of the microcontroller and the resistor between the RX and TX pins.

* Ensure a [modern version of Python](https://www.python.org/) is installed on your system

* `pip install pymcuprog`

* Use the device manager to identify the name of the COM port representing your programmer. In my case it's `COM12`.

* I then interacted with the microcontroller by running `pymcuprog` from a terminal

### Ping the Microcontroller

This command returns the device ID (1E9328 for my ATtiny826) indicating the UPDI connection is working successfully

```bash
pymcuprog ping -d attiny826 -t uart -u com12
```

```
Connecting to SerialUPDI
Pinging device...
Ping response: 1E9328
```

### Write a Hex File

I used Microchip Studio to compile my C code and generate the hex file. Now I can use `pymcuprog` to load those hex files onto the chip. It's slower to program and inconvenient to drop to a terminal whenever I want to program a chip, but it works.

```
pymcuprog write -f LedBlink.hex -d attiny826 -t uart -u com12
```

```
Connecting to SerialUPDI
Pinging device...
Ping response: 1E9328
Writing from hex file...
Writing flash...
```

## Conclusions

* The new AVR series microcontrollers have lots of cool peripherals for the price and are available during a chip shortage that threatens availability of the more common traditional microcontrollers.

* The Atmel-ICE is expensive, but the most convenient and reliable way to program modern AVR microcontrollers using UPDI.

* The MPLAB Snap can program modern AVRs using UPDI after a software flash and a hardware modification, but its support for AVRs seems like an afterthought rather than its design priority.

* You can create a makeshift unofficial UPDI programmer from a USB serial adapter, but the added complexity, lack of debugging capabilities, increased friction during the development loop, and large number of abandoned projects in this space make this an unappealing long term solution in my opinion.

## Resources

* Atmel-ICE
  * [Atmel-ICE on Mouser](https://www.mouser.com/ProductDetail/Microchip-Technology-Atmel/ATATMEL-ICE?qs=sGAEpiMZZMuRZxwUfDU0miN4udwF8GpUanrVt%252BDSn9Q4SZQ5wSGB4Q%3D%3D) (currently $180.64)
  * [Atmel-ICE on DigiKey](https://www.digikey.com/en/products/detail/microchip-technology/ATATMEL-ICE/4753379) (currently $180.62)
  * [Atmel-ICE on Amazon](https://www.amazon.com/s?k=atmel+ice) (currently $126.49)
  * [Atmel-ICE on eBay](https://www.ebay.com/sch/i.html?_nkw=atmel-ice) (currently $135.00)
  * [Atmel-ICE datasheet](https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-ICE_UserGuide.pdf)
* MPLAB Snap
  * [MPLAB Snap on Mouser](https://www.mouser.com/ProductDetail/Microchip-Technology-Atmel/PG164100?qs=w%2Fv1CP2dgqoaLDDBjfzhMQ%3D%3D) (currently $34.77)
  * [MPLAB Snap on DigiKey](https://www.digikey.com/en/products/detail/microchip-technology/PG164100/9562532) (currently $34.76)
  * [MPLAB Snap on Amazon](https://www.amazon.com/s?k=mplab+snap) (currently $34.09)
  * [MPLAB Snap datasheet](https://ww1.microchip.com/downloads/en/DeviceDoc/50002787C.pdf)
  * [MPLAB Snap AVR UPDI modification](http://ww1.microchip.com/downloads/en/DeviceDoc/ETN36_MPLAB%20Snap%20AVR%20Interface%20Modification.pdf)
* [ATTiny826 datasheet](https://ww1.microchip.com/downloads/en/DeviceDoc/ATtiny424-426-427-824-826-827-DataSheet-DS40002311A.pdf)
* [UPDI Physical Interface](https://onlinedocs.microchip.com/pr/GUID-DDB0017E-84E3-4E77-AAE9-7AC4290E5E8B-en-US-4/index.html)
* [Contact me](https://swharden.com/about/) if you have suggestions or updated information
November 15th, 2022

Interfacing HX710 Differential ADC with Arduino

This page demonstrates how to read differential voltage from a HX710 ADC using Arduino. I recently obtained some pressure sensor boards from Amazon for less than $3 each under names like 6pcs 3.3-5V Digital Barometric Air Pressure Sensor Module Liquid Water Level Controller Board 0-40KPa that use this ADC. Several years ago I worked on a precision pressure meter project based on an I2C temperature and pressure sensor (MS5611), and now that I see new inexpensive SPI pressure sensor modules on the consumer market I'm interested to learn more about their capabilities.

Analog-to-Digital Converter IC

The ADC chip is easily identified as a HX710B 24-Bit Analog-to-Digital Converter (ADC) with Built-in Temperature Sensor. According to the datasheet it can be powered by a 3.3V or 5V supply, and the value it reports is the differential voltage between two input pins.

The datasheet indicates this device can be run from a 3.3V or 5V supply, it uses a built-in fixed-gain (128x) differential amplifier, and it can read up to 40 samples per second. The datasheet provides an example circuit demonstrating how this ADC can be used to measure weight from a scale sensor:

Pressure Sensor

To get a better idea of how this sensor works it would be helpful to locate its product number. I had a hunch it was beneath the part so I desoldered it, and indeed I found part identification information.

The pressure sensor is labeled as a PSG010S but unfortunately I struggled to find a quality datasheet for it. I did find some now-deleted images from an AliExpress listing showing the differences between the base model and the R and S variants. I found this PSG010R datasheet (curiously written in Comic Sans) indicating that maximum voltage is 5V and that the gauge pressure is 0 - 40KPa (0 - 5.8 PSI). This seems to be a fairly standard differential pressure sensor design using a pair of voltage dividers where the pressure is a function of the difference in voltage at the two mid-points (a Wheatstone bridge).

Update (2022-12-23): I received an email from somebody offering additional information about this component:

The PSG010 reports positive and negative pressures and can easily have its range shifted to almost double in one direction with almost none in the other. All that is needed is to lift the +V (2) or ground pin (5) and insert a surface mount 75R ±15R under it. Lifting the ground side by 75R makes it double positive, while pushing the applied +V down makes it double negative (vacuum).
-- bruceg

Read HX710B with Arduino

This code demonstrates how to measure HX710B values using Arduino and display the readings in the serial terminal sufficient to graph in real time using the serial plotter. The animated plot is what it looks like when I blow puffs of air on the sensor.

const int HX_OUT_PIN = 2;
const int HX_SCK_PIN = 3;

enum HX_MODE { NONE, DIFF_10Hz, TEMP_40Hz, DIFF_40Hz};
const byte HX_MODE = DIFF_40Hz;

void setup() {
  pinMode(HX_SCK_PIN, OUTPUT);
  pinMode(HX_OUT_PIN, INPUT);
  Serial.begin(9600);
}

void loop() {
  Serial.println(readHX());
}

unsigned long readHX() {

  // pulse clock line to start a reading
  for (char i = 0; i < HX_MODE; i++) {
    digitalWrite(HX_SCK_PIN, HIGH);
    digitalWrite(HX_SCK_PIN, LOW);
  }

  // wait for the reading to finish
  while (digitalRead(HX_OUT_PIN)) {}

  // read the 24-bit pressure as 3 bytes using SPI
  byte data[3];
  for (byte j = 3; j--;) {
    data[j] = shiftIn(HX_OUT_PIN, HX_SCK_PIN, MSBFIRST);
  }

  data[2] ^= 0x80;  // see note

  // shift the 3 bytes into a large integer
  long result;
  result += (long)data[2] << 16;
  result += (long)data[1] << 8;
  result += (long)data[0];

  return result;
}

Note: This code flips the most significant bit of the sensor reading. The sensor always returns this bit as 1, except for the case of an out-of-range error (see excerpt from datasheet below). By simply flipping the bit our reported values are a continuous range from 0 to 2^14-1, with the edge values representing out-of-range errors.

The output 24 bits of data is in 2’s complement format. When input differential signal goes out of the 24 bit range, the output data will be saturated at 0x800000 (MIN) or 0x7FFFFF (MAX) until the input signal comes back to the input range.
-- HX710 datasheet

Update (2022-12-23): I received an email from someone offering feedback about this code:

This code works in a loop, but perhaps by accident. The strongly worded statements in the HX710 datasheet about 25 - 27 clocks per readout imply that it is risky to rely on this. It may be that hanging clocks induce unwanted sleep modes or over-run into the next read cycle, etc. There is simply no real explanation in what is shown, so best to be safe - always set the next mode immediately AFTER collecting a reading and then always poll for new data ready before attempting a collection. Your 'pulse clock line to start a reading' loop before a reading should be 'add next mode' after a reading to comply with the timing specification. This will ensure that the next conversion will be available rather than the next scheduled conversion AFTER the mode is eventually sent.
-- bruceg

Open-Source HX710B Libraries

Although some libraries are available which facilitate interacting with the HX710, here I engage with it discretely to convey each step of the conversion and measurement process. I found that many libraries use the 10 Hz mode by default, whereas I certainly prefer the 40 Hz mode. More frustratingly, code in many libraries refer to this as gain, which is incorrect. The datasheet indicates gain is fixed at 128 and cannot be changed in software.

Update (2022-12-23): I received an email explaining why people often use "gain" and "mode" when referring to the HX710:

The HX711 is similar to the HX710 but it has user selectable gain AND user selectable sample rates BUT only certain combinations are allowed, so setting mode WILL also select its matched gain value. The HX710 uses most of the same internals, but with just 3 modes - reading the Wheatstone Bridge always using 128 gain at 10 or 40Hz while swapping to Avolt (HX710A) or internal Temperature (HX710B) uses a lower gain and less digits. So for people familiar with the HX711 there is no ambiguity in mixing mode and gain.
-- bruceg

Resources

Markdown source code last modified on December 24th, 2022
---
Title: Interfacing HX710 Differential ADC with Arduino
Description: How to read differential voltage from a HX710 ADC using Arduino
Date: 2022-11-15 12:30AM EST
Tags: circuit, microcontroller
---

# Interfacing HX710 Differential ADC with Arduino

**This page demonstrates how to read differential voltage from a HX710 ADC using Arduino.** I recently obtained some pressure sensor boards from Amazon for less than $3 each under names like _6pcs 3.3-5V Digital Barometric Air Pressure Sensor Module Liquid Water Level Controller Board 0-40KPa_ that use this ADC. Several years ago I worked on a [precision pressure meter project](https://swharden.com/blog/2017-04-29-precision-pressure-meter-project/) based on an [I2C](https://en.wikipedia.org/wiki/I%C2%B2C)  temperature and pressure sensor ([MS5611](https://www.te.com/commerce/DocumentDelivery/DDEController?Action=showdoc&DocId=Data+Sheet%7FMS5611-01BA03%7FB3%7Fpdf%7FEnglish%7FENG_DS_MS5611-01BA03_B3.pdf%7FCAT-BLPS0036)), and now that I see new inexpensive [SPI](https://en.wikipedia.org/wiki/Serial_Peripheral_Interface) pressure sensor modules on the consumer market I'm interested to learn more about their capabilities.

<img src="hx710b-pressure-board.jpg" class="my-5 border border-dark shadow img-fluid w-75 mx-auto d-block">

## Analog-to-Digital Converter IC

**The ADC chip is easily identified as a [HX710B](https://www.electronicscomp.com/datasheet/hx710b-ic-datasheet.pdf) _24-Bit Analog-to-Digital Converter (ADC) with Built-in Temperature Sensor_.** According to the datasheet it can be powered by a 3.3V or 5V supply, and the value it reports is the differential voltage between two input pins. 

<img src="hx710b-pinout.jpg" class="my-5 img-fluid w-75 mx-auto d-block">

The datasheet indicates this device can be run from a 3.3V or 5V supply, it uses a built-in fixed-gain (128x) differential amplifier, and it can read up to 40 samples per second. The datasheet provides an example circuit demonstrating how this ADC can be used to measure weight from a scale sensor:

<img src="hx710-datasheet.jpg" class="my-5 img-fluid w-75 mx-auto d-block">

## Pressure Sensor

To get a better idea of how this sensor works it would be helpful to locate its product number. I had a hunch it was beneath the part so I desoldered it, and indeed I found part identification information.

<img src="hx710b-pressure-psg010s.jpg" class="my-5 border border-dark shadow img-fluid w-75 mx-auto d-block">

**The pressure sensor is labeled as a PSG010S** but unfortunately I struggled to find a quality datasheet for it. I did find some now-deleted images from an AliExpress listing showing the differences between the base model and the R and S variants. 
I found [this PSG010R datasheet](https://www.katranji.com/tocimages/files/536845-544144.pdf) (curiously written in Comic Sans) indicating that maximum voltage is 5V and that the gauge pressure is 0 - 40KPa (0 - 5.8 PSI). This seems to be a fairly standard [differential pressure sensor](https://www.avnet.com/wps/portal/abacus/solutions/technologies/sensors/pressure-sensors/measurement-types/differential/) design using a pair of voltage dividers where the pressure is a function of the difference in voltage at the two mid-points (a [Wheatstone bridge](https://en.wikipedia.org/wiki/Wheatstone_bridge)).

**Update (2022-12-23):** I received an email from somebody offering additional information about this component:

> The PSG010 reports positive and negative pressures and can easily have its range shifted to almost double in one direction with almost none in the other.  All that is needed is to lift the +V (2) or ground pin (5) and insert a surface mount 75R ±15R under it. 
Lifting the ground side by 75R makes it double positive, while pushing the applied +V down makes it double negative (vacuum).<br>
> -- <cite class="text-end">bruceg</cite>


<img src="psg-pressure-sensor.jpg" class="my-5 border border-dark shadow img-fluid w-75 mx-auto d-block">

## Read HX710B with Arduino

**This code demonstrates how to measure HX710B values using Arduino** and display the readings in the serial terminal sufficient to graph in real time using the serial plotter. The animated plot is what it looks like when I blow puffs of air on the sensor.

<img src="hx710-arduino-plot.gif" class="my-5 img-fluid mx-auto d-block">

```c
const int HX_OUT_PIN = 2;
const int HX_SCK_PIN = 3;

enum HX_MODE { NONE, DIFF_10Hz, TEMP_40Hz, DIFF_40Hz};
const byte HX_MODE = DIFF_40Hz;

void setup() {
  pinMode(HX_SCK_PIN, OUTPUT);
  pinMode(HX_OUT_PIN, INPUT);
  Serial.begin(9600);
}

void loop() {
  Serial.println(readHX());
}

unsigned long readHX() {

  // pulse clock line to start a reading
  for (char i = 0; i < HX_MODE; i++) {
    digitalWrite(HX_SCK_PIN, HIGH);
    digitalWrite(HX_SCK_PIN, LOW);
  }

  // wait for the reading to finish
  while (digitalRead(HX_OUT_PIN)) {}

  // read the 24-bit pressure as 3 bytes using SPI
  byte data[3];
  for (byte j = 3; j--;) {
    data[j] = shiftIn(HX_OUT_PIN, HX_SCK_PIN, MSBFIRST);
  }
  
  data[2] ^= 0x80;  // see note

  // shift the 3 bytes into a large integer
  long result;
  result += (long)data[2] << 16;
  result += (long)data[1] << 8;
  result += (long)data[0];

  return result;
}
```

**Note: This code flips the most significant bit of the sensor reading.** The sensor always returns this bit as `1`, except for the case of an out-of-range error (see excerpt from datasheet below). By simply flipping the bit our reported values are a continuous range from `0` to `2^14-1`, with the edge values representing out-of-range errors.

> The output 24 bits of data is in [2’s complement format](https://en.wikipedia.org/wiki/Two%27s_complement).
> When input differential signal goes out of the 24 bit range, the output data will be saturated at `0x800000` (MIN) or `0x7FFFFF` (MAX)
> until the input signal comes back to the input range.<br>
> -- <cite class="text-end"><a href='https://www.electronicscomp.com/datasheet/hx710b-ic-datasheet.pdf'>HX710 datasheet</a></cite>

**Update (2022-12-23):** I received an email from someone offering feedback about this code:

> This code works in a loop, but perhaps by accident. The strongly worded statements in the [HX710 datasheet](https://www.electronicscomp.com/datasheet/hx710b-ic-datasheet.pdf) about 25 - 27 clocks per readout imply that it is risky to rely on this.  It may be that hanging clocks induce unwanted sleep modes or over-run into the next read cycle, etc.  There is simply no real explanation in what is shown, so best to be safe - always set the next mode immediately AFTER collecting a reading and then always poll for new data ready before attempting a collection. Your 'pulse clock line to start a reading' loop before a reading should be 'add next mode' after a reading to comply with the timing specification.  This will ensure that the next conversion will be available rather than the next scheduled conversion AFTER the mode is eventually sent.<br>
> -- <cite class="text-end">bruceg</cite>

## Open-Source HX710B Libraries

Although some libraries are available which facilitate interacting with the HX710, here I engage with it discretely to convey each step of the conversion and measurement process. I found that many libraries use the 10 Hz mode by default, whereas I certainly prefer the 40 Hz mode. More frustratingly, code in many libraries refer to this as _gain_, which is incorrect. The datasheet indicates gain is fixed at 128 and cannot be changed in software.

**Update (2022-12-23):** I received an email explaining why people often use "gain" and "mode" when referring to the HX710:

> The [HX711](https://www.digikey.com/htmldatasheets/production/1836471/0/0/1/HX711.pdf) is similar to the [HX710](https://www.electronicscomp.com/datasheet/hx710b-ic-datasheet.pdf) but it has user selectable gain AND user selectable sample rates BUT only certain combinations are allowed, so setting mode WILL also select its matched gain value.
The HX710 uses most of the same internals, but with just 3 modes - reading the Wheatstone Bridge always using 128 gain at 10 or 40Hz while swapping to Avolt (HX710A) or internal Temperature (HX710B) uses a lower gain and less digits. So for people familiar with the HX711 there is no ambiguity in mixing mode and gain.<br>
> -- <cite class="text-end">bruceg</cite>

## Resources

* [Pressure Sensor Guide](https://www.electroschematics.com/pressure-sensor-guide/) by T.K. HAREENDRAN - A similar write-up that goes into additional detail. They didn't de-solder the pressure sensor to identify the component name, but there's lots of good information on this page.

* [bogde/HX711 on GitHub](https://github.com/bogde/HX711) - An Arduino library to interface the Avia Semiconductor HX711 24-Bit Analog-to-Digital Converter (ADC) for reading load cells / weight scales. Code on this page does not use this library, but others may find it helpful.

* [HX710 datasheet (English)](https://www.electronicscomp.com/datasheet/hx710b-ic-datasheet.pdf)

* [Differential pressure sensors](https://www.avnet.com/wps/portal/abacus/solutions/technologies/sensors/pressure-sensors/measurement-types/differential/) - Article about the topic which includes a good example of an instrumentation amplifier.

* [Design tips for a resistive-bridge pressure sensor in industrial process-control systems](https://www.ti.com/lit/an/slyt640/slyt640.pdf) - Texas Instruments application note

* [The Wheatstone Bridge](https://meritsensor.com/the-wheatstone-bridge/) by Michael Daily
June 3rd, 2018

Bit-Bang FTDI USB-to-Serial Converters to Drive SPI Devices

The FT232 USB-to-serial converter is one of the most commonly-used methods of adding USB functionality to small projects, but recently I found that these chips are capable of sending more than just serial signals. With some creative programming, individual output pins can be big-banged to emulate a clock, data, and chip select line to control SPI devices. This post shares some of the techniques I use to bit-bang SPI with FTDI devices, and some of the perks (and quirks) of using FTDI chips to bit-bang data from a USB port. Code examples are available on GitHub, and links to additional resources are at the bottom of this post. After the final build I created a slightly more polished "ftdiDDS.exe" program to control an AD9850 frequency synthesizer from the command line by bit-banging a FT-232, and code (and binaries) are also available on GitHub.

Why Bit-Bang FTDI Pins?

The main reason I like using FTDI devices is because when you plug them in to a modern computer, they just start working! You don't have to worry about drivers, driver versions, driver signing, third party drivers - most of the time it just does what it's supposed to do with no complexity. If I'm going to build a prototype device for a client, a FT-232 USB to serial converter is the way to go because I can be confident that when they plug in, their device will start working right away. Yeah, there are third party drivers to get extra open-sourcey functionality from FTDI devices (libFTDI), but I don't want to ask a client (with unknown tech-savviness) to install third-party unsigned drivers before plugging my device in (and heaven forbid the product doesn't work in their hands and I have to ask them to verify the device is actually using the third-party drivers and not defaulting back to the official ones). In this project I seek to use only the generic, default, officially-supported FTDI driver and API access will be provided by libftd2xx. Don't forget that USB ports supply 5V and GND, so in most cases you can power your project just from the USB port! All-in-all, the FT-232 is a great way to give a small device USB functionality. This post explores how to use it for more than just sending and receiving serial data...

FT-232R Breakout Board

FT-232H Breakout Board

TTL-FT232R Cable

Controlling FTDI Devices with C#

The goal of this post is not to describe every detail about how to control FTDI chips. Instead, the key points of the software are described here (and in the video) so you can get the gist of the main concepts. If you're interested in additional detail, full code examples are provided on the GitHub folder for this project. All code examples were tested with Visual Studio Community 2017, are written in C#, and uses the FTD2XX_NET library installed with NuGet. Also, see the list of resources (including official FTDI datasheets and application notes) at the bottom of this post.

This block of code attaches to FTDI device 0 (the first FTDI device it sees) and sends the letter "a" using a traditional serial protocol. Since this code connects to the first FTDI device it finds, this could be a problem if you have more than 1 FTDI device attached. Alternatively you could have your program connect to a specific FTDI device (e.g., by its serial number). To see what FTDI devices are attached to your computer (and see or set their serial numbers), use the FT_Prog application provided by FTDI. Also, see the code I use to list FTDI devices from inside a C# program ftdiDDS program.

Full code is on GitHub

public static FTDI ftdi = new FTDI();
public static FTDI.FT_STATUS ft_status = FTDI.FT_STATUS.FT_OK;
public static UInt32 bytesWritten = 0;

static void Main(string[] args)
{
    ft_status = ftdi.OpenByIndex(0);
    ft_status = ftdi.SetBaudRate(9600);
    string data = "a";
    ft_status = ftdi.Write(data, data.Length, ref bytesWritten);
}

LED Blink by Bit-Banging FTDI Pins

Here is a minimal complexity LED blink example. This code block alternates between writing 0 (all pins off) and 1 (TX pin high) over and over forever. Note that ftdi.SetBitMode is what frees the FTDI chip from sending serial data when ftdi.Write() gets called. The 255 is a byte mask which tells all 8 pins to be outputs (by setting all 8 bits in the byte to 1, hence 255). Setting bit mode to 1 means we are using asynchronous bit bang bode (sufficient if we don't intend to read any pin states). For full details about these (and other) bit-bang settings, check out the Bit Bang Modes for the FT232R application note.

Full code is on GitHub

ft_status = ftdi.OpenByIndex(0);
ft_status = ftdi.SetBitMode(255, 1);
ft_status = ftdi.SetBaudRate(9600);
int count = 0;

while (true)
{
    byte[] data = { (byte)(count++%2) };
    ft_status = ftdi.Write(data, data.Length, ref bytesWritten);
    System.Threading.Thread.Sleep(100);
}

Bit-Bang SPI with a FT232

In reality all we want to send to SPI devices are a series of numbers which we can place in a byte array. These numbers are transmitted by pulling-low a clip select/enable line, setting a data line (high or low, one bit at a time) and sliding the clock line from low to high. At a high level we want a function to just take a byte array and bit-bang all the necessary SPI signals. At a low level, we need to set the state for every clock cycle, bit by bit, in every byte of the array. For simplify, I use a List<byte> object to collect all my pin states. Then I convert it to an array right before sending it with ftdi.Write().

Full code is on GitHub

List<byte> bytesToSend = new List<byte>();
bytesToSend.Add(123); // just
bytesToSend.Add(111); // some
bytesToSend.Add(222); // test
bytesToSend.Add(012); // data

BitBangBytes(bytesToSend.ToArray());

// given a byte, return a List<byte> of pin states
public static List<byte> StatesFromByte(byte b)
{
    List<byte> states = new List<byte>();
    for (int i=0; i<8; i++)
    {
        byte dataState = (byte)((b >> (7-i)) & 1); // 1 if this bit is high
        states.Add((byte)(pin_data * dataState)); // set data pin with clock low
        states.Add((byte)(pin_data * dataState | pin_clock)); // pull clock high
    }
    return states;
}

// given a byte array, return a List<byte> of pin states
public static List<byte> StatesFromByte(byte[] b)
{
    List<byte> states = new List<byte>();
    foreach (byte singleByte in b)
        states.AddRange(StatesFromByte(singleByte));
    return states;
}

// bit-bang a byte array of pin states to the opened FTDI device
public static void BitBangBytes(byte[] bytesToSend)
{
    List<byte> states = StatesFromByte(bytesToSend);

    // pulse enable to clear what was there before
    states.Insert(0, pin_enable);
    states.Insert(0, 0);

    // pulse enable to apply configuration
    states.Add(pin_enable);
    states.Add(0);
    ft_status = ftdi.Write(states.ToArray(), states.Count, ref bytesWritten);
}

Bit-Bang Control of an RF Synthesizer

The AD9850 is a SPI-controlled DDS (Direct Digital Synthesizer) capable of generating sine waves up to 65 MHz and is available on breakout boards for around $20 on eBay and Amazon. It can be programmed with SPI by sending 40 bits (5 bytes), with the first 4 bytes being a frequency code (LSB first) and the last byte controls phase.

To calculate the code required for a specific frequency, multiply your frequency by 4,294,967,296 (2^32 - 1) then divide that number by the clock frequency (125,000,000). Using this formula, the code for 10 MHz is the integer 343,597,383. In binary it's 10100011110101110000101000111, and since it has to be shifted in LSB first (with a total of 40 bits) that means we would send 11100010100001110101111000101000 followed by the control byte which can be all zeros. In C# using the functions we made above, this looks like the following.

Full code is on GitHub

int freqTarget = 12_345_678; // 12.345678 MHz
ulong freqCode = (ulong)freqTarget * (ulong)4_294_967_296;
ulong freqCrystal = 125_000_000;
freqCode = freqCode / freqCrystal;
bytesToSend.Add(ReverseBits((byte)((freqCode >> 00) & 0xFF))); // 1 LSB
bytesToSend.Add(ReverseBits((byte)((freqCode >> 08) & 0xFF))); // 2
bytesToSend.Add(ReverseBits((byte)((freqCode >> 16) & 0xFF))); // 3
bytesToSend.Add(ReverseBits((byte)((freqCode >> 24) & 0xFF))); // 4 MSB
bytesToSend.Add(0); // control byte
BitBangBytes(bytesToSend.ToArray());

If somebody wants to get fancy and create a quadrature sine wave synthesizer, one could do so with two AD9850 boards if they shared the same 125 MHz clock. The two crystals could be programmed to the same frequency, but separated in phase by 90º. This could be used for quadrature encoding/decoding of single sideband (SSB) radio signals. This method may be used to build a direct conversion radio receiver ideal for receiving CW signals while eliminating the undesired sideband. This technique is described here, here, and here.

Polishing the Software

Rather than hard-coding a frequency into the code, I allowed it to accept this information from command line arguments. I did the same for FTDI devices, allowing the program to scan/list all devices connected to the system. Now you can command a particular frequency right from the command line. I didn't add additional arguments to control frequency sweep or phase control functionality, but it would be very straightforward if I ever decided to. I called this program "ftdiDDS.exe" and it is tested/working with the FT-232R and FT-232H, and likely supports other FTDI chips as well.

Download ftdiDDS

Command Line Usage:

  • ftdiDDS -list lists all available FTDI devices
  • ftdiDDS -mhz 12.34 sets frequency to 12.34 MHz
  • ftdiDDS -device 2 -mhz 12.34 specifically control device 2
  • ftdiDDS -sweep sweep 0-50 MHz over 5 seconds
  • ftdiDDS -help shows all options including a wiring diagram

Building an Enclosure

Although my initial goal for this project was simply to figure out how to bit-bang FTDI pins (the AD9850 was a SPI device I just wanted to test the concept on), now that I have a command-line-controlled RF synthesizer I feel like it's worth keeping! I threw it into an enclosure using my standard methods. I have to admit, the final build looks really nice. I'm still amused how simple it is.

Beware of the FT232R Bit Bang Bug

There is a serious problem with the FT-232R that affects its bit-bang functionality, and it isn't mentioned in the datasheet. I didn't know about this problem, and it set me back years! I tried bit-banging a FT-232R several years ago and concluded it just didn't work because the signal looked so bad. This week I learned it's just a bug (present in every FT-232R) that almost nobody talks about!

Consider trying to blink a LED with { 0, 1, 0, 1, 0 } sent using ftdi.Write() to the FT-232R. You would expect to see two pulses with a 50% duty. Bit-banging two pins like this { 0, 1, 2, 1, 2, 0 } one would expect the output to look like two square waves at 50% duty with opposite phase. This just... isn't what we see on the FT-232R. The shifts are technically correct, but the timing is all over the place. The identical code, when run on a FT-232H, presents no timing problems - the output is a beautiful

The best way to demonstrate how "bad" the phase problem is when bit-banging the FT232R is seen when trying to send 50% duty square waves. In the photograph of my oscilloscope below, the yellow trace is supposed to be a "square wave with 50% duty" (ha!) and the lower trace is supposed to be a 50% duty square wave with half the frequency of the top (essentially what the output of the top trace would be if it were run through a flip-flop). The variability in pulse width is so crazy that initially I mistook this as 9600 baud serial data! Although the timing looks wacky, the actual shifts are technically correct, and the FT-232R can still be used to bit-bang SPI.

Unfortunately this unexpected behavior is not documented in the datasheet, but it is referenced in section 3.1.2 of the TN_120 FT232R Errate Technical Note where it says "The output may be clocked out at different speeds ... and can result in the pulse widths varying unexpectedly on the output." Their suggested solution (I'll let you read it yourself) is a bit comical. It's essentially says "to get a 50% duty square wave, send a 0 a bunch of times then a 1 the same number of times". I actually tried this, and it is only square-like when you send each state about 1000 times. The data gets shifted out 1000 times slower, but if you're in a pinch (demanding squarer waves and don't mind the decreased speed) I guess it could work. Alternatively, just use an FT-232H.

Update (2018-10-05): YouTube user Frederic Torres said this issue goes away when externally clocking the FT232R chip. It's not easy to do on the breakout boards, but if you're spinning your own PCB it's an option to try!

Alternatives to this Method

Bit-banging pin states on FTDI chips is a cool hack, but it isn't necessarily the best solution for every problem. This section lists some alternative methods which may achieve similar goals, and touches on some of their pros and cons.

  • LibFTDI - an alternative, open-source, third party driver for FTDI devices. Using this driver instead of the default FTDI driver gives you options to more powerful commands to interact with FTDI chips. One interesting option is the simple ability to interact with the chip from Python with pyLibFTDI.While this is a good took for hackers and makers, if I want to build a device to send to a lay client I won't want to expect them to fumble with installing custom drivers or ensure they are being used over the default ones FTDI supplies. I chose not to pursue utilizing this project because I value the "plug it in and it just works" functionality that comes from simply using FTDI's API and drivers (which are automatically supplied by Windows)

  • Raspberry PI can bit-bang SPI - While perhaps not ideal for making small USB devices to send to clients, if your primary goal is just to control a SPI device from a computer then definitely consider using a Raspberry Pi! A few of the pins on its header are capable of SPI and can even be driven directly from the bash console. I've used this technique to generate analog voltages from a command line using a Raspberry PI to send SPI commands to a MCP4921 12-bit DAC.

  • Multi-Protocol Synchronous Serial Engine (MPSSE) - Some FTDI chips support MPSSE, which can send SPI (or I2C or other) protocols without you having to worry about bit-banging pins. I chose not to pursue this option because I wanted to use my FT232R (one of the most common and inexpensive FTDI chips), which doesn't support MPSSE. ALthough I do have a FT232H which does support MPSSE (example project), I chose not to use that feature for this project, favoring a single code/program to control all FTDI devices.

  • Bus Pirate - If you don't have a Bus Pirate already, get one! It's one of the most convenient ways to get a new peripheral up and running. It's a USB device you can interact with through a serial terminal (supplied using a FTDI usb-to-serial converter, go fig) and you can tell it to send/receive commands to SPI or I2C devices. It does a lot more, and is worth checking out.

Resources

  • Saleae logic analyzers - The official Saleae hardware (not what was shown in my video, which was a cheap eBay knock-off) can do a lot of great things. Their free software is _really _simple to use, and they haven't gone out of their way to block the use of third-party logic analyzers with their free software. If you are in a place where you can afford to support this company financially, I suggest browsing their products and purchasing their official hardware.

  • DYMO Letra-Tag LT100-H label maker and clear tape - When labels are printed with black boxes around them (a tip I learned from Onno) they look fantastic when placed on project boxes! Don't buy the knock-off clear labels, as they aren't truly clear. The clear tape you need to purchase has the brand name "DYMO" written on the tape dispenser.

  • FT232H breakout board (adafruit) - This is where I got the FT232H board used in this video. You can find additional similar FT232H breakout boards on Amazon.

  • FT232R breakout board - Everyone sells these. I got some lately on Amazon, but I've gotten them before on eBay too.

  • TTL-232R cable - If you're making a device which you want to appear a bit more professional, this cable has the FT232R built-in and it just has several pins (in a female header) you can snap onto your board.

  • Bit Bang Modes for the FT232R - FTDI datasheet detailing how to Bit-Bang the FT232R chip. In practice, the terms, language, and code examples in this datasheet seem similar enough to the FT232H that it probably is all you need to get started, since it's the large-scale concepts which are most important.

  • Introduction to the FTDI BitBang mode - A Hack-A-Day article from 2009 mentions FTDI chips can be used to bit-bang pin states and they have their own LED blink examples. Their article does hint at using this method to bit-bang SPI, but it fails entirely to note the FT232R bug that surely has confused multiple people in the past...

  • FT232R BitBang SPI example - This code uses libftdi, not the default driver supplied by FTDI (libftd2xx).

  • FT232R BitBang mode is broken - an article from 2012 detailing how bad the timing is when bit-banging pin states on the FT232R.

  • Official acknowledgement of the FT232R timing problem is described in the TN_120 FT232R Errate Technical Note in section 3.1.2 where they state the problem as: "The output may be clocked out at different speeds to allow for different pulse widths. However this clocking stage is not synchronized with the incoming data and can result in the pulse widths varying unexpectedly on the output."

  • AD9850 Complete DDS Synthesizer Datasheet

Conclusion

Bit-banging pin states on FTDI devices is relatively simple, even using the standard drivers and API. The FTD2XX_NET library on NuGet provides a simple way to do this. The output of the FT232H is much more accurate in the time domain than the FT232R. Although there are crazy timing issues with the FT232R, it works fine when driving most SPI devices. Here we used this technique to write a console application to control an AD9850 DDS directly from an FT232R using command line arguments. When given a formal enclosure, this project looks (and works) great!

If you make something cool by bit-banging a FTDI device, let me know about it!

Markdown source code last modified on January 14th, 2023
---
title: Bit-Bang FTDI USB-to-Serial Converters to Drive SPI Devices
date: 2018-06-03 18:51:30
tags: csharp, microcontroller
---

# Bit-Bang FTDI USB-to-Serial Converters to Drive SPI Devices

**The FT232 USB-to-serial converter is one of the most commonly-used methods of adding USB functionality to small projects, but recently I found that these chips are capable of sending more than just serial signals. With some creative programming, individual output pins can be big-banged to emulate a clock, data, and chip select line to control SPI devices.** This post shares some of the techniques I use to bit-bang SPI with FTDI devices, and some of the perks (and quirks) of using FTDI chips to bit-bang data from a USB port. Code examples are [available](https://github.com/swharden/AVR-projects/tree/master/FTDI%202018-05-30%20bit%20bang) on GitHub, and links to additional resources are at the bottom of this post. After the final build I created a slightly more polished "ftdiDDS.exe" program to control an AD9850 frequency synthesizer from the command line by bit-banging a FT-232, and code (and binaries) are also [available](https://github.com/swharden/AVR-projects/tree/master/FTDI%202018-06-03%20ftdiDDS) on GitHub.

![](https://www.youtube.com/embed/QkHsryvDZfo)

## Why Bit-Bang FTDI Pins?

The main reason I like using FTDI devices is because when you plug them in to a modern computer, they just start working! You don't have to worry about drivers, driver versions, driver signing, third party drivers - most of the time it just does what it's supposed to do with no complexity. If I'm going to build a prototype device for a client, a FT-232 USB to serial converter is the way to go because I can be confident that when they plug in, their device will start working right away. Yeah, there are third party drivers to get extra open-sourcey functionality from FTDI devices ([libFTDI](https://www.intra2net.com/en/developer/libftdi/)), but I don't want to ask a client (with unknown tech-savviness) to install third-party unsigned drivers before plugging my device in (and heaven forbid the product doesn't work in their hands and I have to ask them to verify the device is actually using the third-party drivers and not defaulting back to the official ones). In this project I seek to use only the generic, default, officially-supported FTDI driver and API access will be provided by [libftd2xx](http://www.ftdichip.com/Drivers/D2XX.htm). Don't forget that USB ports supply 5V and GND, so in most cases you can power your project just from the USB port! All-in-all, the FT-232 is a great way to give a small device USB functionality. This post explores how to use it for more than just sending and receiving serial data...

### FT-232R Breakout Board
<div class="text-center img-border">

[![](232r_thumb.jpg)](232r.png)

</div>

### FT-232H Breakout Board
<div class="text-center img-border">

[![](232h_thumb.jpg)](232h.png)

</div>

### TTL-FT232R Cable
<div class="text-center img-border">

[![](ttl-ft232r-cable_thumb.jpg)](ttl-ft232r-cable.png)

</div>

## Controlling FTDI Devices with C# 

The goal of this post is not to describe every detail about how to control FTDI chips. Instead, the key points of the software are described here (and in the video) so you can get the gist of the main concepts. If you're interested in additional detail, [full code examples are provided on the GitHub folder for this project](https://github.com/swharden/AVR-projects/tree/master/FTDI%202018-05-30%20bit%20bang). All code examples were tested with Visual Studio Community 2017, are written in C#, and uses the FTD2XX_NET library installed with NuGet. Also, see the list of resources (including official FTDI datasheets and application notes) at the bottom of this post.

__This block of code attaches to FTDI device 0 (the first FTDI device it sees) and sends the letter "a" using a traditional serial protocol.__ Since this code connects to the first FTDI device it finds, this could be a problem if you have more than 1 FTDI device attached. Alternatively you could have your program connect to a specific FTDI device (e.g., by its serial number). To see what FTDI devices are attached to your computer (and see or set their serial numbers), use the FT_Prog application [provided by FTDI](http://www.ftdichip.com/Support/Utilities.htm). Also, [see the code I use to list FTDI devices](https://github.com/swharden/AVR-projects/blob/master/FTDI%202018-06-03%20ftdiDDS/source/FTDI-video-demo/Program.cs#L87-L107) from inside a C# program ftdiDDS program.

_Full code is [on GitHub](https://github.com/swharden/AVR-projects/blob/master/FTDI%202018-05-30%20bit%20bang/00-serial.cs)_

```cs
public static FTDI ftdi = new FTDI();
public static FTDI.FT_STATUS ft_status = FTDI.FT_STATUS.FT_OK;
public static UInt32 bytesWritten = 0;

static void Main(string[] args)
{
    ft_status = ftdi.OpenByIndex(0);
    ft_status = ftdi.SetBaudRate(9600);
    string data = "a";
    ft_status = ftdi.Write(data, data.Length, ref bytesWritten);
}

```

# LED Blink by Bit-Banging FTDI Pins

__Here is a minimal complexity LED blink example. This code block alternates between writing 0 (all pins off) and 1 (TX pin high) over and over forever. __Note that `` ftdi.SetBitMode `` is what frees the FTDI chip from sending serial data when `` ftdi.Write() `` gets called. The 255 is a byte mask which tells all 8 pins to be outputs (by setting all 8 bits in the byte to 1, hence 255). Setting bit mode to 1 means we are using asynchronous bit bang bode (sufficient if we don't intend to read any pin states). For full details about these (and other) bit-bang settings, check out the [Bit Bang Modes for the FT232R](http://www.ftdichip.com/Support/Documents/AppNotes/AN_232R-01_Bit_Bang_Mode_Available_For_FT232R_and_Ft245R.pdf) application note.

_Full code is [on GitHub](https://github.com/swharden/AVR-projects/blob/master/FTDI%202018-05-30%20bit%20bang/03-state-LEDblink.cs)_

```cs
ft_status = ftdi.OpenByIndex(0);
ft_status = ftdi.SetBitMode(255, 1);
ft_status = ftdi.SetBaudRate(9600);
int count = 0;

while (true)
{
    byte[] data = { (byte)(count++%2) };
    ft_status = ftdi.Write(data, data.Length, ref bytesWritten);
    System.Threading.Thread.Sleep(100);
}

```

<div class="text-center img-border">

[![](DSC_0023_thumb.jpg)](DSC_0023.jpg)

</div>

# Bit-Bang SPI with a FT232

In reality all we want to send to SPI devices are a series of numbers which we can place in a byte array. These numbers are transmitted by pulling-low a clip select/enable line, setting a data line (high or low, one bit at a time) and sliding the clock line from low to high. At a high level we want a function to just take a byte array and bit-bang all the necessary SPI signals. At a low level, we need to set the state for every clock cycle, bit by bit, in every byte of the array. For simplify, I use a `` List<byte> `` object to collect all my pin states. Then I convert it to an array right before sending it with `` ftdi.Write() ``.

_Full code is [on GitHub](https://github.com/swharden/AVR-projects/blob/master/FTDI%202018-05-30%20bit%20bang/06-bit-bang-spi.cs)_

```cs
List<byte> bytesToSend = new List<byte>();
bytesToSend.Add(123); // just
bytesToSend.Add(111); // some
bytesToSend.Add(222); // test
bytesToSend.Add(012); // data

BitBangBytes(bytesToSend.ToArray());

// given a byte, return a List<byte> of pin states
public static List<byte> StatesFromByte(byte b)
{
    List<byte> states = new List<byte>();
    for (int i=0; i<8; i++)
    {
        byte dataState = (byte)((b >> (7-i)) & 1); // 1 if this bit is high
        states.Add((byte)(pin_data * dataState)); // set data pin with clock low
        states.Add((byte)(pin_data * dataState | pin_clock)); // pull clock high
    }
    return states;
}

// given a byte array, return a List<byte> of pin states
public static List<byte> StatesFromByte(byte[] b)
{
    List<byte> states = new List<byte>();
    foreach (byte singleByte in b)
        states.AddRange(StatesFromByte(singleByte));
    return states;
}

// bit-bang a byte array of pin states to the opened FTDI device
public static void BitBangBytes(byte[] bytesToSend)
{
    List<byte> states = StatesFromByte(bytesToSend);

    // pulse enable to clear what was there before
    states.Insert(0, pin_enable);
    states.Insert(0, 0);

    // pulse enable to apply configuration
    states.Add(pin_enable);
    states.Add(0);
    ft_status = ftdi.Write(states.ToArray(), states.Count, ref bytesWritten);
}

```

<div class="text-center img-border">

[![](DSC_0046_thumb.jpg)](DSC_0046.jpg)

</div>

# Bit-Bang Control of an RF Synthesizer

__The AD9850 is a SPI-controlled DDS (Direct Digital Synthesizer) capable of generating sine waves up to 65 MHz and is available on breakout boards for around $20__ on eBay and Amazon. It can be programmed with SPI by sending 40 bits (5 bytes), with the first 4 bytes being a frequency code (LSB first) and the last byte controls phase.

__To calculate the code required for a specific frequency,__ multiply your frequency by 4,294,967,296 (2^32 - 1) then divide that number by the clock frequency (125,000,000). Using this formula, the code for 10 MHz is the integer 343,597,383. In binary it's 10100011110101110000101000111, and since it has to be shifted in LSB first (with a total of 40 bits) that means we would send 11100010100001110101111000101000 followed by the control byte which can be all zeros. In C# using the functions we made above, this looks like the following.

_Full code is [on GitHub](https://github.com/swharden/AVR-projects/blob/master/FTDI%202018-05-30%20bit%20bang/07-AD9850-single-frequency.cs)_

```cs
int freqTarget = 12_345_678; // 12.345678 MHz
ulong freqCode = (ulong)freqTarget * (ulong)4_294_967_296;
ulong freqCrystal = 125_000_000;
freqCode = freqCode / freqCrystal;
bytesToSend.Add(ReverseBits((byte)((freqCode >> 00) & 0xFF))); // 1 LSB
bytesToSend.Add(ReverseBits((byte)((freqCode >> 08) & 0xFF))); // 2
bytesToSend.Add(ReverseBits((byte)((freqCode >> 16) & 0xFF))); // 3
bytesToSend.Add(ReverseBits((byte)((freqCode >> 24) & 0xFF))); // 4 MSB
bytesToSend.Add(0); // control byte
BitBangBytes(bytesToSend.ToArray());

```

<div class="text-center img-border img-small">

[![](ad9850-SPI-DDS_thumb.jpg)](ad9850-SPI-DDS.png)
[![](scope-output_thumb.jpg)](scope-output.png)

</div>

If somebody wants to get fancy and create a quadrature sine wave synthesizer, one could do so with two AD9850 boards if they shared the same 125 MHz clock. The two crystals could be programmed to the same frequency, but separated in phase by 90º. This could be used for quadrature encoding/decoding of single sideband (SSB) radio signals. This method may be used to build a direct conversion radio receiver ideal for receiving CW signals while eliminating the undesired sideband. This technique is described [here](https://www.eetimes.com/document.asp?doc_id=1224754), [here](https://pdfs.semanticscholar.org/9ca4/d7b29b33ff47bde4945af854416ff0f0a9db.pdf), and [here](http://www.cs.tut.fi/kurssit/TLT-5806/RecArch.pdf).

# Polishing the Software

Rather than hard-coding a frequency into the code, I allowed it to accept this information from command line arguments. I did the same for FTDI devices, allowing the program to scan/list all devices connected to the system. Now you can command a particular frequency right from the command line. I didn't add additional arguments to control frequency sweep or phase control functionality, but it would be very straightforward if I ever decided to. __I called this program "ftdiDDS.exe" and it is tested/working with the FT-232R and FT-232H, and likely supports other FTDI chips as well.__

### Download ftdiDDS

*   64-bit Windows binary: [ftdiDDS.exe](https://github.com/swharden/AVR-projects/blob/master/FTDI%202018-06-03%20ftdiDDS/ftdiDDS.zip)
*   Source code: [ftdiDDS on GitHub](https://github.com/swharden/AVR-projects/tree/master/FTDI%202018-06-03%20ftdiDDS)

### Command Line Usage:

*   `` ftdiDDS -list `` _lists all available FTDI devices_
*   `` ftdiDDS -mhz 12.34 `` _sets frequency to 12.34 MHz_
*   `` ftdiDDS -device 2 -mhz 12.34 `` _specifically control device 2_
*   `` ftdiDDS -sweep `` _sweep 0-50 MHz over 5 seconds_
*   `` ftdiDDS -help `` _shows all options including a wiring diagram_

<div class="text-center">

[![](console_thumb.jpg)](console.jpg)

</div>

# Building an Enclosure

Although my initial goal for this project was simply to figure out how to bit-bang FTDI pins (the AD9850 was a SPI device I just wanted to test the concept on), now that I have a command-line-controlled RF synthesizer I feel like it's worth keeping! I threw it into an enclosure using my standard methods. I have to admit, the final build looks really nice. I'm still amused how simple it is.

<div class="text-center img-border">

[![](enclosed_thumb.jpg)](enclosed.png)
[![](dds-desk_thumb.jpg)](dds-desk.jpg)

</div>

# Beware of the FT232R Bit Bang Bug

__There is a serious problem with the FT-232R that affects its bit-bang functionality, and it isn't mentioned in the datasheet.__ I didn't know about this problem, and it set me back _years_! I tried bit-banging a FT-232R several years ago and concluded it just didn't work because the signal looked so bad. This week I learned it's just a bug (present in every FT-232R) that almost nobody talks about!

__Consider trying to blink a LED with { 0, 1, 0, 1, 0 }__ sent using `` ftdi.Write() `` to the FT-232R. You would expect to see two pulses with a 50% duty. Bit-banging two pins like this { 0, 1, 2, 1, 2, 0 } one would expect the output to look like two square waves at 50% duty with opposite phase. This just... isn't what we see on the FT-232R. The shifts are technically correct, but the timing is all over the place. The identical code, when run on a FT-232H, presents no timing problems - the output is a beautiful

<div class="text-center img-border">

[![](232h-scope_thumb.jpg)](232h-scope.jpg)

</div>

__The best way to demonstrate how "bad" the phase problem is when bit-banging the FT232R is seen when trying to send 50% duty square waves.__ In the photograph of my oscilloscope below, the yellow trace is supposed to be a "square wave with 50% duty" (ha!) and the lower trace is supposed to be a 50% duty square wave with half the frequency of the top (essentially what the output of the top trace would be if it were run through a flip-flop). The variability in pulse width is so crazy that initially I mistook this as 9600 baud serial data! Although the timing looks wacky, the actual shifts are technically correct, and the FT-232R can still be used to bit-bang SPI.

<div class="text-center img-border">

[![](232r-scope2_thumb.jpg)](232r-scope2.jpg)

</div>

**Unfortunately this unexpected behavior is not documented in the datasheet,** but it is referenced in section 3.1.2 of the [TN\_120 FT232R Errate Technical Note](http://www.ftdichip.com/Support/Documents/TechnicalNotes/TN_120_FT232R%20Errata%20Technical%20Note.pdf) where it says "_The output may be clocked out at different speeds ... and can result in the pulse widths varying unexpectedly on the output._" Their suggested solution (I'll let you read it yourself) is a bit comical. It's essentially says "to get a 50% duty square wave, send a 0 a bunch of times then a 1 the same number of times". I actually tried this, and it is only square-like when you send each state about 1000 times. The data gets shifted out 1000 times slower, but if you're in a pinch (demanding squarer waves and don't mind the decreased speed) I guess it could work. Alternatively, just use an FT-232H.

__Update (2018-10-05):__ YouTube user Frederic Torres said this issue goes away when externally clocking the FT232R chip. It's not easy to do on the breakout boards, but if you're spinning your own PCB it's an option to try!

# Alternatives to this Method

Bit-banging pin states on FTDI chips is a cool hack, but it isn't necessarily the best solution for every problem. This section lists some alternative methods which may achieve similar goals, and touches on some of their pros and cons.

*   [LibFTDI](https://www.intra2net.com/en/developer/libftdi/) - an alternative, open-source, third party driver for FTDI devices. Using this driver instead of the default FTDI driver gives you options to more powerful commands to interact with FTDI chips. One interesting option is the simple ability to interact with the chip from Python with [pyLibFTDI](https://pylibftdi.readthedocs.io/en/0.15.0/).While this is a good took for hackers and makers, if I want to build a device to send to a lay client I won't want to expect them to fumble with installing custom drivers or ensure they are being used over the default ones FTDI supplies. I chose not to pursue utilizing this project because I value the "plug it in and it just works" functionality that comes from simply using FTDI's API and drivers (which are automatically supplied by Windows)

*   [Raspberry PI can bit-bang SPI](https://raspberrypi-aa.github.io/session3/spi.html) - While perhaps not ideal for making small USB devices to send to clients, if your primary goal is just to control a SPI device from a computer then definitely consider using a Raspberry Pi! A few of the pins on its header are capable of SPI and can even be driven directly from the bash console. I've [used this technique](https://www.swharden.com/wp/2016-09-28-generating-analog-voltages-with-the-raspberry-pi/) to generate analog voltages from a command line using a Raspberry PI to send SPI commands to a MCP4921 12-bit DAC.

*   [Multi-Protocol Synchronous Serial Engine (MPSSE)](http://www.ftdichip.com/Support/Documents/AppNotes/AN_135_MPSSE_Basics.pdf) - Some FTDI chips support MPSSE, which can send SPI (or I2C or other) protocols without you having to worry about bit-banging pins. I chose not to pursue this option because I wanted to use my FT232R (one of the most common and inexpensive FTDI chips), which doesn't support MPSSE. ALthough I do have a FT232H which does support MPSSE ([example project](http://www.ftdichip.com/Support/Documents/AppNotes/AN_180_FT232H%20MPSSE%20Example%20-%20USB%20Current%20Meter%20using%20the%20SPI%20interface.pdf)), I chose not to use that feature for this project, favoring a single code/program to control all FTDI devices.

*   [Bus Pirate](http://dangerousprototypes.com/docs/Bus_Pirate) - If you don't have a Bus Pirate already, [get one!](https://www.seeedstudio.com/s/bus%20pirate.html) It's one of the most convenient ways to get a new peripheral up and running. It's a USB device you can interact with through a serial terminal (supplied using a FTDI usb-to-serial converter, go fig) and you can tell it to send/receive commands to SPI or I2C devices. It does a lot more, and is worth checking out.

# Resources

*   [Saleae logic analyzers](https://www.saleae.com) - The official Saleae hardware (not what was shown in my video, which was a cheap eBay knock-off) can do a lot of great things. Their free software is _really _simple to use, and they haven't gone out of their way to block the use of third-party logic analyzers with their free software. If you are in a place where you can afford to support this company financially, I suggest browsing their products and purchasing their official hardware.

*   [DYMO Letra-Tag LT100-H label maker](https://www.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=Dymo+LetraTag+LT100-H&rh=i%3Aaps%2Ck%3ADymo+LetraTag+LT100-H) and [clear tape](https://www.amazon.com/Genuine-Polyester-LetraTAG-LetraTag-LT100H/dp/B01M9CPJGK/) - When labels are printed with black boxes around them (a tip I learned from [Onno](http://www.qsl.net/pa2ohh/)) they look fantastic when placed on project boxes! Don't buy the knock-off clear labels, as they aren't truly clear. The clear tape you need to purchase has the brand name "DYMO" written on the tape dispenser.

*   [FT232H breakout board](https://www.adafruit.com/product/2264) (adafruit) - This is where I got the FT232H board used in this video. You can find additional [similar FT232H breakout boards on Amazon](https://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords=ft232h).

*   [FT232R breakout board](https://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords=ft232r&rh=i%3Aaps%2Ck%3Aft232r) - Everyone sells these. I got some lately on Amazon, but I've gotten them before on eBay too.

*   [TTL-232R cable](http://www.ftdichip.com/Support/Documents/DataSheets/Cables/DS_TTL-232R_CABLES.pdf) - If you're making a device which you want to appear a bit more professional, this cable has the FT232R built-in and it just has several pins (in a female header) you can snap onto your board.

*   [Bit Bang Modes for the FT232R](http://www.ftdichip.com/Support/Documents/AppNotes/AN_232R-01_Bit_Bang_Mode_Available_For_FT232R_and_Ft245R.pdf) - FTDI datasheet detailing how to Bit-Bang the FT232R chip. In practice, the terms, language, and code examples in this datasheet seem similar enough to the FT232H that it probably is all you need to get started, since it's the large-scale concepts which are most important.

*   [Introduction to the FTDI BitBang mode](https://hackaday.com/2009/09/22/introduction-to-ftdi-bitbang-mode/) - A Hack-A-Day article from 2009 mentions FTDI chips can be used to bit-bang pin states and they have their own LED blink examples. Their article does hint at using this method to bit-bang SPI, but it fails entirely to note the FT232R bug that surely has confused multiple people in the past...

*   [FT232R BitBang SPI example](http://jdelfes.blogspot.com/2014/02/spi-bitbang-ft232r.html) - This code uses [libftdi](https://www.intra2net.com/en/developer/libftdi/), not the default driver supplied by FTDI ([libftd2xx](http://www.ftdichip.com/Drivers/D2XX.htm)).

*   [FT232R BitBang mode is broken](http://blog.bitheap.net/2012/03/ft232r-bitbang-mode-is-broken.html) - an article from 2012 detailing how bad the timing is when bit-banging pin states on the FT232R.

*   Official acknowledgement of the FT232R timing problem is described in the [TN\_120 FT232R Errate Technical Note](http://www.ftdichip.com/Support/Documents/TechnicalNotes/TN_120_FT232R%20Errata%20Technical%20Note.pdf) in section 3.1.2 where they state the problem as: "_The output may be clocked out at different speeds to allow for different pulse widths. However this clocking stage is not synchronized with the incoming data and can result in the pulse widths varying unexpectedly on the output._"

*   [AD9850 Complete DDS Synthesizer Datasheet](http://www.analog.com/media/en/technical-documentation/data-sheets/AD9850.pdf)

# Conclusion

**Bit-banging pin states on FTDI devices is relatively simple, even using the standard drivers and API.** The FTD2XX_NET library on NuGet provides a simple way to do this. The output of the FT232H is much more accurate in the time domain than the FT232R. Although there are crazy timing issues with the FT232R, it works fine when driving most SPI devices. Here we used this technique to write a console application to control an AD9850 DDS directly from an FT232R using command line arguments. When given a formal enclosure, this project looks (and works) great!

<div class="text-center img-border">

[![](scope-dds_thumb.jpg)](scope-dds.png)

</div>

If you make something cool by bit-banging a FTDI device, let me know about it!
December 19th, 2017

IoT Festivus Pole

The Internet of Things now includes Festivus poles! **Festivus is a holiday celebrated on December 23rd, and its customary practices include a Festivus pole, Festivus dinner, airing of grievances, feats of strength, and Festivus miracles. The internet contains a few nods to the holiday, including what happens when you Google for the word Festivus (a Festivus pole is displayed at the bottom of the page). In 2015 I had the honor of gifting the world with the first Festivus pole video game, and today I am happy to unveil the world's first internet-enabled Festivus pole. Every time somebody tweets #Festivus or #FestivusMiracle, the light at the top of the pole illuminates! All in the room then excitedly exclaim, "it's a Festivus miracle!"

The IoT Festivus Pole is powered by a Raspberry Pi (a Pi 2 Model B, although any Pi would work) running a Python script which occasionally checks for tweets using the twitter API (via twython, a pure-python twitter API wrapper) and controls the GPIO pin 12 with RPi.GPIO (extra docs). After writing the Python script (which should work identically in Python 2 or Python 3), I got it to run automatically every time the system boots by adding a line to /etc/rc.local (surrounding it with parentheses and terminating the line with & to allow it to run without blocking the startup sequence). The LED was added to the end of a long wire (with a series 220-ohm resistor) and connected across the Raspberry Pi header pins 12 (PWM) and 14 (GND). I set PWM frequency to 100 Hz, but this is easily configurable in software.

To build the Festivus pole I got a piece of wood and a steel conduit pipe from Lowe's (total <$5). Festivus purists will argue that Festivus poles should be made from aluminum (with its very high strength to weight ratio). I live in an apartment and don't have a garage, so my tool selection is limited. I cut the wood a few times with a jigsaw and glued it together to make an impressive stand similar to those of traditional Festivus poles. I have a few hole saw drill bits, but none of them perfectly matched the size of the pipe. I traced the outline of the pipe on the wood and cut-out a circular piece with a Dremel drill press in combination with a side-cutting bit. The hole was slightly larger than required for the pipe, so I used a few layers of electrical tape on the bottom of the pipe to "seal" the base of the pipe into the hole, then poured acrylic epoxy into the empty space. Clamping it against a desk allowed the epoxy to set such that the pole was rigidly upright, and the result was a fantastic-looking Festivus pole! It's a bit smaller in size than the famous one featured in Seinfeld, but I think it is appropriately sized for my apartment.

Adding the computer was easy! Internet capability was provided via a USB WiFi card. Code is at the bottom of this page. The LED was connected to Raspberry Pi header pins 12 and 14. The wiring was snaked through the conduit.

The code will work on Python 2 and Python 3. Pip can be used to install RPi.GPIO and twython: pip install python-dev python-rpi.gpio twython

import RPi.GPIO as GPIO
import time
from twython import Twython

APP_KEY = 'zSNYBNWHmXhU3CX765HnoQEbm'
APP_SECRET = 'getYourOwnApiKeyFromTwitterWebsite'
twitter = Twython(APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()

GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)
p = GPIO.PWM(12, 100)
p.start(0)

if __name__=="__main__":
    tweetLast=0
    checkLast=0
    duty=100

    while True:
        if (checkLast+5)<time.time():
            checkLast=time.time()
            print("checking twitter...")
            tweetLatest=twitter.search(q='festivus')["statuses"][0]["created_at"]
            if tweetLatest!=tweetLast:
                print("IT'S A FESTIVUS MIRACLE!")
                tweetLast=tweetLatest
                duty=100
            else:
                print('nothing')

        if duty>=0:
            p.ChangeDutyCycle(duty)

        time.sleep(.3)
        duty-=1

This Festivus pole has been up and running for the last few days and I'm excited to see how much joy it has brought into my household! Admittedly the Raspberry Pi seems to be overkill, but at the time I was considering having it also output audio every time a tweet is made but I never decided on the clip to use so I omitted the feature. An ESP8266 WiFi module interfaced with a microntroller can do the same job with more elegance and lower cost, so I may consider improving it next year. Until then, Happy Festivus!

Markdown source code last modified on January 18th, 2021
---
title: IoT Festivus Pole
date: 2017-12-19 22:11:17
tags: circuit, microcontroller
---

# IoT Festivus Pole

The <em>Internet of Things</em> now includes Festivus poles! **Festivus is a holiday celebrated on December 23rd, and its [customary practices](https://en.wikipedia.org/wiki/Festivus) include a Festivus pole, Festivus dinner, airing of grievances, feats of strength, and Festivus miracles. The internet contains a few nods to the holiday, including [what happens when you Google for the word Festivus](https://www.google.com/search?q=festivus) (a Festivus pole is displayed at the bottom of the page). In 2015 I had the honor of gifting the world with the first [Festivus pole video game](https://www.swharden.com/wp/2015-12-23-festivus-pole-video-game/), and today I am happy to unveil the world's first internet-enabled Festivus pole. Every time somebody tweets #Festivus or #FestivusMiracle, the light at the top of the pole illuminates! All in the room then excitedly exclaim, "it's a Festivus miracle!"

<div class="text-center img-border img-small">

[![](723_thumb.jpg)](723.jpg)

</div>

__The IoT Festivus Pole is powered by a Raspberry Pi__ (a Pi 2 Model B, although any Pi would work) running a Python script which occasionally checks for tweets using the [twitter API](https://developer.twitter.com/en/docs) (via [twython](https://github.com/ryanmcgrath/twython), a pure-python twitter API wrapper) and controls the GPIO pin 12 with [RPi.GPIO](https://pypi.python.org/pypi/RPi.GPIO) ([extra docs](https://learn.sparkfun.com/tutorials/raspberry-gpio/python-rpigpio-api)). After writing the Python script (which should work identically in Python 2 or Python 3), I got it to run automatically every time the system boots by adding a line to /etc/rc.local (surrounding it with parentheses and terminating the line with & to allow it to run without blocking the startup sequence). The LED was added to the end of a long wire (with a series 220-ohm resistor) and connected across the [Raspberry Pi header](https://pinout.xyz) pins 12 (PWM) and 14 (GND). I set PWM frequency to 100 Hz, but this is easily configurable in software.

<div class="text-center img-small">

![](festivus_miracle.gif)
![](729.jpeg)

</div>

__To build the Festivus pole__ I got a piece of wood and a steel conduit pipe from Lowe's (total <$5). Festivus purists will argue that Festivus poles should be made from aluminum (with its very high strength to weight ratio). I live in an apartment and don't have a garage, so my tool selection is limited. I cut the wood a few times with a jigsaw and glued it together to make an impressive stand similar to those of [traditional Festivus poles](https://en.wikipedia.org/wiki/Festivus). I have a few hole saw drill bits, but none of them perfectly matched the size of the pipe. I traced the outline of the pipe on the wood and cut-out a circular piece with a Dremel drill press in combination with a side-cutting bit. The hole was slightly larger than required for the pipe, so I used a few layers of electrical tape on the bottom of the pipe to "seal" the base of the pipe into the hole, then poured acrylic epoxy into the empty space. Clamping it against a desk allowed the epoxy to set such that the pole was rigidly upright, and the result was a fantastic-looking Festivus pole! It's a bit smaller in size than the famous one featured in Seinfeld, but I think it is appropriately sized for my apartment.

<div class="text-center img-border">

[![](725_thumb.jpg)](725.jpg)
[![](726_thumb.jpg)](726.jpg)

</div>

__Adding the computer was easy!__ Internet capability was provided via a USB WiFi card. Code is at the bottom of this page. The LED was connected to [Raspberry Pi header](https://pinout.xyz) pins 12 and 14. The wiring was snaked through the conduit.

<div class="text-center img-border">

[![](728_thumb.jpg)](728.jpg)
[![](719_thumb.jpg)](719.jpg)
[![](726_thumb.jpg)](726.jpg)

</div>

__The code will work on Python 2 and Python 3.__
Pip can be used to install RPi.GPIO and twython: `` pip install python-dev python-rpi.gpio twython ``

```python
import RPi.GPIO as GPIO
import time
from twython import Twython

APP_KEY = 'zSNYBNWHmXhU3CX765HnoQEbm'
APP_SECRET = 'getYourOwnApiKeyFromTwitterWebsite'
twitter = Twython(APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()

GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)
p = GPIO.PWM(12, 100)
p.start(0)

if __name__=="__main__":
    tweetLast=0
    checkLast=0
    duty=100

    while True:
        if (checkLast+5)<time.time():
            checkLast=time.time()
            print("checking twitter...")
            tweetLatest=twitter.search(q='festivus')["statuses"][0]["created_at"]
            if tweetLatest!=tweetLast:
                print("IT'S A FESTIVUS MIRACLE!")
                tweetLast=tweetLatest
                duty=100
            else:
                print('nothing')

        if duty>=0:
            p.ChangeDutyCycle(duty)

        time.sleep(.3)
        duty-=1

```

__This Festivus pole has been up and running for the last few days__ and I'm excited to see how much joy it has brought into my household! Admittedly the Raspberry Pi seems to be overkill, but at the time I was considering having it also output audio every time a tweet is made but I never decided on the clip to use so I omitted the feature. An [ESP8266 WiFi module](https://www.sparkfun.com/products/13678) interfaced with a microntroller can do the same job with more elegance and lower cost, so I may consider improving it next year. Until then, Happy Festivus!

![](https://www.youtube.com/embed/HX55AzGku5Y)
Pages