Morse Code Game

Description

In this game the Arduino blinks a series of long and short flashes on the yellow LED and the players tries to match the pattern using the button. The red and green LEDs are used to indicate when it is the players turn, and if the round was won or lost.

Resources

I combined several examples to make the code including:

The combination_lock1 example from class
The blink, button, and switch examples on the Arduino website
This sketch which uses millis to measure the duration of a button press
This sketch which turns an LED on and off for random amounts of time

Circuit

The circuit is the same as the one we used for the combination lock example, except that I used three LEDs and only two buttons.

Issues

The one thing that I was not able to get my game to do which I had wanted is to get the entire game to start and stop using a button press. I did get a simplified version of the concept to work (see the second code at the bottom) but I was not able to combine the two together and still get them to work.

Code 1: Morse Code Game:

/*
* This sketch is a game where the Arduino gives you pattern of short and long flashes and you match them by pressing a button
* This sketch makes the led blink for either 130 milliseconds or 1000 milliseconds (1 sec)
* Each time the code loops, the blink pattern will get one value longer
* This pattern is saved to an array which is printed to the serial monitor
* When the pattern is 10 blinks long. The pattern will reset to 1.

//===============================================================
//global variables
int red = 6;                     // red LED connected to digital pin 6
int yellow = 7;                  // yellow LED connected to digital pin 7
int green = 8;                   // green LED connected to digital pin 8
int yellowOn = 0;                // Initialize variable for ON time

int buttonStart = 12;            //This button starts the game — At least it should, this part isn’t working yet
int buttonPlay = 11;             //This button plays the game
int BSValue;                     //Used to feel the state of the start button
int BPValue;                     //Used to feel the state of the play button
boolean lastBSValue = LOW;       //Used to remember the last start button state
boolean lastBPValue = LOW;       //Used to remember the last play button state
int debounce = 10;               //Used to make sure we have a real button press

int myFlashes[2] = {130, 1000};              // Array of possible flash lengths
int myPattern[10] = {0,0,0,0,0,0,0,0,0,0};   // create an array with ten slots to hold the blink pattern
int patPos = 0;                              // create an int to hold the position in our pattern array
int myGuess[10] = {0,0,0,0,0,0,0,0,0,0};     // This array will hold the players guesses
int guessPos = 0;                            // create an int to hold the position in the guess array
int guessVal = 0;                            // This holds the value of the player’s guess
int gameOutcome = 0;                         // This will be used to hold the outcome of the game

unsigned long startTime;                  // This is used to measure the start of the player’s button press
unsigned long duration;                   // This value is used to determine the duration of the player’s button press

//=================================================================
//setup
void setup()                      // run once, when the sketch starts
{
pinMode(red, OUTPUT);           // set the LED pins as outputs
pinMode(yellow, OUTPUT);
pinMode(green, OUTPUT);
pinMode(buttonStart, INPUT);    // set the button pins as inputs
pinMode(buttonPlay, INPUT);

digitalWrite(red, LOW);        //start all the buttons and LEDs in the low state
digitalWrite(yellow,LOW);
digitalWrite(green, LOW);
digitalWrite(buttonStart, LOW);
digitalWrite(buttonPlay, LOW);
Serial.begin(9600);            // initialize the SerialMonitor so we can see what the hell is going on
}
//================================================================
//loop
void loop(){

//The “r” while loop progresses the cycle
int r=1;                         // r is the number of flashes in the pattern
while (r<11){                    // r is less than the maximum number of flashes in the pattern +1
int i = 1;                     // i is the number of flashes in this iteration
patPos = 0;                    // patPos keeps track of our position within the myPattern array

//The “i” while loop repeats the blinking within each cycle
while (i<r+1 && patPos < 11){   // i is always less than r+1. patPos is always less than the maximum number of items in the array +1
yellowOn = myFlashes[random(0,2)]; // Select a position in the myFlashes array (0 or 1 at random)
// NOTE: the random function min in inclusive,
// the max is exclusive, so we must set the
// max value one higher tham the maximum
// value we want to return.
myPattern[patPos] = yellowOn;      // set the current position in the pattern array = to the long or short flash length
digitalWrite(yellow, HIGH);     // sets the LED on
delay(yellowOn);               // delays the amount of time designated in the array
digitalWrite(yellow, LOW);     // sets the LED off

delay(500);                    // wait 500 milliseconds inbetween flashes
i++;                           // increase the value of i so that the inner while loop ends eventually
patPos++;                      // increase the position in the pattern array
} //end “i”

//print the pattern so we know what it is
Serial.print(“myPattern is: “);
int j;
for (j=0; j<11; j++){
Serial.print(myPattern[j]);
Serial.print(“, “);
}
Serial.println(“.”);

//tell the player it is their turn by flashing the green light
digitalWrite(green, HIGH);
delay(2000);
digitalWrite(green, LOW);

//It is now the players turn
//=====================================================
while(guessPos<r){                 // The player’s guess must be inside a while loop so that the program does not porgress until the player has made their guess
BPValue = digitalRead(buttonPlay); //look at the play button
if (BPValue != lastBPValue){       //check if the state of the button has changed
delay(debounce);                 //delay and recheck to make sure we have a real button press
BPValue = digitalRead(buttonPlay); //read the button value again
if (BPValue != lastBPValue){       //If the press is real
if(BPValue == HIGH){               // check if the button is in the HIGH state
digitalWrite(yellow, HIGH);      // light up the LED to give the player feedback on their press time
startTime = millis();            // If it is, start counting
while(digitalRead(buttonPlay) == HIGH){ //count as long as the button is in the HIGH state
duration = millis()-startTime;          //then calculate the duration of the button press
}
digitalWrite(yellow, LOW);              //turn the LED off when the press is complete
Serial.print(“the button press duration is “); //Print the duration so we know what it is
Serial.println(duration);

guessVal = duration;                //Now we need to round the press
if(guessVal>100 && guessVal<300){   //if the guess falls within this range we set the guess = to the short flash
guessVal = 130;
}
else if(guessVal>600 && guessVal<2000){ //if the guess falls within this range we set the guess = to the long flash
guessVal = 1000;
}else{                                   //otherwise we set it = to something else
guessVal = 5;
}
myGuess[guessPos] = guessVal;            //Now we populate the guess array with the rounded guess val
guessPos++;                              // Increment the guess array position
}
}
lastBPValue = BPValue;                     // Set the last button state equal to the current button state
}
}
if(guessPos == r){        // When the number of guesses = the number of flashes in the pattern, check to see if they match

//print the guess so we know what it is
Serial.print(“myGuess is: “);
int g;
for (g=0; g<11; g++){
Serial.print(myPattern[g]);
Serial.print(“, “);
}
Serial.println(“.”);

//check to see if the guess array matches the pattern array
if(
myPattern[0] == myGuess[0] &&
myPattern[1] == myGuess[1] &&
myPattern[2] == myGuess[2] &&
myPattern[3] == myGuess[3] &&
myPattern[4] == myGuess[4] &&
myPattern[5] == myGuess[5] &&
myPattern[6] == myGuess[6] &&
myPattern[7] == myGuess[7] &&
myPattern[8] == myGuess[8] &&
myPattern[9] == myGuess[9]
){
Serial.println(“Correct! Next round.”);
delay(500);
digitalWrite(green, HIGH);
delay(500);
digitalWrite(green, LOW);
delay(300);
digitalWrite(green, HIGH);
delay(500);
digitalWrite(green, LOW);
}else{
Serial.println(“Sorry, you lose!”);
r = 0;                      //set r to 0 so that we restart the game
delay(500);
digitalWrite(red, HIGH);
delay(500);
digitalWrite(red, LOW);
delay(300);
digitalWrite(red, HIGH);
delay(500);
digitalWrite(red, LOW);
}

}

//=========================

r++;                            // Increment the value of r so that the outer while loop ends eventually
guessPos = 0;                   //Set the guess array position counter back to 0
patPos = 0;                     // Set the pattern array position counter back to 0

if(r>10){                       // reset r to 1 once the value of r is greater
// than the number of flashes we want in our pattern
Serial.println(“You win!”);
r = 1;
}

//set all the values in the pattern array back to 0
int k;
for (k=0; k<11; k++){
myPattern[k] = 0;
}
//set all the values in the guess array back to 0
int q;
for (q=0; q<11; q++){
myGuess[q] = 0;
}
//Wait 2 seconds and begin the cycle again
delay (2000);
}

}

//=================================

Code 2: Start and stop game function using a button

int green = 8;                    // green LED connected to digital pin 8
int yellow = 7;

//Initialize the buttons
int buttonStart = 12;             // button connected to digital pin 12

int state = HIGH;
int BSValue;                      // Used to feel the state of the start button
boolean LastBSValue = LOW;        // Used to remember the last start button state
boolean gameState = LOW;

long time = 0;
long debounce = 200;

void setup()                      // run once, when the sketch starts
{
pinMode(green, OUTPUT);         // sets the green LED pin as output
pinMode(yellow, OUTPUT);
pinMode(buttonStart, INPUT);    // set the start button as input
Serial.begin(9600);             //start serial monitor so we can read the results
}

void loop(){
BSValue = digitalRead(buttonStart);
if (BSValue == HIGH && LastBSValue == LOW && millis() – time > debounce){
if (state == HIGH){
state = LOW;
digitalWrite(green, HIGH);
gameState = HIGH;
Serial.println (“the gamestate is high”);

}else{
state = HIGH;
digitalWrite(green, LOW);
gameState = LOW;
Serial.println(“the gamestate is low”);
time = millis();
}
}
if(gameState == HIGH){
game();
} else{
Serial.println(“push the button.”);
}
digitalWrite(buttonStart, state);
LastBSValue = BSValue;

}

void game()
{
Serial.println (“A new game has begun!”);
digitalWrite(yellow, HIGH);
delay(150);
digitalWrite(yellow, LOW);
delay(150);
}

//======================

Advertisements

2 thoughts on “Morse Code Game

  1. Pingback: Physical Computing Experiments | conteximus

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s