Buzzer with "if" function not working

Hello, so I have this weird problem with the arduino code

#include <Servo.h>
Servo myservo;

int pos = 0;

void setup() 
{
  myservo.attach(5);
  pinMode(13, OUTPUT);
}


void loop() 
{
 
  for(pos = 0; pos <= 90; pos += 1)
  {
    myservo.write(pos);
    delay(50);
  }
  if(pos < 90)
  {
    tone(13, 200, 100);
    delay(200);
  }
 
  for(pos = 90; pos += 0;)
  {
    myservo.write(pos);
    delay(0);
  }
  
  
}

the problem is at

if(pos < 90)
  {
    tone(13, 200, 100);
    delay(200);
  }

its not playing the sound, what should I do?
I tried putting

    tone(13, 200, 100);
    delay(200);

inside the

for(pos = 0; pos <= 90; pos += 1)
  {
    myservo.write(pos);
    delay(50);
  }

but I have 2 delay, that is the 50 ms delay and the 200 ms delay, and if I put it in one {} it will affect the whole function in the {} so I cant do that.

Please help me!
Thank You!

I do this in tinkercad btw, I dont know if this will do something different or not

At what position of servo, you expect the sound should intiate?


this is the position of the servo and the buzzer

the sound should play when the servo is not 90 degree, like less than 90 degree and when 90 degree it stop

I wanted to mean that "at what angular position (how many degrees) of the shaft of the servo", the buzzer should intiate sound/tone?

I want to make this will be like the train cross system, so there will be a sound playing when the servo is going down to 90 degree

Try the following sketch:

#include <Servo.h>
Servo myservo;

int pos = 0;

void setup() 
{
  myservo.attach(5);
  pinMode(13, OUTPUT);
  //----------------------------
  for(pos = 0; pos <= 90; pos += 1)
  {
    myservo.write(pos);
    delay(50);
    if(pos == 90)
    {
         tone(13, 200, 100);
    }
  }
}

void loop() 
{
 
}

Thank You, I will try it

The servo did work perfectly but the buzzer is not even making any sound. Thank you for answering tho

Nvm I fixed it

#include <Servo.h>
Servo myservo;

int pos = 0;

void setup() 
{
  myservo.attach(5);
  pinMode(13, OUTPUT);
  //----------------------------
  for(pos = 0; pos <= 90; pos += 1)
  {
    myservo.write(pos);
    delay(50);
    if(pos <= 90)
    {
         tone(13, 200, 200);
      	 delay(300);
    }
  }
}

void loop() 
{
 
}

But one thing is, the servo supposed to do the 50 ms delay, not the 300 ms delay
code by @GolamMostafa and only edited a bit

And one question, why dont we put it in the void loop() section?

Code says 0 to 89.

Yes, btw I figured it out, tysm for all your help!
Oh wow, new information I got. Thank you so much! @ec2021
I will try your suggestion @ec2021 thank you so much, btw I cant reply anymore because this is my first day lol

Anything in loop() will be repeated from the beginning (unless you do have a blocking function inside loop() ).

If you want something to be done only once after start of the sketch, setup() is a nice place. Actually what happens to setup() and loop() is something like this in C++:

void setup(){
// Do something at startup
}

void loop(){
// Do something repeatedly
}


void main(){
    setup();
    while(1){
       loop();
     }
}

So setup() is not necessarily the place to put test issues, but a nice one if you want something to be done only once and then stop.

Placing code in setup() lets you run once (press reset to run again). Loop() repeats.

You are using delays in your code which is not always an aedequate solution; I would recommend using millis() to control tone and servo ...

Are you interested in that or happy with your solution?

You could use millis timing and process states to break the code into tasks.
It will far easier to add to and modify where nested code makes that increasingly hard.

void loop()
{
A task to watch for the train that updates a status byte variable.
A task to operate the servo, that reads the train status as trigger when not operating.
A task to sound the buzzer as long as a status set by the server task is ON.
}

A technique called state machine lets you make any task modal, the code is written in numbered "cases" to handle every step of a task. A state variable holds the number of what step to run when void loop calls the task again. Any task can change the state, run the next state according to what happened now.
This is one of the most powerful coding tools I know, and I started coding for money in January 1980.

Teaching millis and states is one thing this board served du jour before COVID and the crap forum clown facelift made it half useless. You should get help going in that direction if you desire so.

You like the idea?

If you wanted to add a start-stop button, the delays in your original code would keep you from sensing the button state. The loop in the servo part would have to be modified to allow early exits and variable start counts to keep.

With non-blocking millis and states codes you add a button task and status byte then modify the other task triggers to respect this No-or-Go status.

A better name for this style is non-blocking event-driven code. Events may be pin state changes, elapsed times, values of variables or operations. You sense events in time to make events happen on time. It's a hell of a lot easier with tasks.

Here is an example of a state machine replacing blinking led13 with delays to doing the same exact (trivial and not optimized) thing with millis only...

I can add non-blocking code from other sketches, maybe have to rename variables or change pins used but when done, all the pieces run together smoothly. A start/stop button, a status light blinking to show that loop is running, no problem.

// add-a-sketch_un-delay 2018 by GoForSmoke @ Arduino.cc Forum
// Free for use, Apr 30/18 by GFS. Compiled on Arduino IDE 1.6.9.
// This sketch shows a general method to get rid of delays in code.
// You could upgrade code with delays to work with add-a-sketch.

// just call it undelay, GFS Jan 25, 2022

#include <avr/io.h>
#include "Arduino.h"

const byte ledPin = 13;
unsigned long delayStart, delayWait;

void setup()
{
  Serial.begin( 115200 );
  Serial.println( F( "\n\n\n  Un-Delay Example, free by GoForSmoke\n" ));
  Serial.println( F( "This sketch shows how to get rid of delays in code.\n" ));

  pinMode( ledPin, OUTPUT );
};


/* The section of the original sketch with delays:
 * 
 * digitalWrite( ledPin, HIGH );   --  0
 * delay( 500 );
 * digitalWrite( ledPin, LOW );    --  1
 * delay( 250 );
 * digitalWrite( ledPin, HIGH );   --  2
 * delay( 250 );
 * digitalWrite( ledPin, LOW );    --  3
 * delay( 250 );
 * digitalWrite( ledPin, HIGH );   --  4
 * delay( 1000 );
 * digitalWrite( ledPin, LOW );    --  5
 * delay( 1000 );
 */

byte blinkStep; // state tracking for BlinkPattern() below

void BlinkPattern()
{
  // This one-shot timer replaces every delay() removed in one spot.  
  // start of one-shot timer
  if ( delayWait > 0 ) // one-shot timer only runs when set
  {
    if ( millis() - delayStart < delayWait )
    {
      return; // instead of blocking, the undelayed function returns
    }
    else
    {
      delayWait = 0; // time's up! turn off the timer and run the blinkStep case
    }
  }
  // end of one-shot timer

  // here each case has a timed wait but cases could change Step on pin or serial events.
  switch( blinkStep )  // runs the case numbered in blinkStep
  {
    case 0 :
    digitalWrite( ledPin, HIGH );
    Serial.println( F( "Case 0 doing something unspecified here at " ));
    Serial.println( delayStart = millis()); // able to set a var to a value I pass to function
    delayWait = 500; // for the next half second, this function will return on entry.
    blinkStep = 1;   // when the switch-case runs again it will be case 1 that runs
    break; // exit switch-case

    case 1 :
    digitalWrite( ledPin, LOW );
    Serial.println( F( "Case 1 doing something unspecified here at " ));
    Serial.println( delayStart = millis());
    delayWait = 250;
    blinkStep = 2;
    break;

    case 2 :
    digitalWrite( ledPin, HIGH );
    Serial.println( F( "Case 2 doing something unspecified here at " ));
    Serial.println( delayStart = millis());
    delayWait = 250;
    blinkStep = 3;
    break;

    case 3 :
    digitalWrite( ledPin, LOW );
    Serial.println( F( "Case 3 doing something unspecified here at " ));
    Serial.println( delayStart = millis());
    delayWait = 250;
    blinkStep = 4;
    break;

    case 4 :
    digitalWrite( ledPin, HIGH );
    Serial.println( F( "Case 4 doing something unspecified here at " ));
    Serial.println( delayStart = millis());
    delayWait = 1000;
    blinkStep = 5;
    break;

    case 5 :
    digitalWrite( ledPin, LOW );
    Serial.print( F( "Case 5 doing something unspecified here at " ));
    Serial.println( delayStart = millis());
    delayWait = 1000;
    blinkStep = 0;
    break;
  }
}


void loop()  // runs over and over, see how often
{            
  BlinkPattern();
}

See if you can add the loop counter task from the sketch below to the one above.

// add-a-sketch_loop_counter 2018 by GoForSmoke @ Arduino.cc Forum
// Free for use, Apr 29/2018 by GFS. Compiled on Arduino IDE 1.6.9.
// This sketch counts times that loop has run each second and prints it.
// It uses the void LoopCounter() function that does not block other code.

#define microsInOneSecond 1000000UL

void setup()
{
  Serial.begin( 115200 );
  Serial.println( F( "\n\n\n  Loop Counter, free by GoForSmoke\n" ));
  Serial.println( F( "This sketch counts times that loop has run each second and prints it." ));
}

void LoopCounter() // tells the average response speed of void loop()
{ // inside a function, static variables keep their value from run to run
  static unsigned long count, countStartMicros; // only this function sees these

  count++; // adds 1 to count after any use in an expression, here it just adds 1.
  if ( micros() - countStartMicros >= microsInOneSecond ) // 1 second
  {
    countStartMicros += microsInOneSecond; // for a regular second
    Serial.println( count ); // 32-bit binary into decimal text = many micros
    count = 0; // don't forget to reset the counter 
  }
}

void loop()  // runs over and over, see how often with LoopCounter()
{
  LoopCounter(); // the function runs as a task, the optimizer will inline the code.
}

The loop speed once blocking is gone... oh my, 1st time's a sur-prize!