I Need Help with Delay Function Code for Servo

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:

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
}
}

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

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) to make it easier to read and copy for examination

    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 ?

      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 ?

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.

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

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
     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

#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);
}
1 Like

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

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

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