-1

我有一些通过蓝牙串行输入的数据,我有一个非常简单的 if 语句来决定下一步要做什么,但是它没有按预期触发。我完全是 Arduino 新手,有人知道为什么会这样吗?

这是日志输出以及完整代码,目前主要怀疑是 controlArm 方法。

日志输出

01:41:37.678 -> A
01:41:37.678 -> 
01:41:37.678 -> 
01:41:37.678 -> 
01:41:37.678 -> Received: A
01:41:37.678 -> controlArm (A)
01:41:37.678 -> Else Move
01:41:37.678 -> moveArm 0 90 45 180 180 90 10
01:41:43.286 -> 1
01:41:43.286 -> 
01:41:43.286 -> 
01:41:43.286 -> 
01:41:43.286 -> Received: 1
01:41:43.286 -> controlArm (1)
01:41:43.286 -> Else Move
01:41:43.286 -> moveArm 0 90 45 180 180 90 10
01:41:47.300 -> 2
01:41:47.300 -> 
01:41:47.300 -> 
01:41:47.300 -> 
01:41:47.300 -> Received: 2
01:41:47.300 -> controlArm (2)
01:41:47.300 -> Else Move
01:41:47.332 -> moveArm 0 90 45 180 180 90 10

完整代码:

#include <SoftwareSerial.h>
#include <Braccio.h>
#include <Servo.h>


Servo base;
Servo shoulder;
Servo elbow;
Servo wrist_rot;
Servo wrist_ver;
Servo gripper;

SoftwareSerial Bluetooth(8, 7);
int M0 = 0;
int M1 = 90;
int M2 = 45;
int M3 = 180;
int M4 = 180;
int M5 = 90;
int M6 = 10;

void setup() {  
    Bluetooth.begin(38400);   
  Serial.begin(9600);
  Braccio.begin();
  Braccio.ServoMovement(20,  20, 90, 90, 90, 90,  10); 

}

void moveArm(){
 
  Serial.println("moveArm " + String(M0) + " " + String(M1) + " " + String(M2) + " " + String(M3) + " " + String(M4) + " " + String(M5) + " " + String(M6));
  Braccio.ServoMovement(M0, M1, M2, M3, M4, M5, M6); 
  }



// This is the main suspect
void controlArm(String command){
  Serial.println("controlArm (" + command+")");
  if (command.equals("1")) {
    M6 = 0;
    moveArm();
  } else if (command == '2'){
    M6 = 30;
    moveArm();
  } else if (command == "A"){
    M6 = 73;
    moveArm();
  } else {
    Serial.println("Else Move");
    moveArm();
  }
}
  
  String Data = "";
void loop() {
  while(Bluetooth.available()){
    char character = Bluetooth.read();
    Serial.println(character);
    if (character == '\n'){
        Serial.print("Received: ");
        Serial.println(Data);
        controlArm(String(Data));
        Data = "";
    } else {
      Data.concat(character);
    }
  }

}
4

1 回答 1

0

所以我不确定问题出在哪里,但是在主循环中,这是一种更好的方法:

void loop() {
  while(Bluetooth.available()){  
    String Data = Bluetooth.readStringUntil('\n');
    Serial.println(Data);
    controlArm(Data);
  }
}
于 2020-07-11T07:09:02.640 回答