# How to use millis function for Servo Motor

Hi,

I want to operate Servo Motor with millis function.

1. Servo Motor will rotate by 20deg (Initial Position)
2. After 5 second
If Servo Motor Angle is less than 90deg then it will rotate to 120deg
if Servo Motor Angle is more than 90 deg then it will rotate to 30deg
3. loop continues after every 5 sec

I have written following code, but its not working. Please suggest the corrections.

#include <Servo.h>
int ANGLE = 0;
Servo servo_9;
unsigned long previousMillis = 0;
const long interval = 5000;

void setup()
{
pinMode(A0, INPUT);
servo_9.attach(9, 500, 2500);
}

void loop()
{
servo_9.write(20);
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
if(ANGLE < 90) {
servo_9.write(120);
} else {
servo_9.write(30);
}
}
previousMillis = currentMillis;
}

You never change the value of ANGLE from 0 so

``````    if (ANGLE < 90)
``````

will always be true

Sorry, actually couldnt understand.
I updated the code as per following and it gives some result,
But still I want to set some initial position for servo motor and then start this loop.

#include <Servo.h>

Servo servo_9;
unsigned long previousMillis = 0;
const long interval = 5000;

void setup()
{
servo_9.attach(9, 500, 2500);
}

void loop()
{
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
servo_9.write(120);
} else {
servo_9.write(30);
}
delay(5000); // Delay a little bit to improve simulation performance
}
}

try this:
(compiles, NOT tested)

``````#include <Servo.h>

Servo servo_9;
unsigned long previousMillis = 0;
const long interval = 5000;

void setup()
{
servo_9.attach(9, 500, 2500);
}

void loop()
{
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
servo_9.write(120);
} else {
servo_9.write(30);
}
previousMillis = currentMillis; //previousMillis needs to be updated. (not in your original code)
delay(1); // <----- not really needed (unless this is really a PC simulation) since you are using millis() already!!!!
}
}
``````

hope that helps…

But still I want to set some initial position for servo motor and then start this loop.

Use servo_9.write() in setup() to move the servo to the required initial position

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