Arduino Forum

Using Arduino => Project Guidance => Topic started by: ndivuyo on Jan 11, 2019, 10:49 pm

Title: CapSense + Tone
Post by: ndivuyo on Jan 11, 2019, 10:49 pm
Hey all. I am using CapacitiveSensor library in combo with the tone() function on n Arduino Nano for some simple touch to tones. Tone() on its own works fine, but when combined with CapSense it becomes very quite and quality degraded. I also hear lots of clicking from the speaker from the capacitive sensing. Any ideas how I can at least get the normal tone volume? Just to clarify I am using the tone() function and not the Tone library (though I would love to use the Tone library but it seems it conflicts with the CapSense library and won't compile)

Thank you!
Title: Re: CapSense + Tone
Post by: ndivuyo on Jan 11, 2019, 11:26 pm
HEre is the code if helpful, just ignore the tone() part for now because I was in the middle of trying different things:

Code: [Select]
#include <CapacitiveSensor.h>
//#include <Tone.h>

struct Cap {
  CapacitiveSensor*  sensor;
  int pin;
  int outPin;
  int val;
  int thresh;
  int note;
  int raw;
  int noteIndex = 0;
  //Tone osc;
  Cap(int pin_, int outPin_, int thresh_, int note_) {
    pin = pin_;
    outPin = pin;
    sensor = new CapacitiveSensor(4, pin);
    thresh = thresh_;
    note = note_;
  void readVal() {
    int lastVal = val;
    raw = sensor->capacitiveSensor(1);
    //raw = analogRead(pin);
    val = raw >= thresh;
    if (val && !lastVal) {
      tone(outPin, note);
    } else noTone(outPin);
Cap* caps[3];
int pins[] = {2,5,6};
int notes[] = {220, 440, 880};
int outPins[] = {9,9,9};

void setup() {
  for (int i = 0; i < 3; ++i) {
    caps[i] = new Cap( pins[i], outPins[i], 30, notes[i] );

void loop() {
  for (int i = 0; i < 3; ++i) {
    Serial.print(" ");
Title: Re: CapSense + Tone
Post by: DrDiettrich on Jan 12, 2019, 01:03 am
Capacitive sensing typically uses blocking code, that interferes with other code.

You also seem to create too many objects dynamically. Try to use an array of sensors and initialize it statically.
Title: Re: CapSense + Tone
Post by: wvmarle on Jan 12, 2019, 07:17 pm
Tone uses timer2 to produce the tones, and should have no problem with blocking code.
CapacitiveSensor library doesn't seem to use timers, so from the face of it no interference.
Title: Re: CapSense + Tone
Post by: Grumpy_Mike on Jan 12, 2019, 07:31 pm
just ignore the tone() part for now because .....
Given that is the part of the code tat is giving you problems we need to see a valid attempt at what you are trying to do and failing.