我正在构建一个互联网控制的机器人,它使用 2 部 Android 手机进行控制。 第一个手机通过 USB 连接到 Arduino Uno 并用作 3G 扩展板 第二部电话用于控制整个事情。它将未分配的字节发送到第一部手机,然后再将其发送到 Arduino。 我在手机上使用的应用程序有一个问题。应用程序中的操纵杆在静止时不会发送特定命令。例如,当我向上移动它时,它会向连接到 Arduino 的手机发送“1”,从而驱动电机向前移动,但是当我释放操纵杆时,它会停止发送数据,但是我的机器人上的电机仍然旋转,直到我向下移动操纵杆,发送数据"2" 电机.run(RELEASE);
如果没有可用的串行数据,如何停止电机?
这是我写的代码。
#include <AFMotor.h>
AF_DCMotor motor_left(2, MOTOR12_1KHZ);
AF_DCMotor motor_right(3, MOTOR12_1KHZ);
int ledPin = 13;
int speed_min = 100; //the minimum "speed" the motors will turn - take it lower and motors don't turn
int speed_max = 1000; //the maximum "speed" the motors will turn – you can’t put in higher
int speed_left = speed_max; // set both motors to maximum speed
int speed_right = speed_max;
int command = 0;
void setup ()
{
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
motor_left.setSpeed(255);
motor_left.run(RELEASE);
motor_right.setSpeed(255);
motor_right.run(RELEASE);
motor_left.setSpeed(speed_left); // minimum speed 135 max speed 255
motor_right.setSpeed(speed_right); // minimum speed 135 max speed 255
}
void loop() {
if (Serial.available() > 0);
byte command = Serial.read();
if (command == 1)
{
Serial.println("Move Forward");
digitalWrite(ledPin, HIGH);
motor_left.run(FORWARD);
}
if (command == 2)
{
Serial.println("Stop");
digitalWrite(ledPin, LOW);
motor_left.run(RELEASE);
}
}
所以基本上,如果没有可用数据,它应该什么也不做。
像这样使用你的代码,会有帮助
void loop() {
if (Serial.available() > 0) {
byte command = Serial.read();
if (command == 1) {
Serial.println("Move Forward");
digitalWrite(ledPin, HIGH);
motor_left.run(FORWARD);
} else if (command == 2) {
Serial.println("Stop");
digitalWrite(ledPin, LOW);
motor_left.run(RELEASE);
} else {
//put your code to stop Motor
}
}
}