Arduino String Comparison

319 Views Asked by At

I have some data coming in through bluetooth serial and I have a very simple if statement to decide what to do next, however it is not firing as expected. I am total Arduino newb, does anyone know why this is happening?

Here is the log output as well as the full code, the main suspect at the moment is controlArm method.

Log Output

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

Full Code:

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

}
1

There are 1 best solutions below

4
On

So I am not sure what the issue was, but here is a better way of doing this that works, in the main loop:

void loop() {
  while(Bluetooth.available()){  
    String Data = Bluetooth.readStringUntil('\n');
    Serial.println(Data);
    controlArm(Data);
  }
}