0

My problem is I want the buzzer to stop after a certain amount of time, regardless if it is still pressed or not.

I have tried to implement a boolean statement to the code but to no avail(I'm not very good at this)

Can someone shed some light as to how I do this?

The code already times out after 1000ms when your finger is lifted off the buttin so I got that far but cant get any further.

Here is what I have.

Any other suggestions are also welcome as I know its not the prettiest or best implemented but i was just happy it worked for me.

// Setting The Pin Numbers
const int touchsensor = 2;                      // the number of the touchsensor pin
const int buzzer =  4;                          // the number of the LED pin

// variables:
int touchsensorState = 0;                       // variable for reading the 
touchsensor status
unsigned long timestamp = 0;
unsigned long timeout = 1000;

void setup() {

  pinMode(buzzer, OUTPUT);                      // initialize the buzzer as an output
  pinMode(touchsensor, INPUT);                  // initialize the touchsensor as an input
 }
void loop() {

   touchsensorState = digitalRead(touchsensor);  // read state of the pushbutton value:

   if (touchsensorState == HIGH) {                 // check if the touch sensor is pressed. If it is, the touchsensorState is HIGH:
     digitalWrite(buzzer, HIGH);                 // buzzer will emit sound:
     timestamp = millis();                       // Timing button press
   } 

   if(millis() - timestamp > timeout) {
   digitalWrite(buzzer, LOW);                  // buzzer will not sound:
   }
}

1 Answer 1

3

you will need to implement a edge sensor. Add a previousTouchsensorState to the globals and replace the if where you check the sensor state with:

if(previousTouchsensorState == LOW && touchsensorState == HIGH) {                 
     // check if the touch sensor is pressed and wasn't the last time though the loop. 
     // If it is, the touchsensorState is HIGH and previousTouchsensorState is LOW:
     digitalWrite(buzzer, HIGH); // buzzer will emit sound:
     timestamp = millis();       // Timing button press
}
previousTouchsensorState  = touchsensorState;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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