一、什么是GPIO?
GPIO(英语:General-purpose input/output),通用型输入输出端口,在单片机上一般是通过一个GND引脚和若干个io引脚配合工作。
单片机可以配置GPIO输入输出模式,与外界环境进行通信交互。在输入环境下,可以读取指定端口的高低电平状态。在输出环境下,可以控制指定端口的高低电平状态。
二、Android GPIO通信
使用Runtime.getRuntime()获取本地GPIO文件并与之通信,直接上代码。
/*** gpio通讯工具*/
class GpioUtil private constructor(){companion object{private var instance:GpioUtil?=nullget() {if (field == null) {field = GpioUtil()}return field}@Synchronizedfun get():GpioUtil{return instance!!}}/*** 执行外部程序指令** @param instruct 指令*/fun chmod(instruct: String?) {try {val runtime = Runtime.getRuntime()val process = runtime.exec("su")val dataOutputStream = DataOutputStream(process.outputStream)dataOutputStream.writeBytes(instruct)dataOutputStream.flush()dataOutputStream.close()} catch (ex: Exception) {ex.printStackTrace()}}/*** 获取gpio编号对应的值,即是高电平或低电平** @return高低电平(0或者1)* * 注意:使用该方法时,initGpio()的dire参数值应为in*/fun getValue(gpioNum:String): Int {val localFile = File("/sys/class/gpio/gpio" + gpioNum+ "/value")if (!localFile.exists()) println(localFile.absoluteFile.toString() + " not exist!")while (true) {try {val localFileReader = FileReader(localFile)val arrayOfChar = CharArray(1)val i = localFileReader.read(arrayOfChar, 0, 1)localFileReader.close()if (i == 1) {val j = arrayOfChar[0].codereturn if (j == 48) 0 else 1}} catch (localFileNotFoundException: FileNotFoundException) {localFileNotFoundException.printStackTrace()return -1} catch (localIOException: IOException) {localIOException.printStackTrace()return -1}}}/*** 发送指令,设置gpio值* 设置gpio值,即设置高电屏* @param paramInt 写入值(0或者1)* @param gpioPort gpio端口* * 注意:使用该方法时,initGpio()的dire参数值应为out*/fun setValue(gpioPort:String,paramInt: Int) {val exportPath1 = "echo $paramInt > /sys/class/gpio/gpio$gpioPort/value"chmod(exportPath1)}/*** 初始化gpio* @param gpioPort gpio端口(单片机服务商提供)* @param dire 输入(只读)/输出(读写)方向**/fun initGpio(gpioPort:String,dire:String){//写入编号val exportPath = "echo $gpioPort > /sys/class/gpio/export"chmod(exportPath)//定义输入输出方向(out / in)val directionPath = ("echo $dire > " + " /sys/class/gpio/gpio" + gpioPort+ "/direction")chmod(directionPath)//赋予引脚编号的读写权限val permissionGpio = "chmod 0777 /sys/class/gpio/$gpioPort/value"chmod(permissionGpio)}
}
本文完毕,下班……