# Using NeoPixels and Servos Together

## The Issue

Not a week goes by in the [Adafruit Forums](http://forums.adafruit.com)&nbsp;that someone isn’t heartbroken to discover that the NeoPixel and Servo libraries won’t work together in the same Arduino sketch. Fear not, help is on the way!

Rather than just leave you with a “mysterious black box” workaround (an Arduino library), it also seemed a good opportunity to introduce some advanced Arduino programming concepts.&nbsp; **If you just want a fix&nbsp;and aren’t interested in a lengthy technical explanation, that’s totally fine! You can skip ahead to the third page, “The TiCoServo Library” and get started.**

![](https://cdn-learn.adafruit.com/assets/assets/000/021/366/medium800thumb/components_title-anim.jpg?1448313701)

## The Root of the Problem

The single-wire control protocol used by NeoPixels requires a very steady data stream at 800 kilobits per second. There’s a _tiny_ margin for error, but not very much. Bits must be issued at a precisely controlled rate…the Adafruit\_NeoPixel library handles&nbsp;all this behind the scenes, carefully counting the time of each machine code instruction. For every pixel, there’s 24 of _these:_

![](https://cdn-learn.adafruit.com/assets/assets/000/021/333/medium800/components_neopixel-timing.png?1416522996)

Meanwhile, the Arduino is normally using small fractions of time here and there to process _interrupts_…certain events and situations that need to be handled immediately. You usually don’t see it, but **interrupts are occurring&nbsp;_all the time_ behind the scenes.** Your regular sketch code stops, an _interrupt service routine_ is called, and your code then resumes right where it left off.&nbsp;Interrupts help the Arduino’s delay() and millis() functions work, as well as Serial.read(), all manner&nbsp;of things!

![](https://cdn-learn.adafruit.com/assets/assets/000/021/334/medium800/components_interrupt.png?1416523011)

These two concepts cannot coexist.&nbsp;Even a very short and simple interrupt routine will throw off the delicate NeoPixel timing. Therefore, **the NeoPixel library temporarily disables _all_ interrupts** when issuing data, then re-enables them when done.

This is rarely a problem. You might have noticed that millis() and micros() lose time in NeoPixel sketches (the timekeeping interrupt stops whenever&nbsp;we write&nbsp;to the strip), that’s usually the extent of it.

The issue arises that **servos also have very specific timing requirements** of their own, and the **Arduino Servo library uses interrupts to achieve this**.&nbsp;So every time the NeoPixel library turns off interrupts, even for a moment, the servos will lose track of time (and therefore position) and shake unpredictably. _How sad!_

![](https://cdn-learn.adafruit.com/assets/assets/000/021/337/medium800/components_servo-timing.png?1416530419)

One way to address this is to _use other features of the AVR microcontroller_ at the heart of the Arduino to&nbsp;_control the servos without using&nbsp;interrupts,_ as we’ll explain on the next page. This is an&nbsp;advanced topic, but a good thing to learn about at some point. If&nbsp;the explanation is too technical for your current skill level, or if&nbsp;you’d rather&nbsp;use our library instead, it’s okay to skip ahead.

**There are hardware-based workarounds as well** &nbsp;that are much more flexible. Our 16-channel 12-bit PWM/Servo Driver (in both [shield](https://www.adafruit.com/products/1411)&nbsp;and [breakout](https://www.adafruit.com/products/815)&nbsp;formats) offloads the servo control task to a special-purpose&nbsp;chip, so NeoPixels can’t interfere. These boards can “stack” to control dozens (potentially even hundreds) of servos! For complex projects that’s probably the way to go. If you just need a couple servos, a little&nbsp;software&nbsp;might be all that’s needed…

# Using a Different Board?

This guide is specific to **8-bit AVR** -based microcontroller boards like the Arduino Uno. If using a newer 32-bit board with an **ARM Cortex-M0** &nbsp;or **M4** processor (such as the Adafruit Feather M0, Circuit Playground Express or Arduino Zero), we have [a different guide using a different approach](../../../../dma-driven-neopixels/overview). Still others, like ESP32 or nRF, may require different tactics or just might not exhibit the problem at all. This guide focuses on the mainstream AVR boards where it’s a big issue.

# Using NeoPixels and Servos Together

## Introducing AVR Peripherals

![](https://cdn-learn.adafruit.com/assets/assets/000/021/340/medium800/components_avrbanner.png?1416541919)

In normal computer use&nbsp;we usually think of _peripherals_ as things like printers or USB drives.

In the realm of the microcontroller, this same word has a slightly different meaning.&nbsp;A “peripheral” is a small section&nbsp;of the silicon real estate, distinct&nbsp;from but alongside the CPU&nbsp;(the part of the microcontroller that actually processes machine instructions), dedicated to handling some specific task _independent_ from the CPU.

Some of the peripherals of&nbsp;the Arduino’s AVR microcontroller include an&nbsp;_analog-to-digital converter_ (used by the analogRead() function), a _serial UART_ (communicates&nbsp;with a host computer, as when using the Serial library and when transferring code to the chip), _SPI_ (Serial Peripheral Interface, sometimes used for SD card interfacing among other things) and _I2C_ (another chip-to-chip communication method, supported by the Wire library).

Of interest to us at the moment are the **_Timer/Counter_ peripherals** , which precisely measure time intervals and can also be used for pulse-width modulation (PWM, sometimes&nbsp;used for controlling LED brightness or for sound). **PWM output from a timer/counter peripheral can be used to drive a servo without interrupting the CPU.** &nbsp;NeoPixels can coexist!&nbsp;It’s not all roses though…there are some serious limitations…we’ll cover that later.

## Heady Stuff

**Controlling peripherals directly&nbsp;is very different from normal Arduino programming.** For this reason, most are neatly wrapped up in libraries (or the core Arduino library itself, which handles the most oft-used functions like digitalWrite() or analogRead()).

Developing code&nbsp;at this level, one starts with the microcontroller _datasheet_…a&nbsp;massive document detailing every last bit and quantifiable attribute of the chip. Published by (and usually freely downloadable from) the chip manufacturers, these datasheets are unique to every specific chip and variant. For example:

- [ATmega 328P Datasheet](http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf)&nbsp;(Arduino Uno, Adafruit Pro Trinket, etc.). 34.3 MB.
- [ATmega 32U4 Datasheet](http://www.atmel.com/Images/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf)&nbsp;(Arduino Leonardo&nbsp;&&nbsp;Micro, Adafruit FLORA, etc.). 7.5 MB.
- [ATmega 2560 Datasheet](http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf)&nbsp;(Arduino Mega). 8.4 MB.
- [ATtiny85 Datasheet](http://www.atmel.com/Images/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf)&nbsp;(Adafruit Trinket & Gemma). 3.8 MB.

![](https://cdn-learn.adafruit.com/assets/assets/000/021/339/medium800/components_datasheet-front.png?1416541843)

_Yes, it really is 650 pages. Fortunately you don’t need to read it all. But fascinating to skim!_

Peripheral control involves accessing the chip’s _special-function registers,_ a few dozen memory addresses&nbsp;that can be read, written or modified&nbsp;like variables, but each one…often _individual bits_ within each one…control aspects of specific peripherals.

Like variables, the special function registers are referred to by name…these have all been defined in a header file that’s automatically included in your sketch.

The ATmega328P in the Arduino Uno and Adafruit Pro Trinket has three timer/counter units (Timer/Counter0, 1 and 2 — each has its own section in the table of contents). Using the 16 MHz CPU clock as a time base, each can count off intervals anywhere&nbsp;between&nbsp;1 and&nbsp;256 ‘ticks’ — but Timer/Counter1 is of particular interest because it’s a _16-bit counter_…it can count anywhere from 1 to 65,536 ticks, providing lots of extra resolution for this task. The “Register Desription”&nbsp;subsection of the datasheet details each of the special function registers pertaining to Timer/Counter1…the register names and also what each bit controls…

![](https://cdn-learn.adafruit.com/assets/assets/000/021/341/medium800/components_datasheet-annotated.png?1416541954)

The page shown above describes the special function register named TCCR1A and the individual control bits within.&nbsp;All these control bits have assigned names too…each corresponds to a single bit number…0 to 7…and one must remember when writing C code to use either the \_BV(bit) macro or (1 \<\< bit) when identifying&nbsp;bits in the register; multiple bits can be added (+)&nbsp;or&nbsp;OR’d&nbsp;(|) together. Usually several registers need to be configured to get any useful work done.

Here’s a few lines from our servo library (which we’ll download on the next page) showing what this type&nbsp;of code looks like:

```auto
TCCR1A = _BV(WGM11);                           // Mode 14 (fast PWM)
TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS11);  // 1:8 prescale
ICR1   = F_CPU / 8 / 50;                       // ~50 Hz (~20 ms)
```

Barely even looks like Arduino code, does it? If you’ve ever had a sketch make you go “buh?”, chances are it’s&nbsp;directly accessing&nbsp;special function registers.

You’ll need to read the relevant parts of the datasheet to&nbsp;fully understand what’s going on and why, but basically: the first two lines (setting the special function registers TCCR1A and TCCR1B) configure the the Timer/Counter1’s&nbsp;_waveform generation mode_ (“fast PWM” in this case) and set&nbsp;a _prescaler_ — sort of a throttle on the ‘tick’ time — advancing the counter every 8 CPU clock cycles instead of every cycle. The next line (ICR1) sets the&nbsp;timer counter’s upper limit (after which it restarts at zero) and thus the overall PWM period.&nbsp;The bit of math here factors in the&nbsp;CPU frequency in Hz (F\_CPU), prescaler (1:8) and servo pulse frequency (50 Hz) to determine this number…on a 16 MHz Arduino, it would be 16,000,000 ÷&nbsp;8 ÷&nbsp;50 = 40,000 ticks per PWM cycle.

In other parts of the code are lines like these:

```auto
TCCR1A ^= _BV(COM1A1);
OCR1A   = pos;
```

The first line toggles (^ is the XOR operator in C) bit COM1A1 in special-function register TCCR1A. This either enables or disables PWM output on the OC1A pin (which is labeled elsewhere in the datasheet…on the Uno, that’s pin 9). The second line sets the output compare register for this same pin — its&nbsp;PWM duty cycle — to the value contained in variable “pos.”

Obtuse stuff, isn’t it?&nbsp;Take it in small steps. Remember, it’s all just about setting and clearing bits. Very, very, very _specific_ bits. Don’t beat yourself up if something doesn’t work the first time, or second, or the 23rd…a few&nbsp;projects I’ve just had to shelve because I never could&nbsp;make heads or tails of it. **AVR peripherals are among the hardest Arduino things to master** , maybe second only to assembly language. This is why Arduino libraries exist, for the rest of us.

Peripherals are&nbsp;a&nbsp;_huge_&nbsp;subject, much more than be covered here (remember, it’s a 650 page datasheet),&nbsp;but I wanted to provide&nbsp;a high-level explanation of this very low-level concept.

## The Good

The payback for all this hard work?&nbsp;In the case of this library, NeoPixels and servos playing nice together.&nbsp;In the broader sense, _much_ more. Byte for byte, cycle for cycle, **there simply is no better optimization strategy than exploiting the microcontroller’s built-in peripherals** , period. Once configured and set on their way, _zero code_ and _zero instruction_ cycles are spent on the task. Other code then runs while the peripherals do their job; it’s an explicit form of **multitasking**.

There’s a lot more than just PWM and timers…some peripherals offer features not normally exposed by the core Arduino libraries, such as _ADC free-run mode_ used in our [voice changer project](../../../../wave-shield-voice-changer).

## The Bad and The Ugly
 **Performance isn’t everything.** It oftens comes at a cost…in this case, flexibility. Consider:

- Peripherals and special-function registers are _unique to every single make and model_ of microcontroller. To use these is to tie yourself to very specific hardware. Code that performs&nbsp;magic on an Arduino Uno **will not&nbsp;work** on an Arduino Due… **it won’t even compile** …they’re based on&nbsp;altogether different architectures. Our library works on the most common 8-bit AVR microcontrollers, but cutting-edge “Arduino compatibles”&nbsp;aren’t supported (though some of these have entirely different&nbsp;ways of resolving the NeoPixel timing issue).
- Peripherals are an _extremely_ limited resource, much more so than even RAM or code space.&nbsp;There is exactly **ONE** &nbsp;16-bit timer/counter on the Arduino Uno. This can easily lead to **library conflicts** …for example, the WaveHC library (which plays WAV files from an SD card) also relies on Timer/Counter1. It won’t get along with NeoPixels either.
- PWM output from the Timer/Counter units is **limited to&nbsp;a very specific set of pins**. On the Arduino Uno, you can control at most **two** servos this way, and they must be on **pins 9 or 10**. On the Leonardo and Micro, at most **four** servos on **pins 5, 9, 10 or 11**. There is no workaround for this that doesn’t involve interrupts…putting us back at square one.
- The Trinket and Gemma microcontrollers _don’t even have_ a 16-bit timer. With only an 8-bit timer to work with, these are limited to about eight distinct servo positions; smooth continuous motion is not possible.

Early versions of the “official” Arduino Servo library worked exactly as we do here…using PWM output from Timer/Counter1. This was later switched to an interrupt-based technique, with the benefit of supporting many servos on any pins. There was no obvious drawback,&nbsp;NeoPixels weren’t even a _thing_ until recently!

# Using NeoPixels and Servos Together

## The TiCoServo Library

If you just want to&nbsp;download and use the library, that’s totally okay. Please just be aware of the following limitations:

- This **only works on certain 8-bit Arduino-compatible boards**. All the most common hardware&nbsp;with an 8-bit AVR microcontroller should be fine (Arduino Uno, Duemilanove, Leonardo, Mega, Pro Trinket, Teensy 2, etc.). 32-bit boards using other microcontrollers (Arduino Due, Teensy 3, etc.) aren’t covered here as most either don’t have this limitation, or use different solutions.
- On **Trinket and Gemma** , only about **eight distinct servo positions** are possible. (Pro Trinket has full resolution.)
- **Servos only work&nbsp;on very specific pins** :

Boards not mentioned above are likely _not_ supported, even if equipped with an AVR microcontroller. Check the library file known\_16bit\_timers.h to see if a board is mentioned; for example, the more recent _Arduino Nano Every_ isn’t present.

[Click to download Adafruit_TiCoServo library for Arduino](https://github.com/adafruit/Adafruit_TiCoServo/archive/master.zip)
[Click to download Adafruit_NeoPixel library for Arduino](https://github.com/adafruit/Adafruit_NeoPixel/archive/master.zip)
Library installation&nbsp;is a common sticking point for beginners…our&nbsp;[All About Arduino Libraries](../../../../adafruit-all-about-arduino-libraries-install-use)&nbsp;guide explains how this is done.

After installing the libraries, restart the Arduino IDE.

There are two simple examples that mix servos and NeoPixels. One&nbsp;will work on an&nbsp; **Adafruit Gemma or&nbsp;Trinket** , the other&nbsp;on an&nbsp; **Arduino Uno** &nbsp;or most other mainstream boards (Leonardo, etc.). You might need to change some pin numbers (NeoPixel pin #, etc.).

**The library is modeled after the official Arduino Servo library…all functions and arguments are identical, and you can simply [refer to the Arduino site for reference](http://arduino.cc/en/Reference/Servo).**&nbsp;Except for the pin-number limitations, most Arduino Servo sketches should be&nbsp;nearly drop-in compatible with just a few changes:

Instead of:

```auto
#include <Servo.h>
```

use:

```auto
#include <Adafruit_TiCoServo.h>
```

The servo declaration changes from:

```auto
Servo myservo; // create servo object to control a servo
```

to:

```auto
Adafruit_TiCoServo myservo; // create servo object to control a servo
```

The attach(),&nbsp;write() and other functions then operate identically to the standard Servo library counterparts…_unless you’re using a Trinket or Gemma…_

## Special Considerations for Trinket and Gemma

Since they’re based on the diminutive ATtiny85 microcontroller, these boards work a little differently.

First,&nbsp;one extra #include line is needed&nbsp;at the top of the code:

```auto
#include <avr/power.h>
```

Then add the following to the setup() function.&nbsp;It’s important that this appear _before_ calling servo.attach()!

```auto
#if (F_CPU == 16000000L)
  clock_prescale_set(clock_div_1);
#endif
```

Unlike the “big boy” code that works with either degrees or microseconds, the “tiny” version can only specify servo positions in raw “ticks,” where each tick is equal to about 128 microseconds.&nbsp;Given that most servos nominally want a timing pulse between 1,000 and 2,000 microseconds, that means values from 8 to 15 ticks are a reasonable range. Every servo is a little different though…some have more or less range, so you might be okay adjusting these values slightly.

This isn’t the big downer it might seem. Many projects only require&nbsp;two servo positions (e.g. a gate, flag or valve switching between open and closed positions).

With such coarse&nbsp;granularity, degree values&nbsp;are fairly meaningless and thus unsupported.&nbsp;You can use the Arduino map() function if you really want to, but whole ranges will just map to a single value. Better to use raw ticks, since you know every value represents a distinct position, even if they don’t intuitively relate to a simple degree multiplier.


## Related Guides

- [Adafruit NeoPixel Überguide](https://learn.adafruit.com/adafruit-neopixel-uberguide.md)
- [Adafruit Pixel Trinkey](https://learn.adafruit.com/adafruit-pixel-trinkey.md)
- [Clockwork Goggles](https://learn.adafruit.com/gemma-m0-clockwork-goggles.md)
- [Fiber Optic Whip](https://learn.adafruit.com/fiber-optic-whip.md)
- [Superhero Power Gauntlet](https://learn.adafruit.com/superhero-power-gauntlet.md)
- [Adafruit Metro ESP32-S3](https://learn.adafruit.com/adafruit-metro-esp32-s3.md)
- [Crickit Powered Minerva Owl Robot](https://learn.adafruit.com/crickit-powered-owl-robot.md)
- [The Scream: Interactive Screaming Painting](https://learn.adafruit.com/the-scream-munch-screaming-interactive-scream-painting.md)
- [Garden Path Lights with WLED and a Sunset Timer](https://learn.adafruit.com/garden-path-lights-with-sunset-timer.md)
- [Circuit Playground Express Perk-up Ears](https://learn.adafruit.com/perk-up-ears.md)
- [HalloWing Jump Scare Trap](https://learn.adafruit.com/hallowing-jump-scare-trap.md)
- [Green Goblin Pumpkin CPB Ornament](https://learn.adafruit.com/green-goblin-pumpkin-cpb-ornament.md)
- [Gemma Color Touch Pendant Necklace](https://learn.adafruit.com/gemma-color-touch-pendant-necklace.md)
- [Hello World of Robotics with Crickit](https://learn.adafruit.com/hello-world-of-robotics-with-crickit.md)
- [LED Rocket Lamp](https://learn.adafruit.com/led-rocket-lamp.md)
- [Crickit Powered Maker Ice Cream Truck!](https://learn.adafruit.com/crickit-maker-ice-cream-truck.md)
