Skip to main content
6 of 8
deleted 19 characters in body
Jamal
  • 34.9k
  • 13
  • 133
  • 237

Simon Says using Arduino UNO

I built a Simon Says game using an Arduino UNO board. This was my first "real" arduino project. I would like to know how to make it better, game mechanics and code efficiency.

#define RedTone 165
#define GreenTone 330
#define YelloTone 659
#define BlueTone 1319
#define FailTone 100

#define BuzzerPin 8


/* The led and button pins are set this way because I use their position as a hexadecimal.
 *  LED PINS:
      red:0
      green:1
      yello:2
      blue:3
    Button Pins:
      red:4
      green:5
      yello:6
      blue:7
*/


byte mem[20];
int sound[16] = {0, RedTone, GreenTone, 0, YelloTone, 0, 0, 0, BlueTone, 0, 0, 0, 0, 0, 0, FailTone};  //the tones are placed in the arrey in the hex spot for turning on the leds.


void setup() {
  DDRD = 0x0F;
  randomSeed(analogRead(0));
  pinMode(BuzzerPin, 1);
}


void blink(int i) { //Blinking and making sound
  PORTD = i;
  tone(BuzzerPin, sound[i]);
  delay(500);
  PORTD = 0x00;
  noTone(BuzzerPin);
  delay(500);
}


void NT(int i) { //Just blinking
  PORTD = i;
  delay(500);
  PORTD = 0x00;
  delay(500);
}


void set_mem() {  //sets the random order of the leds and transforms into the led's pin in hexadecimal
  int b;
  for (int i = 0; i < 20; i++) {
    b = random(4);
    if (b == 3)
      mem[i] = 0x08;
    else if (b == 2)
      mem[i] = 0x04;
    else if (b == 1)
      mem[i] = 0x02;
    else
      mem[i] = 0x01;
  }
}


bool check(int i) { //checks if the pressed button is correct
  byte look;
  for (int x = 0; x <= i; x++) {
    look = 0;
    do
    {
      look = PIND >> 4;  //makes the button press pin to the pin of led with the same color
    }
    while (look == 0);  //waits until a button is pressed
    blink(look); //lights up the button's led
    if (look != mem[x])
      return 0;
  }
  return 1;
}


void loop() {
  set_mem();
  for (int i = 0; i < 20; i++) {
    for (int x = 0; x <= i; x++)
      blink(mem[x]);
    NT(0x09); //signals when it finnished showing the order
    if (check(i) == 0) {
      blink(0x0F); //shows if the player failed
      break; //couses a restart
    }
    NT(0x06); //signals when the player finished pressing the leds
  }
}

How it looks and works:

(I'm having problems making the snippet work, so here is the link to the site itself and here is a video of it working (sorry for the low quality).)

<iframe frameborder='0' height='448' marginheight='0' marginwidth='0' scrolling='no' src='https://circuits.io/circuits/4145099-simon-says-leds-and-buttons/embed#breadboard' width='650'></iframe>

Sela12
  • 161
  • 1
  • 12