As with most of my projects these days, I used CircuitPython for this. Are you new to using CircuitPython? No worries, there is a full getting started guide here.

Adafruit suggests using the Mu editor to edit your code and have an interactive REPL in CircuitPython. You can learn about Mu and installation in this tutorial.

We'll go through the code, piece by piece, starting with the imports and setup.

Download: file
import time
from math import ceil
import board
import rotaryio
import neopixel
from adafruit_debouncer import Debouncer
import digitalio
import pulseio

# Setup the hardware

encoder = rotaryio.IncrementalEncoder(board.D9, board.D7)
button_io = digitalio.DigitalInOut(board.D10)
button_io.direction = digitalio.Direction.INPUT
button_io.pull = digitalio.Pull.UP
button = Debouncer(button_io)
strip = neopixel.NeoPixel(board.D11, 16, brightness=1, auto_write=False)

Here the rotary encoder is set up using the new built-in support for the rotation of the switch and I use my debouncer library to clean up the encoder push switch. Finally the NeoPixel strip is configured. If you are unfamiliar with NeoPixels, there is a great guide on them.

Now let's jump to the main loop:

Download: file
strip.fill(0x000000)
strip.show()
work_time = 6
break_time = 2
time_to_check = 0
state = False
mode, dial_color, time_remaining, increment = compute_mode_settings(True)

while True:
    # check whether the rotary encoder has been pushed. If so enter time-set mode.
    button.update()
    if button.fell:
        work_time = set_timer(0x400000, work_time)
        break_time = set_timer(0x004000, break_time)
        strip.fill(0x000000)
        strip.show()
        mode, dial_color, time_remaining, increment = compute_mode_settings(True)

    now = time.monotonic()
    if now >= time_to_check:          #only check each second
        time_remaining -= 1
        if time_remaining <= 0:       # time to switch modes?
            strip.fill(0x000000)      # clear the dial
            strip.show()              # make some noise
            beep(2, 0.5, 0.25, 4000)
            mode, dial_color, time_remaining, increment = compute_mode_settings(not mode)
        state = not state             # have the top pixel toggle between the dial color and white
        show_time(dial_color, ceil(time_remaining / increment), state)   #update the dial
        time_to_check = now + 1.0

Each time through the loop, it checks for a push on the encoder switch. That's the job of the debouncer's update function. If one was detected (i.e. the button signal went from high to low... it fell) the code enters the mode to set the length of the work phase, followed by the break phase, then back to timing mode.

The next step checks to see if it's time to update the timer. It does this every second (as defined by the last line). So once a second, the time remaining is decreased by 1 (second) and the ring is updated. If it reaches 0, it's time to make some noise and change mode.

In addition to the setup and loop there are a handful of helper functions.

Download: file
last_position = 0

def check_encoder():
    global last_position
    position = encoder.position
    if position > last_position:
        direction = 1
    elif position < last_position:
        direction = -1
    else:
        direction = 0
    last_position = position
    return direction

The check_encoder function tracks the position of the encoder, comparing it to the last known position. Based on that comparison it returns -1, 0, or 1 to indicate that the encoder rotated counter-clockwise, didn't move, or rotated clockwise.

Download: file
def show_time(color, value, bright):
    strip.fill(0x000000)
    if value > 0:
        for i in range(1, value + 1):
            strip[16 - i] = color
        if bright:
            strip[16 - value] = 0x404040
    strip.show()

The show_time function updates the time displayed on the NeoPixel ring. It sets pixels to the specified color starting at pixel zero (which is at the bottom of the ring in the final build) and moving clockwise. The final pixel is handled differently. Depending on the bright parameter, it's either set to the same color as the rest, or white. In the main loop we saw that this value gets toggled each second. The result is that the highest pixel blinks.

Note that for the work and break times, each pixel is worth a different number of seconds. This is because it's typical for the work phase to be a half hour, an hour, or longer, while the break phase is usually between five and fifteen minutes. To give a better, brighter display, I decided to use a different scale for each. This is all adjustable in the compute_mode_settings function:

Download: file
def compute_mode_settings(new_mode):
    work_time_increment = 600   # each work phase pixel is worth 10 minutes
    break_time_increment = 300  # each break phase pixel is worth 5 minutes

    if new_mode:
        return True, 0x400000, work_time * work_time_increment, work_time_increment
    else:
        return False, 0x004000, break_time * break_time_increment, break_time_increment

Depending on which mode is being entered, the appropriate set of values is returned. These are used to update the variables in the loop (see above).

When there's a switch from one phase to the next, we use the piezo buzzer and pulseio to make some noise. The beep function does that:

Download: file
def beep(count, duration, interstitial, freq):
    pwm = pulseio.PWMOut(board.D12, duty_cycle = 0, frequency=freq)
    for _ in range(count):
        pwm.duty_cycle = 0x7FFF
        time.sleep(duration)
        pwm.duty_cycle = 0
        time.sleep(interstitial)
    pwm.deinit()

This is straightforward. It sets up the pulse-width modulation (PWM), loops for the number of beeps requested, and shuts down the PWM. For each beep it sets the duty cycle to 50%, waits for the beep duration, sets the duty cycle to 0% (effectively turning of the sound), then waits for the interstitial duration before playing the next beep (if any).

Next is maybe the most interesting function.

Download: file
def set_timer(color, value):
    global last_position
    time_setting = value
    last_position = encoder.position
    for i in range(16):
        strip[i] = color
        strip.show()
    for i in range(16):
        strip[i] = 0x000000
        strip.show()
    while True:
        show_time(color, time_setting, False)
        button.update()
        if button.fell:
            return time_setting
        direction = check_encoder()
        time_setting += direction
        if time_setting > 16:
            time_setting = 16
        if time_setting < 0:
            time_setting = 0

To start, it initializes from the current encoder position and flashes the ring. Following that there's a loop that shows the current setting (using the show_time function we looked at above) and checks the encoder push switch. If it was pressed the current setting is returned. Otherwise the encoder's rotation is checked and the time setting changed based on the result. Finally the time setting is capped at 0 and 16, which reflects the size of the ring.

That's it. Each piece is fairly simple, but the overall functionality is interesting and useful. Below is all of it, with comments.

"""
The MIT License (MIT)

Copyright (c) 2018 Dave Astels

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
# pylint: disable=global-statement

import time
from math import ceil
import board
import rotaryio
import neopixel
from adafruit_debouncer import Debouncer
import digitalio
import pulseio

# Setup the hardware

encoder = rotaryio.IncrementalEncoder(board.D9, board.D7)
button_io = digitalio.DigitalInOut(board.D10)
button_io.direction = digitalio.Direction.INPUT
button_io.pull = digitalio.Pull.UP
button = Debouncer(button_io)
strip = neopixel.NeoPixel(board.D11, 16, brightness=1, auto_write=False)

last_position = 0

def check_encoder():
    """Check if the encoder has been rotated.
    returns the direction (-1 or +1) if it has, 0 if not.
    """

    global last_position
    position = encoder.position
    if position > last_position:
        direction = 1
    elif position < last_position:
        direction = -1
    else:
        direction = 0
    last_position = position
    return direction


def show_time(color, value, bright):
    """Show remaining time on the ring.
    :param int color: the RGB value to use
    :param int value: how many pixels to light
    :param boolean bright: whether the highest pixel should be brighter (i.e white)
    """
    strip.fill(0x000000)
    if value > 0:
        for i in range(1, value + 1):
            strip[16 - i] = color
        if bright:
            strip[16 - value] = 0x404040
    strip.show()


def set_timer(color, value):
    """Set a time remaing value
    :param int color: the color to use on the ring
    :param int value: the initial value (number of pixels to light)
    Returns the new setting
    """
    global last_position
    time_setting = value
    last_position = encoder.position
    for i in range(16):
        strip[i] = color
        strip.show()
    for i in range(16):
        strip[i] = 0x000000
        strip.show()
    while True:
        show_time(color, time_setting, False)
        button.update()
        if button.fell:
            return time_setting
        direction = check_encoder()
        time_setting += direction
        if time_setting > 16:
            time_setting = 16
        if time_setting < 0:
            time_setting = 0


def beep(count, duration, interstitial, freq):
    """Make some noise
    :param int count: the number of beeps to make
    :param float duration: the length (in seconds) of each beep
    :param float interstitial: the length (in seconds) of the silence between beeps
    :param int freq: the frequency of the beeps
    """
    pwm = pulseio.PWMOut(board.D12, duty_cycle = 0, frequency=freq)
    for _ in range(count):
        pwm.duty_cycle = 0x7FFF
        time.sleep(duration)
        pwm.duty_cycle = 0
        time.sleep(interstitial)
    pwm.deinit()


def compute_mode_settings(new_mode):
    """Compute settings for a new mode
    :param boolean new_mode: the new mode
    Returns
      boolean mode       - the new mode
      int dial_color     - the dial color for the new mode
      int time_remaining - the initial time-remaining for the new mode
      int increment      - the pixel increment for the new mode
    """
    work_time_increment = 600
    break_time_increment = 300

    if new_mode:
        return True, 0x400000, work_time * work_time_increment, work_time_increment
    else:
        return False, 0x004000, break_time * break_time_increment, break_time_increment


# Initialize things

strip.fill(0x000000)
strip.show()
work_time = 6
break_time = 2
time_to_check = 0
state = False
mode, dial_color, time_remaining, increment = compute_mode_settings(True)

# The main loop

while True:
    # check whether the rotary encoder has been pushed. If so enter time-set mode.
    button.update()
    if button.fell:
        work_time = set_timer(0x400000, work_time)
        break_time = set_timer(0x004000, break_time)
        strip.fill(0x000000)
        strip.show()
        mode, dial_color, time_remaining, increment = compute_mode_settings(True)

    now = time.monotonic()
    if now >= time_to_check:          #only check each second
        time_remaining -= 1
        if time_remaining <= 0:       # time to switch modes?
            strip.fill(0x000000)      # clear the dial
            strip.show()              # make some noise
            beep(2, 0.5, 0.25, 4000)
            mode, dial_color, time_remaining, increment = compute_mode_settings(not mode)
        state = not state             # have the top pixel toggle between the dial color and white
        show_time(dial_color, ceil(time_remaining / increment), state)   #update the dial
        time_to_check = now + 1.0
This guide was first published on Jul 02, 2018. It was last updated on Jul 02, 2018. This page (Code) was last updated on Jan 05, 2019.