Advertisement
webtronico

Arduino - Simulating continuous rotation (for standard servos

May 1st, 2024
728
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 1.47 KB | Source Code | 0 0
  1. #include <Servo.h>
  2.  
  3. const int servoPin = 9; // Servo pin
  4. const int buttonIncPin = 2; // Increment button pin
  5. const int buttonDecPin = 3; // Decrement button pin
  6.  
  7. Servo myServo; // Servo object
  8. int servoPosition = 0; // Servo position variable
  9. int prevButtonStateInc = LOW; // Previous state of increment button
  10. int prevButtonStateDec = LOW; // Previous state of decrement button
  11.  
  12. void setup() {
  13.   myServo.attach(servoPin); // Attach servo to pin
  14.   pinMode(buttonIncPin, INPUT); // Set increment button as input
  15.   pinMode(buttonDecPin, INPUT); // Set decrement button as input
  16. }
  17.  
  18. void loop() {
  19.   // Read button states
  20.   int buttonStateInc = digitalRead(buttonIncPin);
  21.   int buttonStateDec = digitalRead(buttonDecPin);
  22.  
  23.   // Increment servo position if increment button is pressed and previously wasn't
  24.   if (buttonStateInc == HIGH && prevButtonStateInc == LOW) {
  25.     servoPosition++;
  26.   }
  27.  
  28.   // Decrement servo position if decrement button is pressed and previously wasn't
  29.   if (buttonStateDec == HIGH && prevButtonStateDec == LOW) {
  30.     servoPosition--;
  31.   }
  32.  
  33.   // Simulate 360-degree rotation by wrapping around servo limits
  34.   if (servoPosition < 0) {
  35.     servoPosition = 180;
  36.   } else if (servoPosition > 180) {
  37.     servoPosition = 0;
  38.   }
  39.  
  40.   // Update servo position
  41.   myServo.write(servoPosition);
  42.  
  43.   // Update previous button states
  44.   prevButtonStateInc = buttonStateInc;
  45.   prevButtonStateDec = buttonStateDec;
  46.  
  47.   delay(50); // Delay between servo movements
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement