You'll need to download install the CapacitiveSensor Library.

Open up the Arduino library manager:

Search for capacitivesensor and install it

Code

After downloading and installing the CapacitiveSensor Library, copy and paste the code below into the Arduino IDE. Then, compile and upload it to your Metro (or Metro Express).

/*
 * CIRC20 - Capacitive Sensing with the Metro and Metro M0 Express
 * 
 * by Brent Rubell for Adafruit Industries.     Support Open Source Hardware, Buy Adafruit!
 */
#include <CapacitiveSensor.h>

// piezo speaker pin
int piezoPin = 9;

// 10M resistor between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil if desired
// put a 10M resistor between pins 4 & 2, pin 2 is the sensor pin, 4 is the receiver 
CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);        

void setup()                    
{
   cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);
   Serial.begin(9600);
   // set the piezo as an output
   pinMode(piezoPin, OUTPUT);
}

void loop()                    
{
    long start = millis();
    long pinTone =  cs_4_2.capacitiveSensor(30);

    Serial.print("sensor value: ");        // check on performance in milliseconds
    Serial.print("\t");                    // tab character for debug windown spacing
    Serial.print(pinTone);                  // print sensor output 1
    Serial.print("\n");

    // map the tone value to frequencies between 500 and 2000
    long mapTone = map(pinTone, 0, 40, 500, 2000);
    // play the mapped tone
    playTone(int(mapTone), 100);
    delay(10);
}

void playTone(int tone, int duration) {
  for (long i = 0; i < duration * 1000L; i += tone * 2) {
    digitalWrite(piezoPin, HIGH);
    delayMicroseconds(tone);
    digitalWrite(piezoPin, LOW);
    delayMicroseconds(tone);
  }
}

I'm having problems with this CIRC

Not hearing anything?

Open up the Arduino Serial Monitor. What do you see as the largest sensor value when you press the pin? The smallest? In the lien below, replace the values for MIN_SENSOR_VALUE and MAX_SENSOR_VALUE with the two numeric values you found:

     long mapTone = map(pinTone, MIN_SENSOR_VALUE, MAX_SENSOR_VALUE, 500, 2000);

Getting sensor readings of 0?

When you open the Arduino Serial Monitor, do you see values of 0 or -2? The resistor you're using might be too small. We advise using a 1M Ohm resistor, not the 10K Ohm Resistor. That's one million ohms. If you don't have any 1M Ohm resistors, you can use any other similar (really large) resistor. 

This guide was first published on Aug 18, 2017. It was last updated on Aug 18, 2017.

This page (Code) was last updated on Mar 12, 2021.

Text editor powered by tinymce.