设置为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
一遍又一遍。伺服器只是来回抽动。它唯一更改的时间(要设置的数字来自Processing程序)是将其设置为180时的数字。然后它来回移动得更多,并说:
Current Rotation:
179
Set to:
180
Writing to servo
Current Rotation:
179
Set to:
180
Writing to servo
一遍又一遍。怎么回事,我该如何解决?干杯,谢谢您的帮助!
答案 0 :(得分:1)
您的代码存在一些问题:
您无需读取当前伺服值,只需保存最后给出的值即可。
逐步移动伺服不是一个好的选择,因为它可能会出现一些移动错误。您需要根据移动阈值找到动态延迟。例如,假设您的伺服器从0到180完全移动的最大延迟时间是2秒,那么如果您需要将伺服器移动90度,则需要1秒的延迟。
您只需要在收到新数据时移动伺服,因此在收到新数据时设置伺服即可。
请记住要根据您的伺服器设置max_delay
。
#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;
// how much time takes servo to move
int move_delay = 0;
// maximum time for changing servo state from lowest to highest value
const int max_delay = 2;
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
Serial.print("New value: ");
Serial.println(rotation);
Serial.print("Current Rotation: ");
Serial.println(rotation);
if (currentRotation != rotation)
{
Serial.println("Setting new value");
// find a proper delay
move_delay = (max_delay / 180) * (abs(rotation - currentRotation)) * 1000;
myServo.write(rotation);
delay(move_delay);
currentRotation = rotation;
}
}
}