2017-02-10 70 views
-1

我正在構建一個使用2個Android手機進行控制的互聯網控制機器人。 第一部手機通過USB連接到Arduino Uno並作爲3G屏蔽 第二部手機用於控制整個事物。它將未分配的字節發送給第一個將其發送給Arduino的手機。 我在手機上使用的應用程序有一個問題。應用程序中的遊戲杆在休息時不發送特定命令。例如,當我將它向上移動時,向連接到Arduino的手機發送「1」,以便向前驅動電機,但當釋放操縱桿時會停止發送數據,但是我的機器人上的電機仍會旋轉,直到我向下移動操縱桿, 「2」motor.run(RELEASE);如果沒有可用的串行數據,如何退出Arduino中的void loop?

如果沒有可用的串行數據,我該如何停止電機?

這是我寫的代碼。

#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); 
} 

} 

所以基本上它應該什麼也不做,如果沒有可用的數據。

回答

0

用你這樣的代碼,這將有助於

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 
       } 


      } 
     } 
+0

不幸的是這並沒有爲電機stoppes紡紗工作。我想這是因爲時機。當Arduino接收到「1」時,下一步是執行else語句,並且由於兩種情況幾乎在同一時間執行,所以motos沒有足夠的時間旋轉。我試圖給其他人增加100ms延遲,但在這種情況下,我的電機每隔100ms停一段時間。 – Fender90

+0

我編輯了我的答案,請檢查 如果問題與您所描述的完全相同,那麼它應該可以工作 –