0

I am playing note tone with CapacitiveSensor and an output of tone like this

void loop() {   
    time_before = millis(); 

    long total1 =  cs_2_3.capacitiveSensor(30);
    long total2 =  cs_2_4.capacitiveSensor(30);


    if((total1>200)||(total2>200)) {

        if(total1>200) {

            tone(12,261); 
            time_after = millis();
            Serial.print("Time: ");
            Serial.println(time_after-time_before);
        }
        if(total2>200) {   
             tone(12,294);   
             time_after = millis();
             Serial.print("Time: ");
             Serial.println(time_after-time_before);
        }
    }
}

How can I read how many seconds I play this note par example

uint128_t
  • 819
  • 5
  • 14

2 Answers2

1

Your code currently will only measure the code execution time and not the duration of the note(s) being played.

You need to follow uint128_t's suggestion and rewrite the code to detect the "button release", at which point you measure the time with millis(), and call noTone(). Only then will you be able to measure the note's duration.

I believe that the source of confusion is that you seem to think that tone() acts like delay() and waits for the note to finish - it does not. tone() merely starts the note and then the next instruction is executed, without waiting for the note to end.

So, using millis() straight after calling tone() will actually only measure the time it takes to execute the tone() statement (and a few if statements - depending on whether you use your original code, or Maximus's code).

Greenonline
  • 3,152
  • 7
  • 36
  • 48
0

Try this:

void loop(){              
    long total1 =  cs_2_3.capacitiveSensor(30);
    long total2 =  cs_2_4.capacitiveSensor(30);    

    if((total1>200)||(total2>200)){

        if(total1>200){
            time_before = millis();
            tone(12,261); 
            time_after = millis();

            Serial.print("Time: ");
            Serial.println(time_after-time_before);
        }

        if(total2>200){ 
            time_before = millis();  
            tone(12,294);   
            time_after = millis();

            Serial.print("Time: ");
            Serial.println(time_after-time_before);
        }
    }
}

Use code indentation if you can. Also, that first OR (||) is unnecessary. I think you need to re-write this, or is this what you wanted?

Greenonline
  • 3,152
  • 7
  • 36
  • 48