# I Need Help with Delay Function Code for Servo

**URL:** <https://forum.arduino.cc/t/i-need-help-with-delay-function-code-for-servo/1058151>\
**Category:** Programming\
**Created:** [November 26, 2022, 10:21am UTC](https://forum.arduino.cc/t/i-need-help-with-delay-function-code-for-servo/1058151 "2022-11-26T10:21:35Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![rabbitmoon](https://avatars.discourse-cdn.com/v4/letter/r/eb9ed0/32.png) [@rabbitmoon](https://forum.arduino.cc/u/rabbitmoon)\
**Post date:** [November 26, 2022, 10:21am UTC](https://forum.arduino.cc/t/i-need-help-with-delay-function-code-for-servo/1058151/1 "2022-11-26T10:21:35Z")

</div>

Hello, I'm struggling with writing a code for my engineering project.

I managed to have the delay functions worked for the DC motor. However, I need help with the coding for the servo. I want to code a delay function to have the button pressed once, and wait for 8 seconds for the servo to sweep from 0 to 180 degrees.

Image attached below:

 ![Delay_TEST](https://europe1.discourse-cdn.com/arduino/original/4X/1/f/9/1f989ec7355098f106f16403598152a03c07b23e.png)

Here's my code:  
// C++ code  
//

const int buttonPin = 7;

int sensorPin = 7;  
int sensorValue = 0;

#include \<Servo.h\>  
int servoPin = 10;  
Servo myservo;  
int angle = 0;

int motorPin = 11;  
int speed = 0;

// set button states  
int buttonState = 0;  
int lastbuttonState = LOW;  
int currentbuttonState = HIGH;

// set motor states  
int motorState1 = HIGH;  
int motorState2 = LOW;

void setup()  
{  
Serial.begin(9600);  
pinMode(buttonPin, INPUT);  
Serial.println("The button is pressed once");

pinMode(servoPin, OUTPUT);  
myservo.attach(servoPin);  
myservo.write(angle);  
currentbuttonState = digitalRead(buttonPin);

pinMode(motorPin, OUTPUT);  
Serial.println("Speed 0 to 255");  
}

void loop()  
{  
delay(1000); // wait for a second for motor to rotate  
digitalWrite(motorPin, HIGH);  
delay(27000); // wait for 27 seconds for motor to stop rotating  
digitalWrite(motorPin, LOW);  
delay(1000); // wait for a second for motor to stop rotating  
exit(0);

buttonState = digitalRead(buttonPin);  
lastbuttonState = currentbuttonState;  
currentbuttonState = digitalRead(buttonPin);

if (lastbuttonState == LOW) {  
digitalWrite(servoPin, HIGH);

if (angle == 0)  
angle = 360;  
else  
myservo.write(angle);  
delay(8000); // wait for 8 seconds for servo to sweep from 0 to 180 degrees  
}  
}

---

<div class="post-metadata">

**Author:** ![UKHeliBob](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/ukhelibob/32/215663_2.png) [@UKHeliBob](https://forum.arduino.cc/u/UKHeliBob)\
**Post date:** [November 26, 2022, 10:23am UTC](https://forum.arduino.cc/t/i-need-help-with-delay-function-code-for-servo/1058151/2 "2022-11-26T10:23:26Z")

</div>

Welcome to the forum

Your topic was **MOVED** to its current forum category which is more appropriate than the original as it is not an Introductory Tutorial

> [@rabbitmoon](#):
>
> Here's my code:

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'  
  
Use **code tags** (the \</\> icon above the compose window)&nbsp;to make it easier to read and copy for examination

> [@How to get the best out of this forum](https://forum.arduino.cc/t/how-to-get-the-best-out-of-this-forum/679966):
>
> See also [FAQ - Arduino Forum](https://forum.arduino.cc/faq) for general rules on forum behaviour and etiquette. Hello, Welcome to the Arduino Forum. This guide explains how to get the best out of this forum. Please read and follow the instructions below. Being new here you might think this is having rules for the sake of rules, but that is not the case. If you don’t follow the guidelines all that happens is there is a long exchange of posts while we try to get you to tell us what we need in order to help you, which is fru…

---

<div class="post-metadata">

**Author:** ![UKHeliBob](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/ukhelibob/32/215663_2.png) [@UKHeliBob](https://forum.arduino.cc/u/UKHeliBob)\
**Post date:** [November 26, 2022, 10:28am UTC](https://forum.arduino.cc/t/i-need-help-with-delay-function-code-for-servo/1058151/3 "2022-11-26T10:28:48Z")

</div>

```cpp
    digitalWrite(servoPin, HIGH);
    if (angle == 0)
      angle = 360;

```

Why are you setting the servo pin HIGH ?  
Why are you writing a value of 360 to the servo ? Can it move through 360 degrees ?

```cpp
      myservo.write(angle);
    delay(8000); // wait for 8 seconds for servo to sweep from 0 to 180 degrees

```

The servo will move to whatever angle you send it and the delay() will occur afterwards. IS that what you want to happen ?

---

<div class="post-metadata">

**Author:** ![PaulRB](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/paulrb/32/216330_2.png) [@PaulRB](https://forum.arduino.cc/u/PaulRB)\
**Post date:** [November 26, 2022, 10:59am UTC](https://forum.arduino.cc/t/i-need-help-with-delay-function-code-for-servo/1058151/4 "2022-11-26T10:59:33Z")

</div>

> [@rabbitmoon](#):
>
> my engineering project

Ok, then you should be learning to be an engineer. Think about power, think about current, think about where that power/current is coming from and how much will be available. Then think about how much power/current is needed. How much does the Uno need? How much does the DC motor need, especially when it starts up. Think about the kinetic energy is stored when the motor is spinning and what happens to that energy when the motor stops. Think about how much current/power the servo motor needs. Compare the current/power that is needed compared to what is available. Do you have documents that tell you these numbers? If not, what can you do to find out what they are?

What voltages is your circuit using? What current/power is available at each voltage? Is the voltage enough for each motor?

When you gather this information together and review it, you will see that there are a number of problems with the circuit you posted. They can't be fixed in software.

---

<div class="post-metadata">

**Author:** ![amitf](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/amitf/32/1057288_2.png) [@amitf](https://forum.arduino.cc/u/amitf)\
**Post date:** [November 26, 2022, 11:31am UTC](https://forum.arduino.cc/t/i-need-help-with-delay-function-code-for-servo/1058151/5 "2022-11-26T11:31:26Z")

</div>

You should use millis() function instead of delay I am sure it will work

---

<div class="post-metadata">

**Author:** ![gcjr](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/gcjr/32/314015_2.png) [@gcjr](https://forum.arduino.cc/u/gcjr)\
**Post date:** [November 26, 2022, 11:45am UTC](https://forum.arduino.cc/t/i-need-help-with-delay-function-code-for-servo/1058151/6 "2022-11-26T11:45:26Z")

</div>

> [@rabbitmoon](#):
>
> wait for 8 seconds for the servo to sweep from 0 to 180 degrees.

do you just want to wait 8 seconds after issuing the servo.write() or do you want it to take 8 seconds to slowly move the servo?

other issues

- why are the button and servo pins the same (7)
- button inputs are normally configured as INPUT\_PULLUP, enabling internal pull-up resistors and wiring the button between pin and ground. the code tests for LOW, but configures the pin as INPUT
- why an initial 1 sec delay at the start of loop()
- a digital pin can only supply about 40 ma. is that enough to drive the motor?
- why `exit(0)` in the middle of loop() -- if you just want to do all this once, just put it in setup()
- why read the buttonPin twice? since there's no need to debounce, could test directly

```arduino
     if (LOW == digitalRead (buttonPin))

```

- there's a test for the angle position, but in the one condition the angle variable is changed but not used to move the servo and in the other condition, the servo is moved and no where is the angle set back to zero ... do you really just want to do this once?
- servos normally only move from 0 to 180, not 360 deg (unless it is a continuous servo)

the problem with checking for the button is that it must be pressed for the fraction of an instant after the delay when the motor is turned off and before the motor is turned on

consider following

```arduino
#undef MyHW
#ifdef MyHW
# include "simLib.hh"
const int buttonPin = A1;

#else
# include <Servo.h>
const int buttonPin = 7;
#endif

// -------------------------------------
const int servoPin = 8;
const int motorPin = 11;

Servo myservo;

int angle = 0;

#define ServoPeriod 2000

// -----------------------------------------------------------------------------
void func ()
{
    digitalWrite (motorPin, HIGH); // turn on motor
    delay (1000); // let run for 2 sec
    digitalWrite (motorPin, LOW);
    delay (1000); // let the motor be off

    if (LOW == digitalRead (buttonPin)) {
        if (0 == angle) {
            for ( ; angle <= 180; angle++) {
                myservo.write (angle);
                delay (ServoPeriod / 180);
            }
        }
        else {
            for ( ; angle >= 0; angle--) {
                myservo.write (angle);
                delay (ServoPeriod / 180);
            }
        }
    }
}

// -----------------------------------------------------------------------------
void loop ()
{
    func (); // or could just call this once in setup
}

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

    pinMode (buttonPin, INPUT);

    myservo.attach (servoPin);
    myservo.write (angle);

    pinMode (motorPin, OUTPUT);
}

```

---

<div class="post-metadata">

**Author:** ![StefanL38](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/stefanl38/32/713548_2.png) [@StefanL38](https://forum.arduino.cc/u/StefanL38)\
**Post date:** [November 26, 2022, 3:40pm UTC](https://forum.arduino.cc/t/i-need-help-with-delay-function-code-for-servo/1058151/7 "2022-11-26T15:40:11Z")

</div>

High rabbitmoon,

welcome to the Arduino-Forum.

You seem to be right at the beginning. And you did a very important first step that does not happen so often.

Posting your first attempt to write the code. This is very good. Even if there might be some bugs in your code. Your attempt to write the code gives very important information about your skill-level which is important to adapt answers to your knowledge- and skill level.

You posted a tinkercad picture that shows how you have wired things together in the tinkercad simulation. The tinkercad-simulation is good for code-development. But it is **really bad** about the **hardware** -aspects.

The onboard-voltage-regulator of an arduino is completely overloaded with a DC-motor and a servo with some load. They need their own powersupply but the GNDs must be connected together.

As a general advice: You should give an overview about the **final purpose** of your project  
What are the DC-motor and the servo do in the end?

Is this just an exercise or is there a realworld-application behind it?

Using some example-code making small modifications in the code is quickly successful.  
But changing the functionality of a given example to deviate more requires as a must understanding the lines of code.

From the questions posted above I can conclude your knowledge is improvable.  
Basically there are two ways to go on:

1. stumbling forward without really understanding how the code works  
you will get a 70% working code pretty quickly. But the 30% missing will need a lot of time to write

2. doesn't seem to make any headway at first by learning basic things that have nothing to do with your actual code but teaching you fundamental concepts that you then can apply to your project **quickly and successful**  **after** having understood the basic concepts.

So you can go on walking by foot as a jogger  
or start building a race-car-kit where building the race-car-kit keeps you behind the startline but in a 500 miles race on the third day (after finishing the race-car-kit) you will wrooom!-zoom pass the jogger and win the race.

If you prefer the second way start reading this tutorial

[Arduino Programming Course](https://startingelectronics.org/software/arduino/learn-to-program-course/)

It is easy to understand and has a good mixture between explaining important concepts and example-codes to get you going. So give it a try and report your opinion about this tutorial.

best regards Stefan  
by the way  
[Make experienced users help: two ways to quickly post code as a code-section](https://forum.arduino.cc/t/make-experienced-users-help-two-ways-to-quickly-post-code-as-a-code-section/937298)

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [May 25, 2023, 3:40pm UTC](https://forum.arduino.cc/t/i-need-help-with-delay-function-code-for-servo/1058151/8 "2023-05-25T15:40:33Z")

</div>

Closed on May 25, 2023, 3:40pm UTC

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