OrangePi通過sysfs控制GPIO接口

OrangePi通過sysfs控制GPIO接口

什么是sysfs

    Sysfs 是 Linux 2.6 所提供的一種虛擬文件系統(tǒng)翘骂。這個(gè)文件系統(tǒng)不僅可以把設(shè)備
    (devices)和驅(qū)動程序(drivers) 的信息從內(nèi)核輸出到 用戶空間再膳,也可以用來對設(shè)備和驅(qū)
    動程序做設(shè)置。
    sysfs 的目的是把一些原本在 procfs 中的吧碾,關(guān)于設(shè)備的部份俺孙,獨(dú)立出來辣卒,以‘設(shè)備層次結(jié)構(gòu)
    架構(gòu)’(device tree)的形式呈現(xiàn)。這個(gè)文件系統(tǒng)由 Patrick Mochel 所寫睛榄,稍后 
    Maneesh Soni 撰寫 "sysfs backing store path"荣茫,以降低在大型系統(tǒng)中對存儲器的需求量.
### 使用的硬件
這里使用的是Orange Pi One,有40Pin的擴(kuò)展接口场靴,類似樹莓派啡莉,使用方法也類似。
    系統(tǒng)是使用的安卓4.4
    導(dǎo)出Gpio接口:
    echo XX  > /sys/class/gpio/export(其中XX為你要導(dǎo)出的GPIO引腳編號旨剥,后面會說到引腳編號計(jì)算方法)
    如果成功的話咧欣,這一步會在/sys/class/gpio目錄下生成 /sys/class/gpio/gpioXX
    設(shè)定IO方向:
    echo out > /sys/class/gpio/gpioXX/direction(輸出)
    echo in > /sys/class/gpio/gpioXX/direction(輸入)

    設(shè)定輸出值:
    echo 1 > /sys/class/gpio/gpioXX/value
    echo 0 >  /sys/class/gpio/gpioXX/value

    或者:
    echo high > /sys/class/gpio/gpioXX/direction(輸出,同時(shí)置高)
    echo low >  /sys/class/gpio/gpioXX/direction(輸出轨帜,同時(shí)置低)

    取消導(dǎo)出:
    echo XX  >  /sys/class/gpio/unexport
### 引腳映射計(jì)算
Orange Pi One 外設(shè)的GPIO如下:

![20151019002607_51900.jpg](http://upload-images.jianshu.io/upload_images/3088365-143e6e024df32a23.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

    計(jì)算公式:

    (P后面的字母在字母表中的位置 - 1) * 32 + 后面的數(shù)字
    例如:
    PA0計(jì)算得到:0    ------>(1-1)*32+0
    PA1計(jì)算得到:1       ------->(1-1)*32+1
    PA15計(jì)算得到:15   ------->(1-1)*32+15
    PD14計(jì)算得到:110  ------->(4-1)*32+14
    PC1計(jì)算得到:65   ------->(3-1)*32+1
### 在Java層控制
import com.donute.robot.utils.ShellUtils;

  /**
   * Created by zhouyufei on 2017/1/4.
   */

  public class Gpio {
      public static final int HIGH=1;
      public static final int LOW=0;
      public static final String IN="in";
      public static final String OUT="out";
      public static final String DISABLE="disable";
      private String path;
      private String direction=DISABLE;
      private int number;

      public Gpio(int number) {
          this.number = number;
          ShellUtils.execCommand("echo "+number+" > /sys/class/gpio/export",true);
          path="/sys/class/gpio/gpio"+number;
      }
      public Gpio openAsOut(){
          direction=OUT;
          ShellUtils.execCommand("echo "+direction+" > "+path+"/direction",true);
          return this;
      }
      public Gpio openAsIn(){
          direction=IN;
          ShellUtils.execCommand("echo "+direction+" > "+path+"/direction",true);
          return this;
      }
      public Gpio close(){
          direction=DISABLE;
          ShellUtils.execCommand("echo "+number+" > /sys/class/gpio/unexport",true);
          return this;
      }
      public void write(int value){
          ShellUtils.execCommand("echo "+value+" > "+path+"/value",true);
      }
      public int read(){
          ShellUtils.CommandResult result=ShellUtils.execCommand("cat "+path+"/value",true,true);
          if (result.result==0){
              try{
                  return Integer.parseInt(result.successMsg);
              }catch (Exception e){
                  return -1;
              }
          }else {
              return -1;
          }
      }

      public String getDirection() {
          return direction;
      }

      public int getNumber() {
          return number;
      }

  }
### ShellUtil代碼
package com.donute.robot.utils;

    /**
     * Created by zhouyufei on 16/7/31.
     */
    import java.io.BufferedReader;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.List;

    /**
     * ShellUtils
     * <ul>
     * <strong>Check root</strong>
     * <li>{@link ShellUtils#checkRootPermission()}</li>
     * </ul>
     * <ul>
     * <strong>Execte command</strong>
     * <li>{@link ShellUtils#execCommand(String, boolean)}</li>
     * <li>{@link ShellUtils#execCommand(String, boolean, boolean)}</li>
     * <li>{@link ShellUtils#execCommand(List, boolean)}</li>
     * <li>{@link ShellUtils#execCommand(List, boolean, boolean)}</li>
     * <li>{@link ShellUtils#execCommand(String[], boolean)}</li>
     * <li>{@link ShellUtils#execCommand(String[], boolean, boolean)}</li>
     * </ul>
     *
     * @author <a  target="_blank">Trinea</a> 2013-5-16
     */
    public class ShellUtils {

        public static final String COMMAND_SU       = "su";
        public static final String COMMAND_SH       = "sh";
        public static final String COMMAND_EXIT     = "exit\n";
        public static final String COMMAND_LINE_END = "\n";

        private ShellUtils() {
            throw new AssertionError();
        }

        /**
         * check whether has root permission
         *
         * @return
         */
        public static boolean checkRootPermission() {
            return execCommand("echo root", true, false).result == 0;
        }

        /**
         * execute shell command, default return result msg
         *
         * @param command command
         * @param isRoot whether need to run with root
         * @return
         * @see ShellUtils#execCommand(String[], boolean, boolean)
         */
        public static CommandResult execCommand(String command, boolean isRoot) {
            return execCommand(new String[] {command}, isRoot, true);
        }

        /**
         * execute shell commands, default return result msg
         *
         * @param commands command list
         * @param isRoot whether need to run with root
         * @return
         * @see ShellUtils#execCommand(String[], boolean, boolean)
         */
        public static CommandResult execCommand(List<String> commands, boolean isRoot) {
            return execCommand(commands == null ? null : commands.toArray(new String[] {}), isRoot, true);
        }

        /**
         * execute shell commands, default return result msg
         *
         * @param commands command array
         * @param isRoot whether need to run with root
         * @return
         * @see ShellUtils#execCommand(String[], boolean, boolean)
         */
        public static CommandResult execCommand(String[] commands, boolean isRoot) {
            return execCommand(commands, isRoot, true);
        }

        /**
         * execute shell command
         *
         * @param command command
         * @param isRoot whether need to run with root
         * @param isNeedResultMsg whether need result msg
         * @return
         * @see ShellUtils#execCommand(String[], boolean, boolean)
         */
        public static CommandResult execCommand(String command, boolean isRoot, boolean isNeedResultMsg) {
            return execCommand(new String[] {command}, isRoot, isNeedResultMsg);
        }

        /**
         * execute shell commands
         *
         * @param commands command list
         * @param isRoot whether need to run with root
         * @param isNeedResultMsg whether need result msg
         * @return
         * @see ShellUtils#execCommand(String[], boolean, boolean)
         */
        public static CommandResult execCommand(List<String> commands, boolean isRoot, boolean isNeedResultMsg) {
            return execCommand(commands == null ? null : commands.toArray(new String[] {}), isRoot, isNeedResultMsg);
        }

        /**
         * execute shell commands
         *
         * @param commands command array
         * @param isRoot whether need to run with root
         * @param isNeedResultMsg whether need result msg
         * @return <ul>
         *         <li>if isNeedResultMsg is false, {@link CommandResult#successMsg} is null and
         *         {@link CommandResult#errorMsg} is null.</li>
         *         <li>if {@link CommandResult#result} is -1, there maybe some excepiton.</li>
         *         </ul>
         */
        public static CommandResult execCommand(String[] commands, boolean isRoot, boolean isNeedResultMsg) {
            int result = -1;
            if (commands == null || commands.length == 0) {
                return new CommandResult(result, null, null);
            }

            Process process = null;
            BufferedReader successResult = null;
            BufferedReader errorResult = null;
            StringBuilder successMsg = null;
            StringBuilder errorMsg = null;

            DataOutputStream os = null;
            try {
                process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH);
                os = new DataOutputStream(process.getOutputStream());
                for (String command : commands) {
                    if (command == null) {
                        continue;
                    }

                    // donnot use os.writeBytes(commmand), avoid chinese charset error
                    os.write(command.getBytes());
                    os.writeBytes(COMMAND_LINE_END);
                    os.flush();
                }
                os.writeBytes(COMMAND_EXIT);
                os.flush();

                result = process.waitFor();
                // get command result
                if (isNeedResultMsg) {
                    successMsg = new StringBuilder();
                    errorMsg = new StringBuilder();
                    successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                    String s;
                    while ((s = successResult.readLine()) != null) {
                        successMsg.append(s);
                    }
                    while ((s = errorResult.readLine()) != null) {
                        errorMsg.append(s);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (os != null) {
                        os.close();
                    }
                    if (successResult != null) {
                        successResult.close();
                    }
                    if (errorResult != null) {
                        errorResult.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (process != null) {
                    process.destroy();
                }
            }
            return new CommandResult(result, successMsg == null ? null : successMsg.toString(), errorMsg == null ? null
                    : errorMsg.toString());
        }

        /**
         * result of command
         * <ul>
         * <li>{@link CommandResult#result} means result of command, 0 means normal, else means error, same to excute in
         * linux shell</li>
         * <li>{@link CommandResult#successMsg} means success message of command result</li>
         * <li>{@link CommandResult#errorMsg} means error message of command result</li>
         * </ul>
         *
         * @author <a  target="_blank">Trinea</a> 2013-5-16
         */
        public static class CommandResult {

            /** result of command **/
            public int    result;
            /** success message of command result **/
            public String successMsg;
            /** error message of command result **/
            public String errorMsg;

            public CommandResult(int result) {
                this.result = result;
            }

            public CommandResult(int result, String successMsg, String errorMsg) {
                this.result = result;
                this.successMsg = successMsg;
                this.errorMsg = errorMsg;
            }
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末魄咕,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子蚌父,更是在濱河造成了極大的恐慌蚕礼,老刑警劉巖烟具,帶你破解...
    沈念sama閱讀 216,591評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異奠蹬,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)嗡午,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評論 3 392
  • 文/潘曉璐 我一進(jìn)店門囤躁,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人荔睹,你說我怎么就攤上這事狸演。” “怎么了僻他?”我有些...
    開封第一講書人閱讀 162,823評論 0 353
  • 文/不壞的土叔 我叫張陵宵距,是天一觀的道長。 經(jīng)常有香客問我吨拗,道長满哪,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,204評論 1 292
  • 正文 為了忘掉前任劝篷,我火速辦了婚禮哨鸭,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘娇妓。我一直安慰自己像鸡,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,228評論 6 388
  • 文/花漫 我一把揭開白布哈恰。 她就那樣靜靜地躺著只估,像睡著了一般。 火紅的嫁衣襯著肌膚如雪着绷。 梳的紋絲不亂的頭發(fā)上蛔钙,一...
    開封第一講書人閱讀 51,190評論 1 299
  • 那天,我揣著相機(jī)與錄音蓬戚,去河邊找鬼夸楣。 笑死,一個(gè)胖子當(dāng)著我的面吹牛子漩,可吹牛的內(nèi)容都是我干的豫喧。 我是一名探鬼主播,決...
    沈念sama閱讀 40,078評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼幢泼,長吁一口氣:“原來是場噩夢啊……” “哼紧显!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起缕棵,我...
    開封第一講書人閱讀 38,923評論 0 274
  • 序言:老撾萬榮一對情侶失蹤孵班,失蹤者是張志新(化名)和其女友劉穎涉兽,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體篙程,經(jīng)...
    沈念sama閱讀 45,334評論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡枷畏,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,550評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了虱饿。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片拥诡。...
    茶點(diǎn)故事閱讀 39,727評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖氮发,靈堂內(nèi)的尸體忽然破棺而出渴肉,到底是詐尸還是另有隱情,我是刑警寧澤爽冕,帶...
    沈念sama閱讀 35,428評論 5 343
  • 正文 年R本政府宣布仇祭,位于F島的核電站,受9級特大地震影響颈畸,放射性物質(zhì)發(fā)生泄漏乌奇。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,022評論 3 326
  • 文/蒙蒙 一承冰、第九天 我趴在偏房一處隱蔽的房頂上張望华弓。 院中可真熱鬧,春花似錦困乒、人聲如沸寂屏。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽迁霎。三九已至,卻和暖如春百宇,著一層夾襖步出監(jiān)牢的瞬間考廉,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評論 1 269
  • 我被黑心中介騙來泰國打工携御, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留昌粤,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,734評論 2 368
  • 正文 我出身青樓啄刹,卻偏偏與公主長得像涮坐,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子誓军,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,619評論 2 354

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,079評論 25 707
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理袱讹,服務(wù)發(fā)現(xiàn),斷路器昵时,智...
    卡卡羅2017閱讀 134,652評論 18 139
  • 整體思路ESP8266作為TCP服務(wù)器,,手機(jī)作為TCP客戶端,自己使用Lua直接做到了芯片里面,省了單片機(jī),,節(jié)...
    楊奉武閱讀 5,840評論 0 5
  • 在這個(gè)標(biāo)題之前捷雕,已經(jīng)換了三個(gè)標(biāo)題椒丧,起了四個(gè)開頭,敲了十個(gè)句子救巷,沒完成一個(gè)段落壶熏。本該能組成文章的字詞句在眼前、在腦子...
    嘿頭羊閱讀 448評論 1 2
  • 這個(gè)世界上有很多的人浦译, 有的喜歡和自己一樣興趣的人久橙, 有的喜歡和自己一樣打扮的人 而有的人, 喜歡和自己一樣性別的人管怠。
    叆藍(lán)炘閱讀 288評論 0 0