Created
December 21, 2024 13:01
-
-
Save jimmy947788/2282a46434b473e03d569fc03e3d2edc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Servo.h> | |
// 修改可用:https://www.thingiverse.com/thing:2847024 | |
// 原始專案:https://www.thingiverse.com/thing:1258082 | |
const int switchPin = 2; // 開關連接到 D2 | |
const int servoPin = 9; // SG90 伺服馬達連接到 D9 | |
Servo myServo; // 創建伺服對象 | |
int switchState = 0; // 當前開關狀態 | |
int lastSwitchState = 1; // 上一次開關狀態 (初始為 OFF,因為使用 INPUT_PULLUP) | |
int servoAngle = 10; // 當前伺服角度 (初始為 10°) | |
void setup() { | |
pinMode(switchPin, INPUT_PULLUP); // 使用內建上拉電阻 | |
myServo.attach(servoPin); // 連接伺服馬達 | |
myServo.write(servoAngle); // 初始化伺服角度為 10° | |
Serial.begin(9600); // 初始化序列埠,波特率設為 9600 | |
} | |
void loop() { | |
switchState = digitalRead(switchPin); // 讀取開關狀態 | |
// 打印當前開關狀態 | |
if (switchState == LOW) { | |
Serial.println("Switch State: ON"); // 開關 ON | |
} else { | |
Serial.println("Switch State: OFF"); // 開關 OFF | |
} | |
// 開關從 OFF -> ON,伺服慢慢轉到 180° | |
if (switchState == LOW && lastSwitchState == HIGH) { | |
Serial.println("Switch turned ON: Rotating to 180°"); | |
for (int angle = servoAngle; angle <= 180; angle++) { | |
myServo.write(angle); | |
delay(10); // 調整速度 | |
} | |
servoAngle = 180; // 更新當前角度 | |
} | |
// 開關從 ON -> OFF,伺服快速回到 10° | |
else if (switchState == HIGH && lastSwitchState == LOW) { | |
Serial.println("Switch turned OFF: Returning to 10°"); | |
myServo.write(10); | |
delay(100); // 快速旋轉回 10° | |
servoAngle = 10; // 更新當前角度 | |
} | |
// 記錄上一次開關狀態 | |
lastSwitchState = switchState; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
公開