Last active
March 6, 2022 19:26
-
-
Save ruirigel/391931a924545f12dd28f1e1f4151499 to your computer and use it in GitHub Desktop.
increase and decrease speed as the servo moves
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Functional example to apply to servo motors to remove the aggressive way they moves. | |
// Author: Rui Rigel https://github.com/ruirigel | |
#include <Servo.h> | |
Servo servo; | |
int SERVOPIN = 4; | |
int POS = 0; | |
int BUTTONPIN = 2; // to move the servo by alternating direction | |
int LEDPIN = 3; // on/off indicator | |
int msv = 50; // speed | |
int move_smoothly = msv; | |
void setup() { | |
Serial.begin(9600); | |
pinMode(LEDPIN, OUTPUT); | |
digitalWrite(LEDPIN, HIGH); | |
servo.attach(SERVOPIN); | |
pinMode(BUTTONPIN, INPUT); | |
} | |
void loop() { | |
if ((digitalRead(BUTTONPIN) == HIGH) && (POS > 179)) { | |
servo.attach(SERVOPIN); | |
for (POS = 180; POS >= 0; POS -= 1) { | |
if (POS > 160) { | |
move_smoothly = move_smoothly - 1; | |
delay(move_smoothly); | |
} | |
if (POS < 160 || POS > 20) { | |
delay(move_smoothly); | |
} | |
if (POS < 20) { | |
move_smoothly = move_smoothly + 1; | |
delay(move_smoothly); | |
} | |
servo.write(POS); | |
} | |
move_smoothly = msv; | |
POS = 0; | |
delay(1000); | |
servo.detach(); | |
} else if ((digitalRead(BUTTONPIN) == HIGH) && (POS < 1)) { | |
servo.attach(SERVOPIN); | |
for (POS = 0; POS <= 180; POS += 1) { | |
if (POS < 20) { | |
move_smoothly = move_smoothly - 1; | |
delay(move_smoothly); | |
} | |
if (POS > 20 || POS < 160) { | |
delay(move_smoothly); | |
} | |
if (POS > 160) { | |
move_smoothly = move_smoothly + 1; | |
delay(move_smoothly); | |
} | |
servo.write(POS); | |
} | |
move_smoothly = msv; | |
POS = 180; | |
delay(1000); | |
servo.detach(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment