极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 9727|回复: 0

arduino宏的应用实例4--用宏实现边沿检测

[复制链接]
发表于 2016-4-27 01:06:16 | 显示全部楼层 |阅读模式
本帖最后由 wwwymq 于 2016-4-27 01:29 编辑

取自前面帖子中的按键检测:
直接上代码:
[pre lang="arduino" line="1" file="edge"]//逻辑量的四种状态:低,上升,高,下降
enum edgeSta {low, trg, high, pop};
//宏名:edge。 返回值:逻辑量状态。输入参数:bool值 用途:检测逻辑量的边沿。
#define edge(ReadData) ({\
    static bool Trg = false;\
    static bool Cont = false;\
    static bool Pop = false;\
    Trg = ReadData & (ReadData ^ Cont); \
    Pop = Cont != ReadData & !Trg; \
    Cont = ReadData; \
    enum edgeSta sta = low;\
    if (Cont) {\
      sta = high;\
    } else {\
      sta = low;\
    }\
    if (Trg) {\
      sta = trg;\
    }\
    if (Pop) {\
      sta = pop;\
    }\
    sta;\
  })

//宏名:timer。返回值:bool 时间到返回真。参数:enable使能,startTime第一次执行时间,delayTime执行间隔时间,doSomeThing任意表达式到时间执行的任务。
#define timer(enable,startTime,delayTime,doSomeThing) ({\
    static unsigned long timsta = millis();\
    static unsigned long tim = startTime;\
    bool ret = false;\
    if(!enable){timsta = millis();tim = startTime;}else{\
      if (millis() - timsta>= tim){\
        doSomeThing;\
        ret = true;\
        timsta = millis(); \
        tim = delayTime;\
      }\
    }\
    ret;\
  })
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(8, INPUT_PULLUP);
}
//检测8号端口按键的状态
void fun1() {
  enum edgeSta a = edge(!digitalRead(8));
  switch (a)
  {
    case low:
      //Serial.println("low");
      break;
    case trg:
      Serial.println("trg");
      break;
    case high:
      //Serial.println("high");
      break;
    default:
      Serial.println("pop");
  }
}
void loop() {
  // put your main code here, to run repeatedly:
  //联合使用定时器和边沿检测处理按键状态。
  timer(true, 0, 20, fun1());
}[/code]
回复

使用道具 举报

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

本版积分规则 需要先绑定手机号

Archiver|联系我们|极客工坊

GMT+8, 2024-4-25 20:02 , Processed in 0.053754 second(s), 17 queries .

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表