首页 > 代码库 > Arduino从基础到实践第三章练习题

Arduino从基础到实践第三章练习题

先写在这里,还没经过测试。

1. LED两端往中间移动,到中间后向两边返回。

 1 // adr301.ino 2  3 byte ledPin[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; 4 int ledDelay(65); 5 int direction = 1; 6 int currentLED = 0; 7 unsigned long changeTime; 8  9 void setup() {10     for(int i=0; i<10; i++){11         pinMode(ledPin[i], OUTPUT);12     }13 14     changeTime = millis();15 }16 17 void loop() {18     if((millis() - changeTime) > ledDelay){19         changeLED();20         changeTime = millis();21     }22 }23 24 void changeLED() {25     for(int i=0; i<10; i++){26         digitalWrite(ledPin[i], LOW);27     }28 29     digitalWrite(ledPin[currentLED], HIGH);30     digitalWrite(ledPin[10 - 1 - currentLED], HIGH);31 32     currentLED += direction;33 34     if(currentLED == 4){35         direction = -1;36     }37 38     if(currentLED == 0){39         direction = 1;40     }41 }

添加结果视频

2. LED弹跳球

 1 // adr302.ino 2  3 byte ledPin[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; 4 int ledDelay(65); 5 int direction = 1; 6 int currentLED = 0; 7 int maxHeight = 9; 8 unsigned long changeTime; 9 10 void setup() {11     for(int i=0; i<10; i++){12         pinMode(ledPin[i], OUTPUT);13     }14 15     changeTime = millis();16 }17 18 void loop() {19     if((millis() - changeTime) > ledDelay){20         changeLED();21         changeTime = millis();22     }23 }24 25 void changeLED() {26     for(int i=0; i<10; i++){27         digitalWrite(ledPin[i], LOW);28     }29 30     digitalWrite(ledPin[currentLED], HIGH);31 32     currentLED += direction;33 34     if(currentLED == maxHeight){35         direction = -1;36         maxHeight -= 1;37     }38 39     if(currentLED == 0){40         direction = 1;41         maxHeight = 9;42     }43 }