Arduino controls the rotation of the servo through two key switches (including code)

Design goals

Two switches control the steering gear rotation

Controlling the servo on Arduino requires the use of a Servo library, which can be used to easily control the servo. The following are the steps for two switches to control the servo through Arduino:

1. Connect the hardware: Connect the VCC pin of the servo to the 5V pin of the Arduino board, and connect the GND pin to the GND pin. Connect the servo's control pin (usually orange or yellow) to the digital pins of the Arduino board.
2. Import the Servo library: Open the "Tools" menu in Arduino IDE, select "Package Manager", search for "Servo", find and install the Servo library.
3. Write code: Write Arduino code, use if statements to detect the status of the two switches, and determine the angle value to be set based on the switch status. Finally, control the rotation of the servo through the Servo library.

Here is a code example:

#include <Servo.h>
#define switchPin1 2
#define switchPin2 3
Servo myservo;
int angle = 0;

void setup() {
  pinMode(switchPin1, INPUT_PULLUP);
  pinMode(switchPin2, INPUT_PULLUP);
  myservo.attach(9);
}

void loop() {
  if (digitalRead(switchPin1) == LOW) {
    angle += 10;
    if (angle > 180) {
      angle = 180;
    }
    myservo.write(angle);
    delay(50);
  }

  if (digitalRead(switchPin2) == LOW) {
    angle -= 10;
    if (angle < 0) {
      angle = 0;
    }
    myservo.write(angle);
    delay(50);
  }
}

4. Upload code: Upload the written code to the Arduino board.
Through the above steps, you can use two switches to control the rotation of the servo. When the first switch is pressed, the servo will turn to the left; when the second switch is pressed, the servo will turn to the right.

Guess you like

Origin blog.csdn.net/m0_58857684/article/details/130653009