This project uses the on-board microphone of the Circuit Playground Express's to trigger a pair of servo actuated costume ears to perk up when there is a loud noise. The ears are mounted on a hair band and the whole thing is completely self-contained. 

Parts

This project uses a Circuit Playground Express, 2 servos, and a LiPo battery. Any size battery can be used, but the 1200 mAh model is a good balance between size and lifespan.

Circuit Playground Express
Circuit Playground Express is the next step towards a perfect introduction to electronics and programming. We've taken the original Circuit Playground Classic and...
$24.95
In Stock
Micro servo
Tiny little servo can rotate approximately 180 degrees (90 in each direction), and works just like the standard kinds you're used to but smaller. You can use any servo...
$5.95
In Stock
Lithium Ion Polymer Battery - 3.7v 1200mAh
Lithium ion polymer (also known as 'lipo' or 'lipoly') batteries are thin, light and powerful. The output ranges from 4.2V when completely charged to 3.7V. This battery...
Out of Stock
Small Alligator Clip to Male Jumper Wire Bundle - 6 Pieces
When working with unusual non-header-friendly surfaces, these handy cables will be your best friends! No longer will you have long, cumbersome strands of alligator clips. These...
Out of Stock
Plastic Pop Rivets for Cardboard Crafts (20-pack)
Enter the world of cardboard construction and build playful robot friends! Instead of slapping on tape or waiting for your hot glue to warm up, you can use these...
$4.50
In Stock

Supplies

  • Headband
  • Construction paper
  • Corrugated cardboard
  • Hot glue and glue gun
  • 2 rubber bands of an appropriate size
  • Felt, faux fur, or fabric as desired to cover the ears
  • Jumper wire with male pins if you want to solder to the CPX for a more robust connection
  • flexible/stranded wire to use as an actuator
  • 4 pieces of stiff wire (long male header pins work well) and wire to mechanically connect the servo 

The diagram below shows alligator clip wires being used to connect the servos, and this is fine for prototyping. But if you want things to be more robust some solder is probably going to be involved. You can cut male jumpers just long enough to reach the required pads on the Circuit Playground Express, coming together at the servo plug and solder them in place.  For something even more permanent, you can trim the servo cables and solder them directly onto the Circuit Playground Express.

Designing the ears

The first step is to make some ears from cardboard. You can experiment with shapes using construction paper. It's thin enough to be easy to work with, and still stiff enough to keep it's shape when folded. Once you have a design you like, it can be a template for markign the design on the corrugated cardboard.

In this case the square edges are 4cm long. The tip of the ear is 1 cm (3/8") wide, with 1.5 cm (5/8") on either side..

The construction paper prototype can be used as a template to mark out the design on cardboard. Mark them out with the corrugations running from the tip down the length of the piece with the two wings to the sides. 

 

The dotted lines are cut part way though, leaving the bottom outside layer. These are the fold lines.

Aside: Reinforced corner joints

Folding the ear results in the bottom and sides meeting along the edges of the cuts. That means there's nothing to glue to. Although hotglue provides some structure itself, it's nice to have a bit more support for the joint. You can do this by cutting a matchstick shaped piece of cardboard to glue inside the corner. That lets each surface (the bottom and side in this case) be glued to this support.

 

All three concave corners can benefit from a bead of hot glue to enhance the bond as well as provide additional structural support. Allow each bead to cool before adding the next or the heat may cause the entire joint to come apart.

The first step is to fold and glue the ears. You can use the method outlined above.

 

Glue a small piece of plastic straw to the middle of the base of the flap to be a guide for the actuating wire.

 

Next glue a servo to the back of each ear as shown: as far down and to the left as possible while still not protruding past the bottom or side of the ear. Consider peeling the foil label from the side of the servo being glued to the ear so that it won't later come off on its own.

 

Poke a small hole near the end of the flap and place a rivet in it. Put the plate on the rivet, but only to the first position. You'll tighten it later. Make a similar hole near the middle of the back of the base.

 

Place a rubber band around the flap rivet as shown. Use a rubber band that is taunt when the flap is extended and has enough strength to pull the flap back when it is released. Poke the other end of the rubber band through the hole in the base so that 2 mm (1/8") sticks through, then push the rivet through it from the top. Place the plate on the rivet and push it on to the second notch.

Connecting the servos

Connect the servos to a board and set them to 0 degrees.  Put a "half" horn (see the photos to the left) onto the shaft so that it faces up.

 

Next you need to link the horn to the ear flap.  You can use a short piece of wire looped around the rivet at the end of the flap and through the straw guide. The ends can be soldered to a small hook made from a pin from a male header strip bent around the tip of needle-nosed pliers.

 

To connect the hook to the servo horn, make a loop from another, longer header pin and place it through the outermost hole in the horn. Squeeze the loop closed.  Hook the hook on the wire through the loop on the horn and squeeze it closed. That will keep it from slipping out when the servo horn point up (and allowing the connecting wire to go slack).

 

The goal is that when the servo is set to 90 degrees the flap is pulled vertical. When the servo goes back to zero degrees, the rubber band pulls the flap back down into the relaxed position.

Covering the mechanism

Now you have working ears. Let's make them look a bit better. You can use any sort of fabric to cover them, felt on the inside and fur on the back would be awesome, but here we just use some felt to keep it easy to see what's going on.

 

Start by cutting an outside piece for each ear. The exact shape isn't overly important; it has to be big enough to accommodate the servo and the motion of the flap, but not so big as to completely obscure the overall ear shape. Secure the corners as shown to the flap rivet, and the front corners of the base.

 

Cut a similar piece for the inside of the ear. It only has to allow for the flap movement.  Tack the corners to the same points as the outside fabric, only on the inside of the ear. Then apply glue along the inside edges of the outside piece, and secure the edges of the inside piece. The final two photos show the result.

Final assembly

All that's left is to mount the two ears, the Circuit Playground Express, and the battery to a headband. Hot glue works well with the ears, while double sided tape will work for the board and battery.

We'll be using CircuitPython for this project. 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 its installation in this tutorial.

The code is based on this guide on CircuitPython audio for the Circuit Playground Express.

A PDMIn object is created to read sound levels from the mic, which are stored in the array named samples. Those samples are then combined using root-mean-square to get a measure of the amount of energy in the sound (which corresponds to the overall volume) and mapped onto a logarithmic scale from 0 to 10. If that results in a value greater than or equal to the trigger threshold (defined by THRESHOLD) the ears perk up. If it's less than THRESHOLD, the ears relax.

Beyond the above, the code only perks up or relaxes the ears the first time the sound is louder or quieter than the threshold. The state variable ears_up tracks the state of the ears (True represents perked up). So the ears will perk up only when the sound is loud enough and the ears are relaxed. If the sound is quiet and the ears are perked up, they will relax.

Why the extra code? To manage a cool off period of a second after the state of the ears changes. The code sleeps for that time and doesn't check the sound. This helps avoid the ears fluttering when the sound level is around the threshold. It also keeps the ears perked up for a second which enhances the effect.

"""
Circuit Playground Express sounds activated ears.

Adafruit invests time and resources providing this open source code.
Please support Adafruit and open source hardware by purchasing
products from Adafruit!

Written by Dave Astels for Adafruit Industries
Copyright (c) 2018 Adafruit Industries
Licensed under the MIT license.

All text above must be included in any redistribution.
"""

import time
import math
import array
import board
import audiobusio
import pwmio
from adafruit_motor import servo
from adafruit_circuitplayground.express import cpx

# Exponential scaling factor.
# Should probably be in range -10 .. 10 to be reasonable.
CURVE = 2
SCALE_EXPONENT = math.pow(10, CURVE * -0.1)

# Number of samples to read at once.
NUM_SAMPLES = 90

# the trigger threshhold
THRESHOLD = 6
left_pwm = pwmio.PWMOut(board.A1, frequency=50)
right_pwm = pwmio.PWMOut(board.A2, frequency=50)

left_ear = servo.Servo(left_pwm)
right_ear = servo.Servo(right_pwm)

cpx.pixels.fill((0, 0, 0))
left_ear.angle = 0
right_ear.angle = 0

# Restrict value to be between floor and ceiling.

def constrain(value, floor, ceiling):
    return max(floor, min(value, ceiling))


def log_scale(input_value, input_min, input_max, output_min, output_max):
    normalized_input_value = (input_value - input_min) / \
                             (input_max - input_min)
    return output_min + \
        math.pow(normalized_input_value, SCALE_EXPONENT) \
        * (output_max - output_min)


# Remove DC bias before computing RMS.

def normalized_rms(values):
    minbuf = int(mean(values))
    samples_sum = sum(
        float(sample - minbuf) * (sample - minbuf)
        for sample in values
    )

    return math.sqrt(samples_sum / len(values))


def mean(values):
    return sum(values) / len(values)


mic = audiobusio.PDMIn(board.MICROPHONE_CLOCK, board.MICROPHONE_DATA,
                       sample_rate=16000, bit_depth=16)


# Record an initial sample to calibrate. Assume it's quiet when we start.
samples = array.array('H', [0] * NUM_SAMPLES)
mic.record(samples, len(samples))
# Set lowest level to expect, plus a little.
input_floor = normalized_rms(samples) + 10

# Corresponds to sensitivity: lower means ears perk up at lower volumes
# Adjust this as you see fit.
input_ceiling = input_floor + 750

ears_up = False

while True:
    samples_read = mic.record(samples, len(samples))
    if samples_read < NUM_SAMPLES:
        print("MISSING SAMPLES, only: {0}".format(samples_read))
    magnitude = normalized_rms(samples)
    # You might want to print this to see the values.
    # print(magnitude)

    # Compute scaled logarithmic reading in the range 0 to 10
    c = log_scale(constrain(magnitude, input_floor, input_ceiling),
                  input_floor, input_ceiling, 0, 10)


    if c >= THRESHOLD and not ears_up:
        ears_up = True
        left_ear.angle = 90
        right_ear.angle = 90
        time.sleep(1.0)
    elif c < THRESHOLD and ears_up:
        ears_up = False
        left_ear.angle = 0
        right_ear.angle = 0
        time.sleep(1.0)
    else:
        time.sleep(0.1)

This guide describes a project to build a set of costume ears that will perk up when there's a loud noise. The final construction was quite basic, but could be incorporated into a more elaborate headpiece of, say, a werewolf costume.

It could also be the basis of a steampunk gadget that reacts to sound.

Have fun!

This guide was first published on Aug 22, 2018. It was last updated on Aug 22, 2018.