How to count number of times servo motor rotates

hi

I am using Arduino Uno, servo motor and ultrasonic sensor for my project. When the sensor detect an object the servo motor will rotates.

I want to know how many times servo motor has rotated and this values need to record and store.. Can anybody provide me with the code.

I am attaching the present code I am using for the project.

#include <Servo.h>
#define trigPin 7
#define echoPin 6
Servo servo;
int sound = 250;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
servo.attach(8);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance < 5) {
Serial.println("the distance is less than 5");
servo.write(90);
}
else {
servo.write(0);
}
if (distance > 60 || distance <= 0){
Serial.println("The distance is more than 60");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}

Best Regards,

Have you got a servo or a continuous rotation "servo" ?

Hi

Its MG996R Tower Pro.

So you mean "count the number of times you wrote a different value to the servo"?

sarinkayyankot:
Its MG996R Tower Pro.

The number does not men anything to me. Is it a continuous rotation servo or is it a standard servo that moves about 180deg between fixed limits?

If it is a continuous rotation servo then you will need something to identify when it makes a full revolution - an optical detector where the beam is broken by something attached to the motor shaft is one possibility.

...R

Hi

Its 180 degree servo motor.

OK

You need to detect when the distance becomes less than 5 rather than when it is less than 5, When that happens add 1 to a counter

See the StateChangeDetection example in the IDE

sarinkayyankot:
Its 180 degree servo motor.

Then your use of the word "rotates" is strange. Do you mean how many times it "moves"?

You can keep track of that simply by incrementing a counter variable every time you issue a command to move the servo.

...R

You can keep track of that simply by incrementing a counter variable every time you issue a command to move the servo.

Except for the fact that the code has these lines in it

if (distance < 5) {
Serial.println("the distance is less than 5");
servo.write(90);

See reply#3

if (rotationAngle>=360){
lap++;                              //number of times servo motor rotates 
rotationAngle=0;
}

I think this counts the laps, isn't that it?

I think this counts the laps, isn't that it?

Where would the value of rotationAngle come from and how would it relate to a servo that can only move through 180 degrees ?