Asif Ali Khan
Asif Ali Khan

Reputation: 49

Cannot send string values one by one to Arduino from a Bluetooth Android app

I am working on a project where I pass string one by one to Arduino from my android app using Bluetooth. The following is my java code.I send string values to this function one by one.The problem here is I receive only one value in the Arduino serial monitor.The remaining values are not received.

public static  void getDistance(float x){
    String xMoved = Float.toString(x);

    Log.d(TAG, "getDistance: called");
    try {
        mBTSocket.getOutputStream().write(xMoved.getBytes());

    } catch (IOException e) {
        e.printStackTrace();
        Log.d(TAG, "getDistance: "+e);
    }
    finally {
        Log.d(TAG, "getDistance:"+"try catch successful");
    }
}

The following is the the code in my arduino:

/* Example sketch to control a 28BYJ-48 stepper motor with ULN2003 driver board and Arduino UNO. More info: https://www.makerguides.com */
// Include the Arduino Stepper.h library:
#include <Stepper.h>
// Define number of steps per rotation:
const int stepsPerRevolution = 2048;
// Wiring:
// Pin 8 to IN1 on the ULN2003 driver
// Pin 9 to IN2 on the ULN2003 driver
// Pin 10 to IN3 on the ULN2003 driver
// Pin 11 to IN4 on the ULN2003 driver
// Create stepper object called 'myStepper', note the pin order:
int  state;
String command;
Stepper myStepper = Stepper(stepsPerRevolution,2,4,3,5);
void setup() {
  // Set the speed to 5 rpm:
  myStepper.setSpeed(15);

  // Begin Serial communication at a baud rate of 9600:
  Serial.begin(9600);
}
void loop() {

  if(Serial.available()){

    command = Serial.readStringUntil('\n');
    state = command.toInt();
    Serial.println(state);

    myStepper.step(state);

}
}

The following is my logcat:

enter image description here

I am confused what am I doing wrong?Anybody please help me out with this.

Upvotes: 0

Views: 160

Answers (1)

Codebreaker007
Codebreaker007

Reputation: 2989

As mentioned you need a "newline" Try

mBTSocket.getOutputStream().write(xMoved.getBytes() +"\n");

There might also be the "problem" of unwanted chars send to evade this you should flush the buffer after transmission

mBTSocket.flush();

Upvotes: 2

Related Questions