kartonman

Servo set angle and speed

Jul 4th, 2023
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. #include <Servo.h>
  2.  
  3. // Pin Definitions
  4. const int switchPin = 2; // Digital pin for the switch
  5. const int servoPin = 9; // Digital pin for the servo
  6.  
  7. // Servo Settings
  8. const int servoMinAngle = 0; // Minimum angle for the servo
  9. const int servoMaxAngle = 45; // Maximum angle for the servo
  10. const int servoSpeed = 1; // Speed of servo movement (range: 1-9)
  11.  
  12. // Global Variables
  13. Servo myServo;
  14. bool switchState = false;
  15. int currentAngle = 0;
  16.  
  17. void setup() {
  18. // Set switch pin as input with internal pull-up resistor
  19. pinMode(switchPin, INPUT_PULLUP);
  20.  
  21. // Attach servo to the corresponding pin
  22. myServo.attach(servoPin);
  23.  
  24. // Initial position of the servo
  25. myServo.write(currentAngle);
  26. }
  27.  
  28. void loop() {
  29. // Read the state of the switch
  30. switchState = digitalRead(switchPin);
  31.  
  32. if (switchState == HIGH) {
  33. // Switch is pressed, move servo from 0 to 45 degrees
  34. if (currentAngle < servoMaxAngle) {
  35. currentAngle += servoSpeed;
  36. myServo.write(currentAngle);
  37. delay(15);
  38. }
  39. }
  40. else {
  41. // Switch is released, move servo from 45 to 0 degrees
  42. if (currentAngle > servoMinAngle) {
  43. currentAngle -= servoSpeed;
  44. myServo.write(currentAngle);
  45. delay(15);
  46. }
  47. }
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment