树莓派pigpio实现gpio中断(python版)

说明:在这里对评论中的问题我统一做一个说明。

  1. gpio的中断Edge设置和回调设置,是在代码中pi.callback(ir_pin, pigpio.RISING_EDGE, cb_func)实现。
  2. 代码最后的try ... except KeyboardInterrupt只是python的一个异常处理写法,代码的核心功能不在这里,不写try ... except KeyboardInterrupt也是可以的。我写这段仅仅是为了表示用户可以通过中断while循环然后执行cb1.cancel()来取消gpio的中断功能。
  3. 看不懂的同学,罚你们把代码再读100遍。没看懂代码就评论不是一个好习惯。

树莓派的pigpio库提供了一个方法来设置gpio中断,即callback():
callback(user_gpio, edge, func)

参数(Parameters):
user_gpio:= 0-31.
edge:= EITHER_EDGE, RISING_EDGE (default), or FALLING_EDGE.
func:= user supplied callback function.

回调函数func接受三个参数:
The user supplied callback receives three parameters, the GPIO, the level, and the tick.

ParameterValueMeaning
GPIO0-31The GPIO which has changed state
level0-20 = change to low (a falling edge)
1 = change to high (a rising edge)
2 = no level change (a watchdog timeout)
tick32 bitThe number of microseconds since boot
WARNING: this wraps around from
4294967295 to 0 roughly every 72 minutes

pigpio library - callback 文档地址

例程:

# -*- coding:UTF-8 -*-

import pigpio
import time

ir_pin = 17
pi = pigpio.pi()
def cb_func(gpio, level, tick):
    print(gpio, level, tick)
    print("\n GPIO:%d Rising Edge Detected.Sending message to DingTalk."%ir_pin)
    dingmessage()

cb1 = pi.callback(ir_pin, pigpio.RISING_EDGE, cb_func)
Count = 1
while True:
    try:
        print("%d Seconds in main loop"%(Count*5))
        time.sleep(5)
        Count += 1
        pass
    except KeyboardInterrupt:
        break
        pass
    pass
print("Program terminated by user, clean up cb1 callback setting")
cb1.cancel()
  • 3
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 15
    评论
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值