去抖函数的总结

/*******************************

防抖动的函数
 参数:
 pinx:需要读取的引脚状态
 data:赋值
 div:赋值的偏移量
 * Shake_count:防抖的计数

*********************************/

#define Shake_Min 1
#define Shake_Mid 5
#define Shake_Max 10

void Shake_Function(u8 pinx, u8* data,u8 div,u8* Shake_count)

{

    u8 count = *Shake_count;
    
    if(pinx)//防抖动
    {
        count++;
    }
    else
    {
        count--;

    }

    if(count>=Shake_Max)
    {
        count = Shake_Mid;
        *data |=div;
    }
    else if(count<=Shake_Min)
    {
        count = Shake_Mid;
        *data &=(~div);
    }
    else
    {}
    *Shake_count = count;

}

/**************************************************************************
*检查拨码开关,根据拨码开关的数字码
***************************************************************************/

void DIP_Switch_Config(void)
{

    static u8 DIP_Count[5]={Shake_Mid,Shake_Mid,Shake_Mid,Shake_Mid,Shake_Mid};

    Shake_Function(READ_DIP_Switch1,&PROMARK.DIP_Switch_ID,0x01,&DIP_Count[0]);
    Shake_Function(READ_DIP_Switch2,&PROMARK.DIP_Switch_ID,0x02,&DIP_Count[1]);
    Shake_Function(READ_DIP_Switch3,&PROMARK.DIP_Switch_ID,0x04,&DIP_Count[2]);
    Shake_Function(READ_DIP_Switch4,&PROMARK.DIP_Switch_ID,0x08,&DIP_Count[3]);

    Shake_Function(READ_DIP_Switch5,&PROMARK.DIP_Switch_ID,0x10,&DIP_Count[4]);    

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
和节流都是用来控制函数执行频率的方法,但它们的实现和应用场景有所不同。 防函数的作用是在指定的时间间隔内,如果函数被连续调用多次,则只执行最后一次调用,并将其延迟到指定时间后执行。常见的应用场景是在用户输入频繁的情况下进行搜索或请求数据,以减少不必要的请求或计算。 一个简单的防函数可以这样实现: ```python import time def debounce(delay): def decorator(func): last_called = time.time() def wrapper(*args, **kwargs): nonlocal last_called now = time.time() if now - last_called < delay: return last_called = now return func(*args, **kwargs) return wrapper return decorator ``` 使用示例: ```python @debouce(0.5) def search(keyword): # 模拟搜索操作 print("正在搜索:", keyword) search("apple") search("banana") time.sleep(1) search("cat") ``` 上述代码中,`debounce` 函数接受一个时间间隔 `delay`,并返回一个装饰器函数。装饰器函数 `wrapper` 在每次调用被装饰的函数之前会检查距离上一次调用的时间间隔,如果小于 `delay`,则直接返回,否则执行被装饰的函数。 节流函数的作用是在指定的时间间隔内,保证函数执行的频率不超过指定的次数。常见的应用场景是在用户频繁触发事件(如滚动、鼠标移动等)时,进行性能优化。 一个简单的节流函数可以这样实现: ```python import time def throttle(limit): def decorator(func): last_called = 0 count = 0 def wrapper(*args, **kwargs): nonlocal last_called, count now = time.time() if now - last_called > limit: count = 0 last_called = now count += 1 if count <= limit: return func(*args, **kwargs) return wrapper return decorator ``` 使用示例: ```python @throttle(2) def log(message): print(message) for i in range(5): log(i) time.sleep(0.5) ``` 上述代码中,`throttle` 函数接受一个次数限制 `limit`,并返回一个装饰器函数。装饰器函数 `wrapper` 在每次调用被装饰的函数之前会检查距离上一次调用的时间间隔和执行次数,如果时间间隔大于限制且执行次数不超过限制,则执行被装饰的函数总结:防函数适用于需要延迟执行并且只关心最后一次调用结果的场景,节流函数适用于需要控制函数执行频率的场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值