A counter needed for this function

Hello everyone, i am currently working on a project on an arduino uno board and from the tasks requested in this project to be made is that i need to activate a buzzer after a button is pushed fifty times this is the code and i need to add the part that will allow me to do achieve such a function but i have failed to do that:
#define B2 2
#define B1 3
#define Green 4
#define Red 5
#define Y2 6
#define Y1 7
#define Trigcom 8
#define Echocom 9
#define buzzcom 10
long duration;
int distance;
int safetyDistance;
int counter = 0;
void setup()
// B2 switch one
pinMode(B2, INPUT);
// B1 switch two
pinMode(B1, INPUT);
// Green for extended solenoid valve
pinMode(Green, OUTPUT);
// Red for retracted solenoid valve
pinMode(Red, OUTPUT);
// Y2 for relay one
pinMode(Y2, OUTPUT);
// Y1 for relay two
pinMode(Y1, OUTPUT);
// Trigger connection point
pinMode(Trigcom, OUTPUT);
// Echo connection point
pinMode(Echocom, INPUT);
// Buzzer connection point
pinMode(buzzcom, OUTPUT);
// initialize and activate serial COMs
void loop ()
if (digitalRead(B2) == 0 && digitalRead(B1) == 1) {
digitalWrite(Green, HIGH);
digitalWrite(Green, LOW);
digitalWrite(Y1, HIGH);
digitalWrite(Y2, LOW);
digitalWrite(Red, LOW);
if (digitalRead(B1) == 0 && digitalRead(B2) == 1) {
digitalWrite(Red, HIGH);
digitalWrite(Red, LOW);
digitalWrite(Y2, HIGH);
digitalWrite(Y1, LOW);
digitalWrite(Green, LOW);
digitalWrite(Trigcom, LOW);
digitalWrite(Trigcom, HIGH);
digitalWrite(Trigcom, LOW);
duration = pulseIn(Echocom, HIGH);
distance = duration * 0.034 / 2;
safetyDistance = distance;
if (safetyDistance <= 150) {
digitalWrite(buzzcom, HIGH);
digitalWrite(buzzcom, LOW);
Serial.print("proximity range in Centimeters: ");

With switches, it is usually best to look at when a switch changes state.

When the switch changes from closed to open, increment counter


When the switch opens, if counter is == 50 do your stuff.

1 Like

do i put the increment on the switch intended for this function only right??

Depends on your needs.

If you want 50 switch operations to cause the buzzer operation and it can be from any switch operation, then counter++ would be added to all the switch code that can contribute to the counter incrementing.

1 Like

Study this:

The problem with the above example is the switch should be wired as S3 in the schematic below and look for a LOW for a switch closure.

1 Like

thanks for support that helped a lot

See post #5

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.