一條隨手的Arduino sketch優化 以Examples-02.Digital-Debounce為例
1 const int buttonPin = 2;
2 const int ledPin = 13;
3
4 int ledState = HIGH;
5 int buttonState;
6 int lastButtonState = LOW;
7
8 unsigned long lastDebounceTime = 0;
9 unsigned long debounceDelay = 50;
10
11 void setup() {
12 pinMode(buttonPin, INPUT);
13 pinMode(ledPin, OUTPUT);
14 digitalWrite(ledPin, ledState);
15 }
16
17 void loop() {
18 int reading = digitalRead(buttonPin);
19 if (reading != lastButtonState) {
20 lastDebounceTime = millis();
21 }
22 if ((millis() - lastDebounceTime) > debounceDelay) {
23 if (reading != buttonState) {
24 buttonState = reading;
25 if (buttonState == HIGH) {
26 ledState = !ledState;
27 }
28 }
29 }
30 digitalWrite(ledPin, ledState);
31 lastButtonState = reading;
32 }
原文的程式碼 暫時去掉註釋,便於顯示重點。
編譯結果:
Sketch uses 1116 bytes (3%) of program storage space. Maximum is 30720 bytes.
Global variables use 19 bytes (0%) of dynamic memory, leaving 2029 bytes for local variables. Maximum is 2048 bytes.
優化手段1:選用夠用的資料型別,這裡面的int物件,都是小於255的,可以換成byte:
const byte buttonPin = 2; const byte ledPin = 13; byte ledState = HIGH; byte buttonState; byte lastButtonState = LOW; unsigned long lastDebounceTime = 0; unsigned long debounceDelay = 50; void setup() { pinMode(buttonPin, INPUT); pinMode(ledPin, OUTPUT); digitalWrite(ledPin, ledState); } void loop() { byte reading = digitalRead(buttonPin); if (reading != lastButtonState) { lastDebounceTime = millis(); } if ((millis() - lastDebounceTime) > debounceDelay) { if (reading != buttonState) { buttonState = reading; if (buttonState == HIGH) { ledState = !ledState; } } } digitalWrite(ledPin, ledState); lastButtonState = reading; }
編譯結果:
Sketch uses 1074 bytes (3%) of program storage space. Maximum is 30720 bytes.
Global variables use 17 bytes (0%) of dynamic memory, leaving 2031 bytes for local variables. Maximum is 2048 bytes.
效果:
程式空間減少42位元組;SRAM減少2位元組。
繼續淦:
裡面有一個函式在相近的位置,用了兩遍,且貌似挺複雜的,就是:millis();
將其合二為一,但是又要增加一個全域性變數,試試效果:
const byte buttonPin = 2; const byte ledPin = 13; byte ledState = HIGH; byte buttonState; byte lastButtonState = LOW; unsigned long lastDebounceTime = 0; unsigned long debounceDelay = 50; unsigned long ml = 0; void setup() { pinMode(buttonPin, INPUT); pinMode(ledPin, OUTPUT); digitalWrite(ledPin, ledState); } void loop() { byte reading = digitalRead(buttonPin); ml = millis(); if (reading != lastButtonState) { lastDebounceTime = ml; } if ((ml - lastDebounceTime) > debounceDelay) { if (reading != buttonState) { buttonState = reading; if (buttonState == HIGH) { ledState = !ledState; } } } digitalWrite(ledPin, ledState); lastButtonState = reading; }
編譯結果:
Sketch uses 1052 bytes (3%) of program storage space. Maximum is 30720 bytes.
Global variables use 17 bytes (0%) of dynamic memory, leaving 2031 bytes for local variables. Maximum is 2048 bytes.
又幹掉22位元組的程式空間,SRAM竟然沒變?
(1166-1052)/1166 = 104/1166 = 9.8%
將近10%的優化成果,這還沒使用骨灰級的暫存器大法來優化pinMode和digitalRead/Write。
後續再試:constbytedebounceDelay=50; 結果還是1052、17,看來是編譯器自動將其優化了。