【发布时间】:2019-11-12 13:27:48
【问题描述】:
我的伺服器只有在设置为 180 度时才开始“改变”(这就是代码告诉我的)。
我曾尝试搜索该网站以及 Google,但这似乎与以高级不可重复的方式写入 Servo 非常具体有关。
改变舵机的代码是:
#include <SoftwareSerial.h>
#include <Servo.h>
const int rxPin = 12;
const int txPin = 13;
SoftwareSerial bluetooth (rxPin, txPin);
Servo myServo;
boolean canMove = true;
int rotation = 0;
int currentRotation = 0;
void setup() {
Serial.begin(9600); // Begins Serial communication
bluetooth.begin(9600);
myServo.attach(11); // Sets a servo on pin 11
}
void loop() {
// put your main code here, to run repeatedly:
// Checks if Serial has something to read
if (bluetooth.available() > 0) {
rotation = bluetooth.read(); // Reads it and sets it to an integer
}
currentRotation = myServo.read();
if (currentRotation != rotation) {
Serial.println("Current Rotation:");
Serial.println(currentRotation);
Serial.println("Set to:");
Serial.println(rotation);
for (int i = currentRotation; i < rotation; i++) {
Serial.println("Writing to servo");
myServo.write(i);
}
}
}
有一个将数据发送到 Arduino 的处理程序,但我可以完全看到数字正在进入 Arduino 的串行监视器(它们从 0 到 180 不等)
完成此操作后,串行监视器中显示的唯一内容是:
Current Rotation:
93
Set to:
0
Current Rotation:
93
Set to:
0
Current Rotation:
93
Set to:
0
Current Rotation:
93
Set to:
0
Current Rotation:
93
Set to:
0
一遍又一遍。伺服器只是来回抽动。它唯一改变的时候(设置的数字来自处理程序)是当它设置为 180 时。然后它来回移动更多,并说:
Current Rotation:
179
Set to:
180
Writing to servo
Current Rotation:
179
Set to:
180
Writing to servo
一遍又一遍。发生了什么事,我该如何解决?干杯,感谢您的帮助!
【问题讨论】:
-
你到底想做什么?您想从蓝牙接收值并将伺服(逐步)移动到该值吗?我也不明白你为什么使用循环来移动伺服,为什么不直接将值写入伺服?
-
@M.R.第一部分是对的。我想使用循环,这样我就不必使用延迟来确保它在代码返回并再次执行之前完成,因为当前的旋转不是它设置的旋转,这会导致错误。因此,for 循环确保在伺服被写入之前不会发生任何事情。
-
你的 for 循环只处理当前旋转小于旋转的情况,因为你有一个较小的然后检查
-
@Ferrybig 哦!你说的对。谢谢!