天天看點

Android GPIO控制方法

方法1: Android Things 外設I/O-GPIO: 可參考文章: https://www.jianshu.com/p/d33c4b832bf0

方法2:

GPIO0對應系統節點如: /sys/class/backlight/rk28_bl/gpio0

//讀GPIO

private String getGpioString(String path) {
                String defString = "0";// 預設值
                try {
                        @SuppressWarnings("resource")
                        BufferedReader reader = new BufferedReader(new FileReader(path));
                        defString = reader.readLine();
                } catch (IOException e) {
                        e.printStackTrace();
                }
                return defString;
        }

getGpioString("/sys/class/backlight/rk28_bl/gpio0")   傳回字元串“0” 或者“1”
           

//将GPIO口設定為輸出的時候,預設是輸出,調用下面的方法即可變成預設輸入

public boolean gpio_input0() {
	return  RootCommand("echo  2 > /sys/class/backlight/rk28_bl/gpio0");
}
           

//當GPIO口為輸出的時候,通過以下的辦法來控制高低電平

private boolean set_gpio0_high() {   //拉高
		boolean FLAG = RootCommand("echo  1 > /sys/class/backlight/rk28_bl/gpio0");
		return FLAG;
	}
public boolean set_gpio0_low() {    //拉低
		boolean FLAG =  RootCommand("echo 0 >/sys/class/backlight/rk28_bl/gpio0");
		return FLAG;
	}
           

//下面的是執行的方法

private boolean RootCommand(String command) {
		Process process = null;
		DataOutputStream os = null;
		try {
			process = Runtime.getRuntime().exec("su");
			os = new DataOutputStream(process.getOutputStream());
			os.writeBytes(command + "\n");
			os.writeBytes("exit\n");
			os.flush();
			process.waitFor();
		} catch (Exception e) {
			return false;
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				process.destroy();
			} catch (Exception e) {
			}
		}
		return true;
	}