0

I'm building an app in Android to communicate with Arduino via usb.

In Android, I create a button to send data to the Arduino. The Arduino should then respond to this message and send another message to be treated in the function of the same button. The problem is that when I click on the button the app stops.

My Arduino code:

        void setup()  
    {  
    Serial.begin(9600); 
    }  
    void loop()  
    {
     char c;
     int i = 0;
     if(Serial.available()){
     c=Serial.read();
     if (c == '4'){
      Serial.write("X:100 Y:10");
     }
    }
    }

Defining a Callback which triggers whenever data is read in Android:

UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
    @Override
    public void onReceivedData(byte[] arg0) {
        String data = null;
        try {
            data = new String(arg0, "UTF-8");
            data.concat("\n");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
};

The button function in Android is:

public void goBefore(View view) {
    ssend = "M114"; // send message to update current position
    serialPort.write(ssend.getBytes());
    String[] current_Pos = data.split(" ");

Do you know what I'm doing wrong?

Hayden Eastwood
  • 928
  • 2
  • 10
  • 20
Nana
  • 1
  • 2
  • If your app stops there is a crash caused by an exception. Post the stacktrace from the logcat. It will tell you what went wrong. – blackapps Apr 26 '20 at 14:48
  • Does it stop because of code in onReceiveData ? Please tell better what happens. – blackapps Apr 26 '20 at 14:49
  • I think the app stop because i have used the variable "data" before receiving it – Nana Apr 26 '20 at 17:21
  • if I remove the line "String[] current_Pos = data.split(" ");" in the function goBefore, I have no problem and receive the message. but what i need is treating this message in the function goBefore not out of it. – Nana Apr 26 '20 at 17:29
  • Call goBefore() in onReceiveData(). – blackapps Apr 27 '20 at 07:31
  • If i call goBefor() in onReceiveData(), it will send the data "M114" again. – Nana Apr 27 '20 at 07:57
  • Change your scenario. The flow. And you should not handle data if there is no data. Is it null then? Check. – blackapps Apr 27 '20 at 08:05
  • Sorry, but I don't understand what what did you mean. – Nana Apr 27 '20 at 08:39

0 Answers0