このチュートリアルはの一部です: サーボモーター
サーボモーターに関連するすべてのビデオをここに掲載しています。他のビデオへのリンクはこの記事の下にあります。
Build an Arduino Servo Toggle Switch with a Push Button
Build an Arduino Servo Toggle Switch with a Push Button
This project guide will show you how to create a simple yet highly useful circuit: a servo motor that toggles between two positions with each press of a single push button. On the first press, the servo will smoothly sweep from 0 to 180 degrees. On the second press, it will sweep back from 180 to 0 degrees. This is a fundamental concept in robotics and automation, perfect for creating mechanisms like an automatic door latch, a simple robotic arm, a flag waver, or any project that requires a two-state physical action.
We will walk through the required hardware, the wiring, and provide a detailed explanation of the Arduino code that makes it all work.
Hardware and Wiring
The components for this project are minimal and common in most Arduino starter kits. You will need an Arduino board (like an Uno), a standard hobby servo motor (e.g., SG90), a push button, and a few jumper wires.
The wiring is straightforward. The servo's power and ground lines connect to the Arduino's 5V and GND pins, while its signal line connects to a PWM-capable pin (pin 9 in our code). The push button connects between digital pin 2 and GND.
The Arduino Code Explained
The sketch uses the standard Servo.h library, which is included with the Arduino IDE. The code is designed to be clean and easy to understand, using flags to keep track of the servo's state and `for` loops to create a smooth sweeping motion.
Global Variables and Configuration
At the top of the code, we define the pins and the servo's behavior. These are the main values you might want to customize for your project.
#include <Servo.h>
// Define variables for servo and button pins
const int servoPin = 9; // Connect servo signal wire to digital pin 9
const int buttonPin = 2; // Connect push button to digital pin 2
// Define servo movement parameters
const int initialAngle = 0; // Servo's starting angle
const int targetAngle1 = 180; // First target angle
const int targetAngle2 = 0; // Second target angle
const int movingStep = 1; // Step size for smooth movement (1 degree at a time)
Servo myServo; // Create a Servo object
// State-tracking variables
int currentAngle = initialAngle;
bool buttonPressed = false;
bool servoAt180 = false;
servoPin: The pin connected to the servo's signal wire. This must be a PWM pin (marked with a `~` on most Arduino boards).buttonPin: The pin the push button is connected to.initialAngle,targetAngle1,targetAngle2: These define the start and end points of the servo's movement.movingStep: This controls how many degrees the servo moves in each step of the loop. A smaller number creates a smoother, slower motion.
The `setup()` Function
The setup() function runs once when the Arduino is powered on. It initializes the servo, configures the button pin, and sets the servo to its starting position.
void setup() {
myServo.attach(servoPin); // Attaches the servo to its pin
pinMode(buttonPin, INPUT_PULLUP); // Set the button pin as input with internal pull-up
myServo.write(initialAngle); // Move the servo to its initial position
Serial.begin(9600); // Start serial for debugging
}
We use INPUT_PULLUP for the button pin. This activates an internal resistor in the Arduino, which keeps the pin's state HIGH when the button is not pressed. When the button is pressed, it connects the pin to ground, making the state LOW. This useful feature means you don't need to add an external pull-up resistor to your circuit.
The `loop()` - The Core Logic
The main loop continuously checks for a button press. When a press is detected, it moves the servo to its next target position.
void loop() {
// Read the state of the button
int buttonState = digitalRead(buttonPin);
// Check if the button is pressed (LOW) and it wasn't already being held down
if (buttonState == LOW && !buttonPressed) {
delay(50); // Debounce delay to prevent multiple triggers
if (digitalRead(buttonPin) == LOW) { // Re-check the button state
buttonPressed = true; // Mark the button as pressed
if (!servoAt180) {
// If not at 180, move to 180
for (int angle = currentAngle; angle <= targetAngle1; angle += movingStep) {
myServo.write(angle);
delay(15); // Delay between steps to control speed
}
currentAngle = targetAngle1;
servoAt180 = true; // Update state
} else {
// If at 180, move back to 0
for (int angle = currentAngle; angle >= targetAngle2; angle -= movingStep) {
myServo.write(angle);
delay(15);
}
currentAngle = targetAngle2;
servoAt180 = false; // Update state
}
}
}
// Reset the button press flag once the button is released
if (buttonState == HIGH) {
buttonPressed = false;
}
}
The code uses a boolean flag, servoAt180, to remember the servo's last position. When the button is pressed, it checks this flag: if the servo is not at 180 degrees, it moves it there; otherwise, it moves it back to 0. The for loops are what create the smooth sweeping motion, moving the servo one degree at a time with a small delay between each step.
How It Works
Once you upload the code and power on your Arduino, the servo will move to its initial 0-degree position.
- First Press: When you press the button, the code detects the input and begins moving the servo from 0 towards 180 degrees, one degree at a time.
- Second Press: After the servo has reached 180 degrees, the next button press will cause it to sweep back from 180 towards 0 degrees.
This cycle will repeat with each subsequent button press, creating a reliable and predictable toggle mechanism for your project.
このチュートリアルはの一部です: サーボモーター
- Arduinoを使ってプッシュボタンでサーボを制御する
- Control a Servo Motor with a Push Button: Move Servo and Return SPB-1
- Control a Servo Motor with a Push Button: Move Servo in One Direction SPB-2
- Controlling a Servo Motor with a Push Button: Move Servo While Button Is Pressed (SPB-3)
- Arduinoを使ってポテンショメータでサーボを制御する
- Arduinoを使ってポテンショメータとLCD1602でサーボを制御する
- Arduinoを使った赤外線リモコンによるサーボモーターの制御
- ポテンショメーターを使用したArduinoサーボモーター制御
- Arduino用の手のジェスチャーによるサーボ位置の制御
- Controlling Two or More Servos with Potentiometers Using an Arduino
- How to Control a 360° Servo with Three Push-Button Switches
- How to Use Continuous 360° Servo with Arduino
- PCA9685 16チャンネル 12ビット サーボコントローラ V1 用の Arduino コードとビデオ
/*
* このコードはrobojax.comによって提供されています。
* 配線図とこのチュートリアルの詳細は、こちらでご覧いただけます:https://robojax.com/T661
*/
#include <Servo.h>
// サーボとボタンのピンのための変数を定義する
const int servoPin = 9; // サーボ信号の配線をデジタルピン9に接続します。
const int buttonPin = 2; // デジタルピン2にプッシュボタンを接続します。
// サーボの動作パラメータを定義する
const int initialAngle = 0; // サーボの起動角度
const int targetAngle1 = 180; // 最初の目標角度
const int targetAngle2 = 0; // 第2の目標角度(この場合は最初と同じ)
const int movingStep = 1; // 滑らかな動きのためのステップサイズ(例:一度に1度)
Servo myServo; // Servoオブジェクトを作成する
int currentAngle = initialAngle; // サーボの現在の角度を追跡するための変数
bool buttonPressed = false; // ボタンの状態を追跡するためのフラグ
bool servoAt180 = false; // サーボが180度にあるかどうかを追跡するフラグ
void setup() {
myServo.attach(servoPin); // サーボピンのサーボをサーボオブジェクトに取り付ける
pinMode(buttonPin, INPUT_PULLUP); // 内部プルアップ抵抗を使用してボタンピンを入力に設定する
myServo.write(initialAngle); // サーボを初期角度に設定します。
Serial.begin(9600); // デバッグのためにシリアル通信を開始します。
}
void loop() {
// ボタンの状態を読み取る
int buttonState = digitalRead(buttonPin);
// ボタンが押されているか確認してください(INPUT_PULLUPのためLOW)および以前に押されていなかったこと。
if (buttonState == LOW && !buttonPressed) {
delay(50); // デバウンス遅延
if (digitalRead(buttonPin) == LOW) { // デバウンス後に確認ボタンを押す
buttonPressed = true; // ボタンが現在押されていることを示すフラグを設定します。
if (!servoAt180) {
// サーボを180度に移動させてください。
Serial.println("Moving to 180 degrees");
for (int angle = currentAngle; angle <= targetAngle1; angle += movingStep) {
myServo.write(angle);
delay(15); // この遅延を望ましい速度に合わせて調整してください。
}
currentAngle = targetAngle1;
servoAt180 = true;
} else {
// サーボを0度に移動させる
Serial.println("Moving to 0 degrees");
for (int angle = currentAngle; angle >= targetAngle2; angle -= movingStep) {
myServo.write(angle);
delay(15); // この遅延を望ましい速度に合わせて調整してください。
}
currentAngle = targetAngle2;
servoAt180 = false;
}
}
}
// ボタンが解放されたときに、ボタンが押されたフラグをリセットします。
if (buttonState == HIGH) {
buttonPressed = false;
}
}
リソースと参考文献
まだリソースはありません。
ファイル📁
ファイルは利用できません。