Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagecpp
themeMidnight
titleServo Positional Control
#include <Servo.h>

// Define Button Pins
#define BUTTON1_PIN 2
#define BUTTON2_PIN 4
#define BUTTON3_PIN 7

// Servo
Servo servo1;
int servoPos = 0;
const int maxServoPos = 180;
bool windingUp = false;

void setup() {
  // initialize serial communications at 19200 bps:
  Serial.begin(19200);

  // Servo setup
  servo1.attach(9);  // Attaching the servo to pin 9
  servo1.write(0);   // Move servo to home position

  // Button inputs
  pinMode(BUTTON1_PIN, INPUT);
  pinMode(BUTTON2_PIN, INPUT);
  pinMode(BUTTON3_PIN, INPUT);
}

void loop() {
  // Read button states
  bool button1State = digitalRead(BUTTON1_PIN);
  bool button2State = digitalRead(BUTTON2_PIN);
  bool button3State = digitalRead(BUTTON3_PIN);

  if (windingUp) {
    // Check if the winding up condition should be terminated
    if (!(button1State == HIGH && button2State == HIGH)) {
      windingUp = false;
      servoPos = 0;
      servo1.write(servoPos);  // Move servo to position 0 degrees when released
    } else if (servoPos < maxServoPos) {
      servoPos++;
      servo1.write(servoPos);
      delay(15); // Control the winding speed
    }
  } else {
    // Condition for both buttons pressed simultaneously
    if (button1State == HIGH && button2State == HIGH) {
      windingUp = true;
    } else if (button1State == HIGH) {
      servo1.write(0);  // Move servo to position 0 degrees
    } else if (button2State == HIGH) {
      servo1.write(66);  // Move servo to position 66 degrees
    } else if (button3State == HIGH) {
      servo1.write(132); // Move servo to position 132 degrees
    }
  }
}