嵌入式arduino計數小程式
阿新 • • 發佈:2019-01-13
/*內容:以按鍵單擊(表示為0),⻓長擊(表示為1) 為輸⼊入,統計連續1(包括單個1)出現的狀態總共的次 數。 要求 必須包含fsm,中斷,不不可以使⽤用輪詢!!! 每一次按鍵,led亮一次 需要進⾏行行消抖*/ int last_state=0; int current_state=0; int count=0; int ledPin=13; int buttonPin=2; unsigned long duration; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode( ledPin , OUTPUT); pinMode( buttonPin , INPUT); attachInterrupt(0, counter, CHANGE); } void loop() { // put your main code here, to run repeatedly: switch(current_state){ case 1: if(last_state==0){ count++; Serial.print("count:"); Serial.println(count); } last_state=current_state; break; case 0: //digitalWrite( ledPin , LOW ); last_state=current_state; break; } } void counter(){ if (!( digitalRead( buttonPin) )){ delay( 50 ); if (!( digitalRead( buttonPin) )){ digitalWrite( ledPin , HIGH ); duration=pulseIn(buttonPin,LOW,60000000); if(duration/1000000.0>1){ current_state=1; //Serial.begin(9600); Serial.print("time:"); Serial.println("long"); }else{ current_state=0; //Serial.begin(9600); Serial.print("time:"); Serial.println("short"); } digitalWrite( ledPin , LOW ); } } }