struct pin{
uint8_t high;
uint8_t low;
};
static const uint8_t number_of_pins = 4;
static const uint8_t number_of_leds = number_of_pins*number_of_pins - number_of_pins;
static const uint8_t led_pinout[number_of_pins] = {3,4,5,6};
uint8_t button_pin = 2;
bool button_pressed = false; // has the button been push
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(button_pin, INPUT);
attachInterrupt(digitalPinToInterrupt(button_pin), button_press, FALLING); // do it on a change so that it can be updated
}
void loop() {
uint32_t speed_sec = 500;
uint8_t speed_change_per_round = 40;
bool is_winning = true;
uint8_t number_of_rounds = 0;
uint8_t winning_round = 10; // how many rounds you have to complete in order to win
uint8_t last_led = 0; // the last led lit up before the game end
if(button_pressed == true){
// the game has started
delay(100);
button_pressed = false; // set back to false as we already acknowledged the press
while(is_winning){
for(int i = 1; i < number_of_leds+1; i++){
set_charlie_pin(i);
delay(speed_sec);
if(number_of_rounds != 0){
if(button_pressed == false && i == 1){
is_winning = false;
break;
}
}
if(button_pressed == true && i != 1){
last_led = i;
is_winning = false;
break;
}
button_pressed = false; // set back to false as we already acknowledged the press
}
speed_sec = speed_sec - speed_change_per_round*number_of_rounds;
number_of_rounds += 1;
if(number_of_rounds == winning_round){
last_led = 1;
break;
}
}
set_charlie_pin(last_led);
delay(1000);
set_charlie_pin(0); //set all the pins back to inputs
if(is_winning){
// insert success led routine
for(int i = 0; i < 20;i++){
for(int j = 0; j < number_of_leds+1; j++){
if((j%2 == 0 && i%2 == 0) || (j%2 != 0 && i%2 != 0)){
set_charlie_pin(j);
}
}
delay(100);
}
set_charlie_pin(0);
} else {
//insert losing led routine
for(int i = 0; i < 3;i++){
set_charlie_pin(1);
delay(500);
set_charlie_pin(0);
delay(500);
}
}
button_pressed = false; // clear the button press
}
}
void button_press(){
button_pressed = true; //!digitalRead(button_pin); // the ! mark means it does the opposite if digital read is 1 button_pressed is 0
}
void set_charlie_pin(uint8_t led_number){
static const struct pin pins[number_of_leds] = {{4,1},{3,4},{4,2},{2,1},{1,3},{3,2},{1,4},{2,3},{3,1},{1,2},{2,4},{4,3}};
if(led_number > number_of_leds){
printf("Led number is to big");
return;
}
for(int i = 0; i < number_of_pins; i++){
pinMode(led_pinout[i],INPUT);
}
if(led_number == 0){
return;
}
uint8_t high_pin = led_pinout[pins[led_number-1].high - 1];
uint8_t low_pin = led_pinout[pins[led_number-1].low - 1];
pinMode(high_pin, OUTPUT);
pinMode(low_pin, OUTPUT);
digitalWrite(high_pin,1);
digitalWrite(low_pin,0);
}