android客户端控制树莓派GPIO点亮LED灯

  首先需要android客户端与树莓派进行连接,树莓派与android客户端利用wifi连接并进行socket通信请参考我的另一片文章:https://mp.csdn.net/postedit/79911322 。树莓派与Android客户端连接成功后就可以开始让android客户端给树莓派发送指令控制树莓派GPIO口的电平输出

    首先需要搞清楚树莓派的GPIO引脚,这里我用的树莓派3B,其引脚图参数如下:

    上图中左右依次对应,而我这里利用的是23、24(GPIO.4、GPIO.5)两个引脚分别来点亮2个LED灯。

    先贴上跑在树莓派上的python代码(代码很简单我就不写注释了,有问题可以留言):

import socket
import time
import sys
import RPi.GPIO as GPIO
import time

GPIO_PIN = 23

HOST_IP = "192.168.12.1"
HOST_PORT = 7654

GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.OUT)    #用到的引脚必须要先setup
GPIO.setup(24, GPIO.OUT)

print("Starting socket: TCP...")
socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print("TCP server listen @ %s:%d!" %(HOST_IP, HOST_PORT) )
host_addr = (HOST_IP, HOST_PORT)
socket_tcp.bind(host_addr)
socket_tcp.listen(1)	

while True:
	print ('waiting for connection...')
	socket_con, (client_ip, client_port) = socket_tcp.accept()
	print("Connection accepted from %s." %client_ip)

	socket_con.send("Welcome to RPi TCP server!")

	while True:
		data=socket_con.recv(1024)
		if data:
			print(data)	
			while True:
				ctlmsg=socket_con.recv(1024)
				if ctlmsg=="device1":
					GPIO_PIN=23
				if ctlmsg=="device2":
					GPIO_PIN=24	
				if ctlmsg=="turn_on":
					print("************turn on********")
					GPIO.output(GPIO_PIN,GPIO.HIGH)
				if ctlmsg=="turn_off":
					print("************turn off********")
					GPIO.output(GPIO_PIN,GPIO.LOW)
				if ctlmsg=="exit":
					print("*************exit from device_control************")
					break
				
socket_tcp.close()

    接下来是android客户端的实现,先看xml布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context="woyou.wifidemo.ui.activity.Device_Control_Activity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_weight="2"
            android:text="设备选择:"
            android:textSize="20dp"/>
        <Spinner
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:layout_weight="8"
            android:id="@+id/sp_dev_select"/>
    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="80dp" />
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_weight="1"
            android:id="@+id/bt_dev1_on"
            android:text="开启"/>
        <TextView
            android:layout_width="20dp"
            android:layout_height="wrap_content" />
        <Button
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:layout_weight="1"
            android:id="@+id/bt_dev1_off"
            android:text="关闭"/>
    </LinearLayout>

</LinearLayout>

    接下来是功能实现:

package woyou.wifidemo.ui.activity;

import android.support.annotation.NonNull;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import woyou.wifidemo.R;
import woyou.wifidemo.utils.Socket_Utils;


public class Device_Control_Activity extends ActionBarActivity {

    Button bt_dev1_on;
    Button bt_dev1_off;
    Spinner spinner;
    private String[] dev = {"设备一","设备二"};
    private List<String> dev_list = null;
    private ArrayAdapter adapter = null;

    String device_select = "设备一";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setTitle("设备控制");
        setContentView(R.layout.activity_device__control_);
        initView();
        initSpiner();
        onlistener();
    }

    private void initSpiner() {
        for (int i=0 ; i < dev.length ; i++)
            dev_list.add(dev[i]);
        adapter = new ArrayAdapter(this , android.R.layout.simple_list_item_1 , dev_list);
        adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);//为adapter分配样式:单选
        spinner.setAdapter(adapter);
    }


    private void onlistener() {
        bt_dev1_on.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Socket_Utils.send(Socket_Utils.socket , "turn_on");    //给树莓派发送turn_on
            }
        });
        bt_dev1_off.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Socket_Utils.send(Socket_Utils.socket , "turn_off");    //给树莓派发送turn_off
            }
        });

        //下拉框的设备选择监听
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ArrayAdapter<String> adapter = (ArrayAdapter<String>) parent.getAdapter();
                device_select = (String) adapter.getItem(position);
                if (device_select.equals("设备一"))
                    Socket_Utils.send(Socket_Utils.socket , "device1");    //给树莓派发送device1
                if (device_select.equals("设备二"))
                    Socket_Utils.send(Socket_Utils.socket , "device2");    //给树莓派发送device2

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


    }

    private void initView() {
        bt_dev1_off = (Button) findViewById(R.id.bt_dev1_off);
        bt_dev1_on = (Button) findViewById(R.id.bt_dev1_on);
        spinner = (Spinner) findViewById(R.id.sp_dev_select);
        dev_list = new ArrayList<String>();
    }
}

    主要实现了一个下拉选择框选择设备(LED灯),然后给树莓派发送相关指令控制树莓派的GPIO口进而控制小灯泡亮灭

    看一下效果:

由于我的项目中需要用到继电器来控制设备,所有我加了个继电器,大家完全可以去掉继电器,我的接线图如下:    



设备1开(LED1亮),由于太亮,我用手指挡住了,效果好点


切换设备



设备2开(LED2亮)



阅读更多

没有更多推荐了,返回首页