Built-in project · Arduino Uno R3

Arpeggiator on an Arduino Uno

Hold a chord on eight keys and an Uno plays it one note at a time: up, down, up and down or random, at a tempo you set with a knob, with a latch to keep it going. The whole build, an Arduino Uno and 12 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.

Teaching? Assign it to your class in one click.

Intermediate About 40 minutes to build and run. Runs in your browser. Free, and no account needed.

The parts retail for about $34. On Mokxi they're free.

The circuit runs here once the page has loaded.

What you'll learn

  • Sound
  • Controllers
  • Reading a button
  • Reading a knob with an analog pin
  • Difficulty: Intermediate
  • Time: About 40 minutes
  • Board: Arduino Uno R3
  • Parts: 14

How it works

Hold a chord on eight keys and an Uno plays it one note at a time: up, down, up and down or random, at a tempo you set with a knob, with a latch to keep it going.

Arduino Uno R3 runs the sketch below. The circuit around it: Pushbutton, Piezo speaker, Potentiometer. pinMode sets KEY_PIN[k] as an input with its pull-up on. digitalRead reads whether KEY_PIN[k] is HIGH or LOW. analogRead measures the voltage on A1 as a number. Serial.begin opens the serial port at 9600 baud. tone plays a note on PIEZO_PIN.

Parts list

14 parts, plus the jumper wires. They retail for about $34; on Mokxi they're free.

Wiring table

Every connection, pin by pin, read from the circuit itself. Each row joins the pin on the left to the pin on the right, by a jumper wire or a breadboard strip.

Part and pinConnects to
Pushbutton (1) pin 2aArduino Uno R3 pin GND
Pushbutton (2) pin 2aArduino Uno R3 pin GND
Pushbutton (3) pin 2aArduino Uno R3 pin GND
Pushbutton (4) pin 2aArduino Uno R3 pin GND
Pushbutton (5) pin 2aArduino Uno R3 pin GND
Pushbutton (6) pin 2aArduino Uno R3 pin GND
Pushbutton (7) pin 2aArduino Uno R3 pin GND
Pushbutton (8) pin 2aArduino Uno R3 pin GND
Pushbutton (9) pin 2aArduino Uno R3 pin GND
Pushbutton (10) pin 2aArduino Uno R3 pin GND
Pushbutton (10) pin 1aArduino Uno R3 pin 12
Pushbutton (9) pin 1aArduino Uno R3 pin 11
Piezo speaker pin 1Arduino Uno R3 pin 10
Pushbutton (8) pin 1aArduino Uno R3 pin 9
Pushbutton (7) pin 1aArduino Uno R3 pin 8
Pushbutton (6) pin 1aArduino Uno R3 pin 7
Pushbutton (5) pin 1aArduino Uno R3 pin 6
Pushbutton (4) pin 1aArduino Uno R3 pin 5
Pushbutton (3) pin 1aArduino Uno R3 pin 4
Pushbutton (2) pin 1aArduino Uno R3 pin 3
Pushbutton (1) pin 1aArduino Uno R3 pin 2
Potentiometer pin 3Arduino Uno R3 pin 5V
Piezo speaker pin 2Arduino Uno R3 pin GND
Potentiometer pin 1Arduino Uno R3 pin GND
Potentiometer pin 2Arduino Uno R3 pin A0

The code

The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.

sketch.ino · Arduino Uno R3
// Arpeggiator: hold a chord and hear it played one note at a time.
//
// Wiring:
//   keys    pins 2 to 9, each to GND (C D E F G A B C)
//   mode    pin 11 to GND: up, down, up and down, random
//   latch   pin 12 to GND: keep playing after you let go of the keys
//   tempo   potentiometer wiper -> A0, ends to 5 V and GND
//   piezo   pin 10 -> piezo -> GND
//
// An arpeggio is a chord played as a run of notes instead of all at once. The
// keys you hold are the chord; each step of the clock plays the next note of it.
// Hold C, E and G and "up" plays C E G C E G, "down" plays G E C, "up and down"
// plays C E G E C E G..., and "random" picks any held note each step.
//
// The clock is a pair of times, the next step and the end of the note, so the
// keys are read all the time and the tempo can change in the middle of a
// phrase. Each step is a sixteenth note and the note sounds for 70% of it,
// which leaves a tiny gap so repeated notes are heard as separate notes.
//
// The latch button turns the held keys into a toggle: while latch is on, the
// chord stays when you let go, and the next key you press starts a new chord.
//
// Things to try. Hold three keys and change the mode. Turn the knob while it
// plays. Latch a chord and keep your hands free.

const uint8_t KEYS = 8;
const uint8_t KEY_PIN[KEYS] = {2, 3, 4, 5, 6, 7, 8, 9};
const uint16_t NOTE_HZ[KEYS] = {262, 294, 330, 349, 392, 440, 494, 523};
const char *const NOTE_NAME[KEYS] = {"C4", "D4", "E4", "F4", "G4", "A4", "B4", "C5"};
const uint8_t PIEZO_PIN = 10;
const uint8_t MODE_PIN = 11;
const uint8_t LATCH_PIN = 12;

enum Mode : uint8_t { UP, DOWN, UPDOWN, RANDOM, MODES };
const char *const MODE_NAME[MODES] = {"up", "down", "up and down", "random"};

uint8_t mode = UP;
bool latched = false;
uint8_t chord = 0;       // bit k is key k
uint8_t lastKeys = 0;    // the keys down on the last pass, for new-chord detection
int8_t current = -1;     // the key played last
int8_t direction = 1;    // for up and down
uint32_t nextStep = 0;
uint32_t noteOff = 0;
bool sounding = false;

// button edges
bool modeWas = false, latchWas = false;
uint32_t modeAt = 0, latchAt = 0;

static uint8_t keysDown()
{
  uint8_t down = 0;
  for (uint8_t k = 0; k < KEYS; k++) {
    if (digitalRead(KEY_PIN[k]) == LOW) {
      down |= 1 << k;
    }
  }
  return down;
}

static bool pressed(uint8_t pin, bool &was, uint32_t &at)
{
  bool down = digitalRead(pin) == LOW;
  uint32_t now = millis();
  if (down != was && now - at > 20) {
    was = down;
    at = now;
    return down;
  }
  return false;
}

// The next held key above (dir = 1) or below (dir = -1) `from`, or -1.
static int8_t neighbor(int8_t from, int8_t dir)
{
  for (int8_t k = from + dir; k >= 0 && k < KEYS; k += dir) {
    if (chord & (1 << k)) {
      return k;
    }
  }
  return -1;
}

static int8_t lowest()
{
  for (int8_t k = 0; k < KEYS; k++) {
    if (chord & (1 << k)) {
      return k;
    }
  }
  return -1;
}

static int8_t highest()
{
  for (int8_t k = KEYS - 1; k >= 0; k--) {
    if (chord & (1 << k)) {
      return k;
    }
  }
  return -1;
}

// Which key to play next, given the mode and the key played last.
static int8_t pick()
{
  if (chord == 0) {
    return -1;
  }
  int8_t next;
  switch (mode) {
    case UP:
      next = current < 0 ? lowest() : neighbor(current, 1);
      return next < 0 ? lowest() : next;
    case DOWN:
      next = current < 0 ? highest() : neighbor(current, -1);
      return next < 0 ? highest() : next;
    case UPDOWN:
      if (current < 0) {
        direction = 1;
        return lowest();
      }
      next = neighbor(current, direction);
      if (next < 0) {
        // turn round at the end, without playing the end note twice
        direction = -direction;
        next = neighbor(current, direction);
        if (next < 0) {
          next = current;  // a chord of one note
        }
      }
      return next;
    default: {
      uint8_t count = 0;
      for (uint8_t k = 0; k < KEYS; k++) {
        count += (chord >> k) & 1;
      }
      uint8_t n = random(0, count);
      for (uint8_t k = 0; k < KEYS; k++) {
        if ((chord >> k) & 1) {
          if (n == 0) {
            return k;
          }
          n--;
        }
      }
      return lowest();
    }
  }
}

void setup()
{
  Serial.begin(9600);
  for (uint8_t k = 0; k < KEYS; k++) {
    pinMode(KEY_PIN[k], INPUT_PULLUP);
  }
  pinMode(MODE_PIN, INPUT_PULLUP);
  pinMode(LATCH_PIN, INPUT_PULLUP);
  pinMode(PIEZO_PIN, OUTPUT);
  randomSeed(analogRead(A1));
  Serial.println("Arpeggiator ready: mode up");
}

void loop()
{
  uint32_t now = millis();
  uint8_t down = keysDown();

  if (pressed(MODE_PIN, modeWas, modeAt)) {
    mode = (mode + 1) % MODES;
    direction = 1;
    current = -1;  // each mode starts from its own end of the chord
    Serial.print("Mode ");
    Serial.println(MODE_NAME[mode]);
  }
  if (pressed(LATCH_PIN, latchWas, latchAt)) {
    latched = !latched;
    Serial.println(latched ? "Latch on" : "Latch off");
    if (!latched) {
      chord = down;
    }
  }

  if (latched) {
    // a key pressed after everything was let go starts a new chord
    if (down != 0 && lastKeys == 0) {
      chord = 0;
    }
    chord |= down;
  } else {
    chord = down;
  }
  lastKeys = down;

  // sixteenth notes: a quarter of a beat, 100 to 300 BPM
  uint16_t bpm = 100 + (uint16_t)((analogRead(A0) * 200UL) / 1023);
  uint32_t stepMs = 15000UL / bpm;

  if (sounding && now >= noteOff) {
    noTone(PIEZO_PIN);
    sounding = false;
  }
  if (now >= nextStep) {
    nextStep += stepMs;
    if (nextStep < now) {
      nextStep = now + stepMs;  // we fell behind (nothing was held): start fresh
    }
    int8_t key = pick();
    if (key >= 0) {
      current = key;
      tone(PIEZO_PIN, NOTE_HZ[key]);
      sounding = true;
      noteOff = now + stepMs * 7 / 10;
      Serial.print("Arp ");
      Serial.print(NOTE_NAME[key]);
      Serial.print(" ");
      Serial.print(bpm);
      Serial.println(" BPM");
    } else {
      current = -1;
      direction = 1;
    }
  }
}

Code walkthrough

The key functions of the sketch, and what each one does.

setup sketch.ino

Runs once when the board starts. It gets the pins and libraries ready.

void setup()
{
  Serial.begin(9600);
  for (uint8_t k = 0; k < KEYS; k++) {
    pinMode(KEY_PIN[k], INPUT_PULLUP);
  }
  pinMode(MODE_PIN, INPUT_PULLUP);
  pinMode(LATCH_PIN, INPUT_PULLUP);
  pinMode(PIEZO_PIN, OUTPUT);
  randomSeed(analogRead(A1));
  Serial.println("Arpeggiator ready: mode up");
}

loop sketch.ino

Runs over and over for as long as the board has power. This is where the project does its work.

void loop()
{
  uint32_t now = millis();
  uint8_t down = keysDown();

  if (pressed(MODE_PIN, modeWas, modeAt)) {
    mode = (mode + 1) % MODES;
    direction = 1;
    current = -1;  // each mode starts from its own end of the chord
    Serial.print("Mode ");
    Serial.println(MODE_NAME[mode]);
  }
  if (pressed(LATCH_PIN, latchWas, latchAt)) {
    latched = !latched;
    Serial.println(latched ? "Latch on" : "Latch off");
    if (!latched) {
      chord = down;
    }
  }

  if (latched) {
    // a key pressed after everything was let go starts a new chord
    if (down != 0 && lastKeys == 0) {
      chord = 0;
    }
    chord |= down;
  } else {
    chord = down;
  // ... 33 more lines in the editor

Troubleshooting

The usual mistakes with this circuit, and the fix for each.

  • The input reads random HIGH and LOW when the button is not pressed. Pushbutton
    A floating pin picks up noise. Add a 10 k pull-down or pull-up resistor, or use INPUT_PULLUP and wire the button between the pin and GND. Then pressed reads LOW.
  • The button seems always pressed, or never changes. Pushbutton
    A 4-leg tactile switch has legs joined in pairs. Place it across the breadboard center gap so the pairs sit on different rows. Wired along one side, the legs are already connected.
  • A passive piezo stays silent when you just set the pin HIGH. Piezo speaker
    A passive piezo needs a changing signal. Use tone(pin, frequency) or a PWM wave. Around 2 to 4 kHz is loudest. A buzzer with a built in oscillator makes sound from plain DC instead.
  • Sound is very quiet or the pin seems overloaded. Piezo speaker
    Drive the piezo from a pin directly, or through a 100 ohm resistor. For a bigger buzzer, switch it with a transistor. Check that you wired the right two legs and joined grounds.
  • The reading jumps around or only covers part of the range. Potentiometer
    Wire the two outer legs to 5 V and ground and the middle leg (the wiper) to an analog pin. Using the wrong two legs gives a dead or partial range.
  • Turning the knob does nothing, or the value is stuck at 0 or 1023. Potentiometer
    Check that the wiper goes to an analog input (A0 to A5 on an Uno), not a digital pin. Make sure both ends are connected, since a floating end gives noise.
  • Upload fails or nothing runs after wiring pins 0 and 1 to a module. Arduino Uno R3
    Pins 0 and 1 are the USB serial port. Move the module to other pins, or unplug it while uploading. Also check the right board is selected.
  • Pins misbehave or the board resets when you power motors or servos from it. Arduino Uno R3
    Each I/O pin gives about 20 mA, 40 mA max. Power motors and servos from their own supply and join its ground to the Uno's GND.

Change it and keep it

Open it in the editor, change the circuit or the code, and keep your version in a free account.