android对接单片机wifi模块

最近搞了两个项目。一个对接wifi模块的智能床垫,一个对接串口的开柜功能。分享一下,感觉对初学者有帮助。

有开发需求或者解决不了单片机通讯的可以联系我。乐意解答。vx:13335208818

对接wifi模块流程:

1.硬件方面设置好wifi模块的热点名称

2.android连接这个热点

3.用户选择家庭常用wifi热点以及密码

4.连接并将热点名称以及密码发给单片机

5.解决。

其实可以直接连接后通讯,就可以省下发送wifi热点密码的环节,但是弊端较大,用户手机必须连接我们的wifi热点,这样影响他的其他功能,还是走这个环节比较好。

通讯代码:

 

    String dataToServer = "SETAP:\"ADAD\",\"1226545D\"";

    static PrintWriter mPrintWriterClient = null;
    TextView zz;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        zz = (TextView) findViewById(R.id.zzz);


        new Thread1().start();


        Toast.makeText(MainActivity.this, "绑定成功", Toast.LENGTH_LONG).show();
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(intent);

    }

    class Thread1 extends Thread {

        @Override
        public void run() {
            try {
                
                Socket socket = new Socket("192.168.4.1", 5060);
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                mPrintWriterClient = new PrintWriter(socket.getOutputStream(), true);
                String line = mPrintWriterClient.toString();
                String z = line;
                zz.setText("Message from server " + line);


                sendMsg();
                br.close();
                socket.close();


            } catch (UnknownHostException e) {
// TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
// TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public void sendMsg() {
        String info = dataToServer;

        Log.i("ContentOfEditText", info);
        try {
            Socket socket = new Socket("192.168.4.1", 5060);
            OutputStream out = socket.getOutputStream();
            out.write(info.getBytes("UTF-8"));

            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

 

你可能感兴趣的:(android)