Search code examples
androidarduinoandroid-wifi

Connecting arduino to android using wifi Shield


I am trying to connect arduino Uno to android device using Wifi over a Common Lan connection but the following code is not giving me any response from Arduino. Arduino is working well with the desktop checking code.Here is my android part of the code on click of a toggle button

//WIFI socket code
    ToggleButton toggle = (ToggleButton) findViewById(R.id.wifiTButton);
    toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {

                // wifi thread code

                final Runnable r = new Runnable()
                {
                    public void run() 
                    {

                     Socket socket = null;
                     DataOutputStream dataOutputStream = null;
                     DataInputStream dataInputStream = null;
                    textOut = (TextView) findViewById(R.id.textOut);
                     textIn=(EditText)  findViewById(R.id.textIn);
                     try {
                      socket = new Socket("10.0.0.101", 7);
                     dataOutputStream = new DataOutputStream(socket.getOutputStream());
                      dataInputStream = new DataInputStream(socket.getInputStream());
                      dataOutputStream.writeByte(111111);
                      //dataOutputStream.writeUTF("111111".toString() );//textOut.getText().toString());
                      textIn.setText(dataInputStream.readByte());
                     // textIn.setText(dataInputStream.readUTF());
                        Log.d(TAG, " why is not working");

                    } catch (UnknownHostException e) {
                        Log.d(TAG, "Unknown Host");
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        Log.d(TAG, "Input Output Exception");
                        e.printStackTrace();
                    }                   
                     finally{
                      if (socket != null){
                       try {
                        socket.close();
                       } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                       }
                      }

                      if (dataOutputStream != null){
                       try {
                        dataOutputStream.close();
                       } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                       }
                      }

                      if (dataInputStream != null){
                       try {
                        dataInputStream.close();
                       } catch (IOException e) {
                        e.printStackTrace();
                       }
                      }
                     }

                      handler.postDelayed(this, 1000);
                    }
                };

              handler.postDelayed(r, 1000);


             } 

        }
    });

Solution

  • I was able to solve the problem. It is running well with the command button instead of a toggle button and properly using the thread syntax. Here is a sample application mainActivity code.

    package com.example.arduinoandroid;
    
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Handler;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
     import android.widget.Toast;
        public class MainActivity extends Activity {
    Handler handler;
    String TAG = "main Activity";
    Button bt1;
    TextView textOut;
    EditText editIn;
    static byte abc;
    Socket socket = null;
    DataOutputStream dataOutputStream = null;
    DataInputStream dataInputStream = null;
    
    class Task implements Runnable {
    
        @Override
        public void run() {
    
            try {
                socket = new Socket("10.0.0.101", 7);
                dataOutputStream = new DataOutputStream(
                        socket.getOutputStream());
                dataInputStream = new DataInputStream(socket.getInputStream());
    
                dataOutputStream.writeByte(111);
    
                // dataOutputStream.writeUTF("111111".toString()
                // );//textOut.getText().toString());
                abc = dataInputStream.readByte();
                Toast.makeText(getBaseContext(), abc, Toast.LENGTH_SHORT)
                        .show();
                // textIn.setText(dataInputStream.readUTF());
                Log.d(TAG, " why is not working");
    
            } catch (UnknownHostException e) {
                Log.d(TAG, "Unknown Host");
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                Log.d(TAG, "Input Output Exception");
                e.printStackTrace();
            }
    
            finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
    
                if (dataOutputStream != null) {
                    try {
                        dataOutputStream.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
    
                if (dataInputStream != null) {
                    try {
                        dataInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
            handler.post(new Runnable() {
    
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    textOut.setText("working ae");
                }
    
            });
    
        }
    
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        handler = new Handler();
        // WIFI socket code
        bt1 = (Button) findViewById(R.id.chkButton1);
        textOut = (TextView) findViewById(R.id.textOut);
        editIn = (EditText) findViewById(R.id.editIn);
        bt1.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View v) {
    
                new Thread(new Task()).start();
    
            }
    
        });
    
    }
    
     }
    

    and the code for xml part is

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${packageName}.${activityClass}" >
    
    <Button
        android:id="@+id/chkButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="140dp"
        android:text="Check wifi" />
    
    <TextView
        android:id="@+id/textOut"
        android:layout_width="wrap_content"
        android:layout_height="39dp"
        android:layout_gravity="bottom|right"
        android:text="Output" />
    
    <EditText
        android:id="@+id/editIn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:ems="10"
         android:text="111111"/>
      </LinearLayout>
    

    Please include the following permissions in the manifest file

    <uses-permission android:name="android.permission.INTERNET"/> 
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />