検索コード

簡単なArduinoプロジェクト:プッシュボタンでサーボを180度から0度へ、そして戻す制御

簡単なArduinoプロジェクト:プッシュボタンでサーボを180度から0度へ、そして戻す制御

はじめに

この記事では、押しボタンを使ってサーボモーターを制御する簡単なArduinoプロジェクトについて説明します。サーボモーターは、特定の位置に回転できる精密なモーターで、ロボット工学や自動化などの用途に最適です。このプロジェクトでは、ボタンが押されるとサーボが0度から180度に動き、離されると0度に戻ります。

プロジェクトの部品と配線

Arduinoボード、サーボモーター、押しボタンが必要です。

配線手順:

  • サーボモーター信号線(通常は黄色/オレンジ)をArduinoのピン3に、電源線(赤)を5Vに、接地線(黒/茶)をGNDに接続します。
  • 押しボタン:一方の端子をデジタルピン2に、もう一方の端子をGNDピンに接続します。これで完了です!Arduinoの内蔵プルアップ抵抗を使用するため、外部抵抗は必要ありません。

 

コードの解説

プログラムは、ピン定義、setup()関数、loop()関数の3つの主要部分に分けられます。

ピン定義

このセクションでは、必要なライブラリを設定し、使用するピンに意味のある名前を割り当てます。

#include <Servo.h>

const int servoPin = 3;
const int buttonPin = 2;

Servo myServo;

setup()関数

setup()関数には、Arduinoボードの電源投入時またはリセット時に一度だけ実行されるコードが含まれています。初期設定に使用されます。

void setup() {
  myServo.attach(servoPin);
  pinMode(buttonPin, INPUT_PULLUP);
  myServo.write(0);
}

重要な変更点はpinMode(buttonPin, INPUT_PULLUP);です。これにより、ピンの電圧をHIGHに引き上げる内部抵抗が有効になります。ボタンを押すと、ピンが接地に接続され、電圧がLOWに下がります。

loop()関数

loop()関数にはメインのプログラムロジックが含まれており、setup()関数が終了した後、繰り返し永久に実行されます。

void loop() {
  int buttonState = digitalRead(buttonPin);

  if (buttonState == LOW) {
    myServo.write(180);
  } else {
    myServo.write(0);
  }
}

ここでのロジックは逆になっています。ボタンを押すとLOW信号になるため、if (buttonState == LOW)条件を使用してサーボを180度に動かします。

画像

Arduino wiring for Servo motor with a push button
Arduino wiring for Servo motor with a push button
795-Ardunino code to control servo motor using a push button to move between 180 and zero degree
言語: C++
#include <Servo.h>
/*
 * This is sketch for controlling servo motor. when push button is pressed, the servo moves to 180 degreees and stays there. when the push button is released, the servo motor returns back to 0 degree.
 */
 // Define the pin for the servo motor
const int servoPin = 3;
 // Define the pin for the push button
const int buttonPin = 2;

 // Create a Servo object
Servo myServo;

void setup() {
 // Attach the Servo object to the servo pin
  myServo.attach(servoPin);
 // Set the button pin as an input
  pinMode(buttonPin, INPUT);
 // Start the servo at 0 degrees
  myServo.write(0);
}

void loop() {
 // Read the state of the push button
  int buttonState = digitalRead(buttonPin);

 // If the button is pressed (HIGH)
  if (buttonState == HIGH) {
 // Move the servo to 180 degrees
    myServo.write(180);
  } else {
 // If the button is released (LOW), move the servo back to 0 degrees
    myServo.write(0);
  }
}

必要かもしれないもの

リソースと参考文献

まだリソースはありません。

ファイル📁

ファイルは利用できません。