Arduino 外部中断 button 之 按下和释放 完整周期 处理方案

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29757283/article/details/79469806

代码:

/**
 * Function:  N/A
 *
 * Verified board: Arduino Leonardo
 * Symptom: N/A
 * Impact scope: N/A
 * Author:  CSDN账号:qq_29757283
 * --- 2018/Mar/06 ---
 *   not work well!
 *  一旦逻辑错一处,就到处都错了。
 *      -- delay(1000) 导致 g_press_release_flag 没有改变, 此时中断,则逻辑出错。
 *      
 * --- 2018/Mar/06  17:16  ---
 *   改变 attachInterrupt 监听的状态,就可以现实。检测 电平而不是 动作边沿!
 *     -- 再加上 高电平时才做动作的判断。现象上已经OK了。
 * 
 * 
 */

const byte interruptPin = 2;                                    /* 0, 1, 2, 3, 7 can be used as interruptPin */

bool g_press_release_flag = false;
bool intr_pin_flag = false;

#define hight_level HIGH
#define low_level LOW

void intr_function_handle();


void setup(){

    pinMode(interruptPin, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(interruptPin), interruptPin_LOW_handle, LOW);

    /** Debug log - Serial **/
    Serial.begin(9600);
    while( !Serial ){;}

    Serial.println( "I am Serial.\nI am ready!" );

    return;
}


void loop(){

    if( (g_press_release_flag == true) && (digitalRead(interruptPin)==hight_level) ){
        intr_function_handle();
    }

    // Serial.println( "I am Good! ");
    // Serial.println( "I am work somthing else");

    delay(500);

    // Serial.println( "here is keep doing things.");
    // Serial.println( "aha!" );

    delay(500);

    return;
}


//       ______false____ true  ____false______
// 1. __|               |_____|
//
// 2.     do _                 _true__
//  function  |__false___flase_|(after|____false___
//                        do function)
//       1. true + 2. flase => 2. true |do function|=set=> 2. false
    

/*
 * usage: if (g_press_release_flag == true)  =call=>  intr_function_handle();
 */
void intr_function_handle(){
    static int i = 0;
    // Serial.println( "you call intr_function_handle() %dth", ++i );
    Serial.println( "\n############you call intr_function_handle() ############\n" );
    // ... code ...

    g_press_release_flag = false;

    return;
}

void interruptPin_LOW_handle(){

    attachInterrupt(digitalPinToInterrupt(interruptPin), interruptPin_HIGH_handle, HIGH);

    Serial.println( "\tintr PIN -- LOW" );

    return;
}

void interruptPin_HIGH_handle(){

    attachInterrupt(digitalPinToInterrupt(interruptPin), interruptPin_LOW_handle, LOW);

    Serial.println("\tintr PIN -- HIGH");

    g_press_release_flag = true;
    return;
}

Reference:

Reference > Language > Functions > External interrupts > Attachinterrupt





猜你喜欢

转载自blog.csdn.net/qq_29757283/article/details/79469806