-1

I am trying to communicate Arduino Uno with an android phone. What I trying to is:

  1. Android device post a string to Arduino

  2. Arduino post a integer to Android

So far I can post message from Android, received in Arduino board, but I can not post a integer to Android, nothing receive at Android

Arduino Code (Which can receive character "a", "b", "c", "d", and for case "z", I would like to send back the distance which is an int) :

void loop()
{ 
  distance = Dist.getDistanceCentimeter();
  if(distance<=5 & distance>1)
  {
    back();
    delay(100);
    ting();
    distance=0;
  } 
  if(Serial.available())
  {
    lkf = Serial.read();
  switch(lkf)
  {
  case 'a':
     front();
     servoX.write(90);
     lkf=0;  
     break;   
   case 'b':
     back();
     lkf=0;
     break;     
   case 'c':
     left();
     lkf=0;
     break;
   case 'd':
     right();
     lkf=0;
     break; 
  case 'z':
    Serial.write(distance);
    break; 
    }
  }
 }

Android Code:

In Main Activity

@Override
protected TCPClient doInBackground(String... message) {

    //create TCPClient object 
    mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
        @Override
        //check whether server return message
        public void messageReceived(String message) {
            f_sensor.setText(message);
            Log.d("test1","msg rece" + message);
            //publishProgress(message);
        }
    });
    mTcpClient.run();

    return null;
}

TCP Cilent

public class TCPClient {

    private String serverMessage;
    public static final String SERVERIP = "192.168.8.1"; //your computer IP address
    public static final int SERVERPORT = 2001;
    private OnMessageReceived mMessageListener = null;
    private boolean mRun = false;

    PrintWriter out;
    BufferedReader in;

    /**
     *  Constructor of the class. OnMessagedReceived listens for the messages received from server
     */
    public TCPClient(OnMessageReceived listener) {
        mMessageListener = listener;
    }

    /**
     * Sends the message entered by client to the server
     * @param message text entered by client
     */
    public void sendMessage(String message){
        if (out != null && !out.checkError()) {
            out.println(message);
            out.flush();
        }
    }

    public void stopClient(){
        mRun = false;
    }

    public void run() {

        mRun = true;

        try {
            //here you must put your computer's IP address.
            InetAddress serverAddr = InetAddress.getByName(SERVERIP);

            Log.e("TCP Client", "C: Connecting...");

            //create a socket to make the connection with the server
            Socket socket = new Socket(serverAddr, SERVERPORT);

            try {

                //send the message to the server
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

                Log.e("TCP Client", "C: Sent.");

                Log.e("TCP Client", "C: Done.");

                //receive the message which the server sends back
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                //in this while the client listens for the messages sent by the server
                while (mRun) {
                    serverMessage = in.readLine();

                    if (serverMessage != null && mMessageListener != null) {
                        //call the method messageReceived from MyActivity class
                        mMessageListener.messageReceived(serverMessage);
                    }
                    serverMessage = null;

                }

                Log.d("test1",serverMessage);
                Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");

            } catch (Exception e) {

                Log.e("TCP", "S: Error", e);

            } finally {
                //the socket must be closed. It is not possible to reconnect to this socket
                // after it is closed, which means a new socket instance has to be created.
                socket.close();
            }

        } catch (Exception e) {

            Log.e("TCP", "C: Error", e);

        }

    }

    //Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
    //class at on asynckTask doInBackground
    public interface OnMessageReceived {
        public void messageReceived(String message);
    }
}
  • 1
    Your Android code purports to talk TCP, while your Arduino is talking Serial. Somewhere in between is an unspecified translation which may be a source of trouble. Your Android code looks improperly structured - you should not be creating a server object for a single use in an AsyncTask (which by default is now blocking) as you appear to be with doInBackground() but rather maintaining one within a background thread mechanism designed to continue running independent of others. Finally, your Arduino code will only transmit when it receives something, and it is unclear that it is doing so. – Chris Stratton Mar 9 '15 at 14:25
0

Using serial.println instead of serial.write fixes the issue.

  • 1
    If you are going to use a readLine() type method on the receiver, yes, you will need to transmit a terminating newline. However, a lot of others aspects of your design remain suspicious and potential sources of future issues, too - particularly the way you are doing threading on the Android side. – Chris Stratton Mar 10 '15 at 12:53
  • @ChrisStratton no, the issue's related to this: the .write() function sends the ASCII code, .print() converts it to a string. So Serial.write(65) would send A, Serial.print(65) would send 6, 5. The println would also add a newline character. So the issue is they were sending the ASCII code instead of the string composed of ASCII codes. – Anonymous Penguin Mar 10 '15 at 22:09
  • One issue. My point is they have others as well. – Chris Stratton Mar 11 '15 at 0:18
  • Entirely replacing the poster's answer with your own words is not appropriate, especially when you still fail to state the cause of the specific observed issue (no data, not unexpected data). If you want to offer your opinion do so in a comment, or post your own answer which may be judged by the community on its merits. – Chris Stratton Mar 11 '15 at 0:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.