Repeat a task 4 times then stop

Hello, right now I am trying to get a light and sound to play simultaneously for one second on and one second off, repeating four times but only when the potentiometer is in a particular range. If the potentiometer is moved the light and sound should stop and reset once the potentiometer is moved back into range. If the potentiometer stays within range, the light and noise shouls stop after 4 cycles. I will post full code, but the part I seek help on is the last if statement thats between values 513-768.

int hertz = 1000;
int bomb = 200;
void setup()
{
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(7, INPUT_PULLUP);
}

void loop()
{
  for(int hertz = 1000; hertz <= 4000; hertz = hertz +250)
  {
    if(analogRead(A0) <=256)
    {
      digitalWrite(12,HIGH);
      delay(200);
      tone(8,hertz,bomb);
      digitalWrite(12,LOW);
      delay(200);
    }
  }
  hertz = 1000;
  if(analogRead(A0) >= 257 && analogRead(A0) <= 512)
  {
    digitalWrite(10,HIGH);
    delay(10);
    digitalWrite(10,LOW);
    if(digitalRead(7) == LOW)
    {
      while(analogRead(A0) >= 257 && analogRead(A0) <= 512)
      {
        digitalWrite(10,LOW);
      }
    }
  }
  if(analogRead(A0) >=513 && analogRead(A0) <= 768)
  {
    for(int i = 0;i <4; i++)
    {
      digitalWrite(9, HIGH);
      tone(8, hertz, 1000);
      delay(1000);
      
      digitalWrite(9, LOW);
      delay(1000);
    }
  }
}

The first thing you need to master is how to make non-blocking TIMERs.

i.e. avoid using delay(...)

In general, you should not use magic numbers. The I/O pins love to have a functional name.

i hope this is saying you want something to happen no more than 4 times after the pot value is within a certain range

looks like the code

  • toggles pin 12 and generates a tone from 1 to 4K if the pot <= 256
  • toggles pin 10 if the pot is 257 <= 512 and doesn't nothing while the pot value remains within that range
  • toggles pin 9 and turns a tone on/off 4 times if the pot is 513 <= 768

the code doesn't seem to match your stated goal

look this over

int hertz = 1250;
int cnt;

void loop()
{
    int potVal = analogRead(A0);

    if (257 <= potVal && potVal <= 512) {
        if (4 > cnt)  {
            cnt++;
            Serial.println ("action");
            tone(8, hertz, 1000);
            delay(1000);
        }
    }

    else  {
        cnt = 0;
        Serial.println (potVal);
        delay (500);
    }
}

void setup()
{
    Serial.begin (9600);
}

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