|
| 1 | +/* |
| 2 | + * Author: Alex Mainstone |
| 3 | + * Username: eeuae3 |
| 4 | + * Date: 11/02/2018 |
| 5 | + */ |
| 6 | + |
| 7 | +//This will make my code extendable, allowing for users to add their own switch and LED |
| 8 | +const int LED_NUM = 4; |
| 9 | +const int leds[LED_NUM] = {3,4,5,2}; |
| 10 | +const int switches[LED_NUM] = {8,7,6,9}; |
| 11 | + |
| 12 | +int level = 0; //the number of leds in the level |
| 13 | +int current = 0; //current place in order |
| 14 | +const int MAX_LEVEL = 100; //The maximum level |
| 15 | +int order[MAX_LEVEL] = {}; |
| 16 | + |
| 17 | +void setup() { |
| 18 | + for(int i = 0; i < LED_NUM; i++){ //Enable all LED's and Buttons |
| 19 | + pinMode(leds[i], OUTPUT); |
| 20 | + pinMode(switches[i], INPUT); |
| 21 | + } |
| 22 | + compTurn(); |
| 23 | +} |
| 24 | + |
| 25 | +//Flashes the desired LED |
| 26 | +void flashLED(int LED) { |
| 27 | + delay(1000); |
| 28 | + digitalWrite(LED, HIGH); |
| 29 | + delay(1000); |
| 30 | + digitalWrite(LED, LOW); |
| 31 | +} |
| 32 | + |
| 33 | +//Generates the next member of the sequence |
| 34 | +void compTurn() { |
| 35 | + current = 0; |
| 36 | + order[level++] = leds[rand() % LED_NUM]; |
| 37 | + for(int i = 0; i < level; i++) { |
| 38 | + flashLED(order[i]); |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +//Flashes all LEDs |
| 43 | +void fail() { |
| 44 | + for(int i = 0; i < LED_NUM; i++) { |
| 45 | + digitalWrite(leds[i], HIGH); |
| 46 | + } |
| 47 | + delay(1000); |
| 48 | + for(int i = 0; i < LED_NUM; i++) { |
| 49 | + digitalWrite(leds[i], LOW); |
| 50 | + } |
| 51 | + level = 0; |
| 52 | + compTurn(); |
| 53 | +} |
| 54 | + |
| 55 | +void loop() { |
| 56 | + for(int i = 0; i < LED_NUM; i++) { |
| 57 | + int state = digitalRead(switches[i]); |
| 58 | + if(state == HIGH){ |
| 59 | + while(state == HIGH) { state = digitalRead(switches[i]); } //Wait until the button is released |
| 60 | + if(order[current] == leds[i]) { |
| 61 | + current++; |
| 62 | + if(current == level){ |
| 63 | + compTurn(); |
| 64 | + } |
| 65 | + } else { |
| 66 | + fail(); |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments