您现在的位置是: 网站首页 > 程序设计  > 树莓派 

GPIO-封装

2020年1月22日 08:00 1394人围观

简介树莓派GPIO封装

    对系统的GPIO库进行封装,对上层屏蔽直接设置IO口的操作,只暴露high和low两个接口

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    #!/usr/bin/python3 
    #encoding=utf-8
    
    import time
    
    try: 
        import RPi.GPIO as _GPIO 
    except Exception as e: 
        class _GPIO(): 
            OUT = 0 
            LOW = 0 
            HIGH = 0 
            BOARD = 0
    
            @staticmethod 
            def setup(index, inout): 
                pass
    
            @staticmethod 
            def output(index, high): 
                pass
    
            @staticmethod 
            def setmode(x): 
                pass
    
    class GPIO(object): 
        BCM     = _GPIO.BCM 
        BOARD   = _GPIO.BOARD 
        LOW     = _GPIO.LOW 
        HIGH    = _GPIO.HIGH
    
        def __init__(self, index, inout=_GPIO.OUT): 
            self.__index = index 
            _GPIO.setup(self.__index, inout, initial = GPIO.LOW)
    
        def high(self): 
            _GPIO.output(self.__index, GPIO.HIGH)
    
        def low(self): 
            _GPIO.output(self.__index, GPIO.LOW)
    
        @staticmethod 
        def init(mode): 
            _GPIO.setmode(mode)
    
        @staticmethod 
        def cleanup(): 
            _GPIO.cleanup()
    
    def main(): 
        GPIO.init(GPIO.BCM) 
        led = GPIO(21) 
        led.high() 
        time.sleep(1) 
        GPIO.cleanup()
    
    if '__main__' == __name__: 
        main()
    

    上一篇: Raft 日志复制

    下一篇: 点亮LED