6177浏览
查看: 6177|回复: 1

[进阶] arduino宏的应用实例4--用宏实现边沿检测(转)

[复制链接]
取自前面帖子中的按键检测:
直接上代码:
  1. //逻辑量的四种状态:低,上升,高,下降
  2. enum edgeSta {low, trg, high, pop};
  3. //宏名:edge。 返回值:逻辑量状态。输入参数:bool值 用途:检测逻辑量的边沿。
  4. #define edge(ReadData) ({\
  5.     static bool Trg = false;\
  6.     static bool Cont = false;\
  7.     static bool Pop = false;\
  8.     Trg = ReadData & (ReadData ^ Cont); \
  9.     Pop = Cont != ReadData & !Trg; \
  10.     Cont = ReadData; \
  11.     enum edgeSta sta = low;\
  12.     if (Cont) {\
  13.       sta = high;\
  14.     } else {\
  15.       sta = low;\
  16.     }\
  17.     if (Trg) {\
  18.       sta = trg;\
  19.     }\
  20.     if (Pop) {\
  21.       sta = pop;\
  22.     }\
  23.     sta;\
  24.   })
  25. //宏名:timer。返回值:bool 时间到返回真。参数:enable使能,startTime第一次执行时间,delayTime执行间隔时间,doSomeThing任意表达式到时间执行的任务。
  26. #define timer(enable,startTime,delayTime,doSomeThing) ({\
  27.     static unsigned long timsta = millis();\
  28.     static unsigned long tim = startTime;\
  29.     bool ret = false;\
  30.     if(!enable){timsta = millis();tim = startTime;}else{\
  31.       if (millis() - timsta>= tim){\
  32.         doSomeThing;\
  33.         ret = true;\
  34.         timsta = millis(); \
  35.         tim = delayTime;\
  36.       }\
  37.     }\
  38.     ret;\
  39.   })
  40. void setup() {
  41.   // put your setup code here, to run once:
  42.   Serial.begin(9600);
  43.   pinMode(8, INPUT_PULLUP);
  44. }
  45. //检测8号端口按键的状态
  46. void fun1() {
  47.   enum edgeSta a = edge(!digitalRead(8));
  48.   switch (a)
  49.   {
  50.     case low:
  51.       //Serial.println("low");
  52.       break;
  53.     case trg:
  54.       Serial.println("trg");
  55.       break;
  56.     case high:
  57.       //Serial.println("high");
  58.       break;
  59.     default:
  60.       Serial.println("pop");
  61.   }
  62. }
  63. void loop() {
  64.   // put your main code here, to run repeatedly:
  65.   //联合使用定时器和边沿检测处理按键状态。
  66.   timer(true, 0, 20, fun1());
  67. }
复制代码


dsweiliang  初级技神

发表于 2016-5-4 09:36:41

学习学习
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

为本项目制作心愿单
购买心愿单
心愿单 编辑
[[wsData.name]]

硬件清单

  • [[d.name]]
btnicon
我也要做!
点击进入购买页面
上海智位机器人股份有限公司 沪ICP备09038501号-4

© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed

mail