本文所介绍的内容基于树莓派瑞士军刀扩展板(SAKS),由于 SAKS 基于树莓派通用的 GPIO 设计,文中的原理和代码也适用于其他情况。
本文由树莓派实验室创作,遵循CC协议(署名-非商业性使用-禁止演绎-相同方式共享),欢迎树莓派爱好者们遵循协议内容转载传播。谢绝不遵守协议的转载和抄袭。
本节将介绍如何通过 SAKS 扩展板 DIY 一个数字秒表。需要用到一个轻触开关,开关按下时开始计时,再次按下时停止计时。数码管显示秒表读数。
由于我们已经开始基于 SAKS SDK 开发(了解 SAKS SDK 发布的信息请阅读这里),本例程中涉及到的 SAKS 扩展板引脚编号我们根本不需要再关心。
我们之前已经通过《浪漫小夜灯》和《数字闹钟》两篇教程介绍了轻触开关和数码管的使用方法,本文对这部分不再赘述。有了之前的基础,我们直接给出完整代码,可以看到运用了 SAKS SDK 之后,实现一个秒表的基本功能是相当简单的。代码中的要点是计算两个时间点之间的时间差,我们通过 Python 的 datetime.utcnow() 方法可以轻松实现。
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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | #!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Spoony' __license__ = 'Copyright (c) 2015 NXEZ.COM' from sakshat import SAKSHAT import time from datetime import datetime from sakspins import SAKSPins as PINS #Declare the SAKS Board SAKS = SAKSHAT() __start_time = datetime.utcnow() __end_time = datetime.utcnow() __timer_running = False #在检测到轻触开关触发时自动执行此函数 def tact_event_handler(pin, status): ''' called while the status of tacts changed :param pin: pin number which stauts of tact is changed :param status: current status :return: void ''' global __start_time global __end_time global __timer_running if pin = = PINS.TACT_RIGHT and status = = True : if __timer_running: __end_time = datetime.utcnow() else : __start_time = datetime.utcnow() SAKS.digital_display.show(( "%02d.%02d" % ( 0 , 0 ))) __timer_running = not __timer_running if __name__ = = "__main__" : #设定轻触开关回调函数 SAKS.tact_event_handler = tact_event_handler SAKS.digital_display.show(( "%02d.%02d" % ( 0 , 0 ))) while True : if __timer_running: __end_time = datetime.utcnow() c = __end_time - __start_time #print c.seconds #print c.microseconds SAKS.digital_display.show(( "%02d.%02d" % (c.seconds, c.microseconds))) time.sleep( 0.01 ) input ( "Enter any keys to exit..." ) |
将上面的程序源码保存为 main.py 接下来如果要运行,请注意程序开头的 from sakshat import SAKSHAT,需要导入 SAKS SDK 模块。为此我们需要将 SAKS SDK 模块的相关文件和 main.py 放在一起才能正确执行 main.py 程序。我们准备了一个包含 main.py 和 SAKS SDK 的包并在 Github 上提供下载:https://github.com/nxez/SAKS-tutorials/tree/master/digital-stopwatch
接下来在终端运行:
1 2 3 4 5 6 7 | git clone https: //github .com /nxez/SAKS-tutorials .git cd SAKS-tutorials cd digital-stopwatch sudo python main.py |
如果你觉得轻触开关太灵敏导致体验不佳,可以修改 SAKS SDK 的 entities/tact.py 中 bouncetime 的参数,默认如下:
1 | GPIO.add_event_detect(pin, GPIO.BOTH, callback = self .make_event, bouncetime = 1 ) |
修改成100-500之间的数值可以明显消除轻触按钮的抖动
1 | GPIO.add_event_detect(pin, GPIO.BOTH, callback = self .make_event, bouncetime = 100 ) |
下面这段视频是用以上代码,将轻触开关用光控模块替代之后的效果。
后面我们后面将开始介绍如何基于 SAKS 扩展板 DIY 各种有趣、实用的东西,欢迎持续关注!
本文属于《树莓派瑞士军刀扩展板(SAKS)DIY 教程》系列文章,查看系列文章目录,请访问:../../../nopathsource/fe9e9968c5df92f612fe55580cbf7e19.htmlswiss-army-knife-shield-for-raspberry-pi-diy-tutorials
发表评论