How can you sense a closed circuit? I want to have 4 pins with disconnected wires and when touched with a fifth wire play a specific note on a piezo buzzer until disconnected again.

This project loops through several keys and checks whether they are being touched using the Capactive Sensor library. I want to do something similar, but not with capacitive sensing. Alternatively, it may work to have the buzzer always trying to play a note, but only sounds when one of the 4 circuits is close. I'm just not sure how that would work in the code.

Here is their code that uses capactive sensing:

#include <CapacitiveSensor.h>
#include "pitches.h"

#define COMMON_PIN      2    // The common 'send' pin for all keys
#define BUZZER_PIN      A4   // The output pin for the piezo buzzer
#define NUM_OF_SAMPLES  10   // Higher number whens more delay but more consistent readings
#define CAP_THRESHOLD   150  // Capactive reading that triggers a note (adjust to fit your needs)
#define NUM_OF_KEYS     8    // Number of keys that are on the keyboard

// This macro creates a capacitance "key" sensor object for each key on the piano keyboard:
#define CS(Y) CapacitiveSensor(2, Y)

// Each key corresponds to a note, which are defined here. Uncomment the scale that you want to use:
int notes[]={NOTE_C4,NOTE_D4,NOTE_E4,NOTE_F4,NOTE_G4,NOTE_A4,NOTE_B4,NOTE_C5}; // C-Major scale

// Defines the pins that the keys are connected to:
CapacitiveSensor keys[] = {CS(3), CS(4), CS(5), CS(6), CS(7), CS(8), CS(9), CS(10)};

void setup() { 
  // Turn off autocalibrate on all channels:
  for(int i=0; i<8; ++i) {
  // Set the buzzer as an output:

void loop() {    
  // Loop through each key:
  for (int i = 0; i < 8; ++i) {
    // If the capacitance reading is greater than the threshold, play a note:
    if(keys[i].capacitiveSensor(NUM_OF_SAMPLES) > CAP_THRESHOLD) {
      tone(BUZZER_PIN, notes[i]); // Plays the note corresponding to the key pressed

Connect your fifth wire to ground. Set the four inputs to INPUT_PULLUP. The four inputs will default HIGH, and be pulled LOW when connected to the ground wire.

  • Inversely, you can also set the inputs to INPUT_PULLDOWN and have the fifth wire connected to +5v, which will pull the pin HIGH when connected, and LOW when not.
    – Matt Clark
    Oct 22 '14 at 15:59
  • 1
    Assuming you're not using a AVR of course, since those only have pullups. Oct 22 '14 at 16:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.