Memory game

For the first project, I created a game that would play a pattern of LEDs, which the user would then have to replicate by pressing the corresponding buttons.  If the user successfully completed the task, the LEDs would flash to show the user has won.  I tried to implement a randomizer to create a new pattern each time, but it didn’t end up working so for now there is only one pattern of lights for the user to play.

Code:

int red = 11;                 // red LED connected to digital pin 11
int blue = 12;                // blue LED connected to digital pin 12
int green = 13;              // green LED connected to digital pin 13
int redButton = 2;          // button for red LED connected to pin 2
int blueButton = 3;          // button for blue  LED connected to pin 3
int greenButton = 4;        // button for green LED connected to pin 4
int val1 = 0;
int val2 = 0;
int val3 = 0;
int prev1 = LOW;
int prev2 = LOW;
int prev3 = LOW;
long time = 0;
long debounce = 200;

boolean playing = false;
boolean won;

long num1;
long num2;
long num3;
long num4;
long num5;

void setup()
{
pinMode(red, OUTPUT);      // sets the LED pins as output
pinMode(blue, OUTPUT);
pinMode(green, OUTPUT);
pinMode(redButton, INPUT);  //sets the button pins as input
pinMode(greenButton, INPUT);
pinMode(blueButton, INPUT);
}

//set up play pattern array
int pattern[]={
red,blue,blue,green,red};
int results[]={
};

void loop()
{
if (playing==false){
playPattern();
playing=true;
}
else {
playerTurn();
}

/* TEST LEDS CODE
if(val1==LOW) {
digitalWrite(red, HIGH);
} else {
digitalWrite(red, LOW);
}

if(val2==LOW) {
digitalWrite(blue, HIGH);
} else {
digitalWrite(blue, LOW);
}

if(val3==LOW) {
digitalWrite(green, HIGH);
} else {
digitalWrite(green, LOW);
}
*/
}

void playPattern()
{
digitalWrite(pattern[0], HIGH);   // sets the LED on
delay(1000);                  // waits for a second
digitalWrite(pattern[0], LOW);    // sets the LED off
delay(500);
digitalWrite(pattern[1], HIGH);
delay(1000);                  // waits for a second
digitalWrite(pattern[1], LOW);
delay(500);
digitalWrite(pattern[2], HIGH);
delay(1000);
digitalWrite(pattern[2], LOW);
delay(500);
digitalWrite(pattern[3], HIGH);
delay(1000);
digitalWrite(pattern[3], LOW);
delay(500);
digitalWrite(pattern[4], HIGH);
delay(1000);
digitalWrite(pattern[4], LOW);
delay(500);
digitalWrite(pattern[5], HIGH);
delay(1000);
digitalWrite(pattern[5], LOW);
delay(1000);
}

void playerTurn()
{
for(int i=0; i<5; i++) {

val1 = digitalRead(redButton);
val2 = digitalRead(greenButton);
val3 = digitalRead(blueButton);

if(val1==HIGH && prev1==LOW && millis() – time > debounce) {
//red was pressed
digitalWrite(red, HIGH);   // sets the LED on
delay(500);                  // waits for a second
digitalWrite(red, LOW);    // sets the LED off
results[i]=red;
time = millis();
}
if(val2==HIGH && prev2==LOW && millis() – time > debounce) {
//green was pressed
digitalWrite(green, HIGH);   // sets the LED on
delay(500);                  // waits for a second
digitalWrite(green, LOW);    // sets the LED off
results[i]=green;
time = millis();
}
if(val3==HIGH && prev3==LOW && millis() – time > debounce) {
//blue was pressed
digitalWrite(blue, HIGH);   // sets the LED on
delay(500);                  // waits for a second
digitalWrite(blue, LOW);    // sets the LED off
results[i]=blue;
time = millis();
}
prev1=val1;
prev2=val2;
prev3=val3;
}

for(int j=0; j<5; j++) {
if (pattern[j] != results[j]) {
won=false;
}
}

if (won==false) {
//play pattern again
}
else {
//flash lights
for(int k=0; k<5; k++) {
digitalWrite(red, HIGH);   // sets the LED on
digitalWrite(green, HIGH);    // sets the LED on
digitalWrite(blue, HIGH);    // sets the LED on
delay(100);                  // waits for a second
digitalWrite(red, LOW);    // sets the LED off
digitalWrite(green, LOW);    // sets the LED off
digitalWrite(blue, LOW);      // sets the LED off
delay(100);                  // waits for a second
}
}

}

Song-Playing Shirt

For exercise three, I used a buzzer embedded in a shirt to play two holiday-themed songs, each activated by a button.  The buzzer plays songs by using an array of notes and an array of beats.  The notes are found by converting standard pitch notes into frequencies and then into periods using the formula period = 1/frequency.

Video:

http://www.vimeo.com/2049436

Code (adapted from buzzer code on Arduino website):

// TONES  ==========================================
// Start by defining the relationship between
//       note, period, &  frequency.
#define  lowa  4545    // 220 Hz
#define  lowb  4048    // 247 Hz
#define  c     3830    // 261 Hz
#define  d     3400    // 294 Hz
#define  e     3038    // 329 Hz
#define  f     2865    // 349 Hz
#define  g     2550    // 392 Hz
#define  a     2272    // 440 Hz
#define  as    2145    // 466 Hz  – calculated using period = 1/frequency
#define  b     2028    // 493 Hz
#define  C     1912    // 523 Hz
// Define a special note, ‘R’, to represent a rest
#define  R     0

// SETUP ============================================
// Set up speaker on a PWM pin (digital 9, 10 or 11)
int speakerOut = 9;
int button1 = 2;
int button2 = 4;
int state1 = LOW;
int state2 = LOW;
int reading1;
int previous1 = LOW;
int reading2;
int previous2 = LOW;

long time = 0;
long debounce = 200;

// Do we want debugging on serial out? 1 for yes, 0 for no
int DEBUG = 1;
int counter = 0;
int plays = 1;

void setup() {
pinMode(speakerOut, OUTPUT);
pinMode(button1, INPUT);
pinMode(button2, INPUT);
if (DEBUG) {
Serial.begin(9600); // Set serial out if we want debugging
}
}

// MELODY and TIMING  =======================================
//  melody[] is an array of notes, accompanied by beats[],
//  which sets each note’s relative length (higher #, longer note)
int melody[] = {
C,  b,  g,  C,  b,   e,  R,  C,  c,  g, a, C };
int happybirthday[] = {
c,c,d,c,f,e,R, c,c,d,c,g,f,R, c,c,C,a,f,e,d,R, as,as,a,f,g,f,R,R};
int heartandsoul[] = {
c,c,c, c,lowb,lowa,lowb,c,d, e,e,e, e,d,c,d,e,f, g,c, a,g,f,e,d,c,R,R };
int beats[]  = {
16, 16, 16,  8,  8,  16, 32, 16, 16, 16, 8, 8 };
int beatsHB[] = {
16,16,32,32,32,32,16, 16,16,32,32,32,32,16, 16,16,32,32,32,32,16, 16,16,32,32,32,32,16,16};
int beatsHS[] = {
32,32,96, 16,16,16,16,16,32, 32,32,96, 16,16,16,16,16,32, 64,96, 16,16,16,32,32,96, 32,32};
//int MAX_COUNT = sizeof(melody) / 2; // Melody length, for looping.
int MAX_COUNT = sizeof(heartandsoul) / 2;

// Set overall tempo
long tempo = 10000;
// Set length of pause between notes
int pause = 1000;
// Loop variable to increase Rest length
int rest_count = 100; //<-BLETCHEROUS HACK; See NOTES

// Initialize core variables
int tone = 0;
int beat = 0;
long duration  = 0;

// PLAY TONE  ==============================================
// Pulse the speaker to play a tone for a particular duration
void playTone() {
long elapsed_time = 0;
if (tone > 0) { // if this isn’t a Rest beat, while the tone has
//  played less long than ‘duration’, pulse speaker HIGH and LOW
while (elapsed_time < duration) {

digitalWrite(speakerOut,HIGH);
delayMicroseconds(tone / 2);

// DOWN
digitalWrite(speakerOut, LOW);
delayMicroseconds(tone / 2);

// Keep track of how long we pulsed
elapsed_time += (tone);
}
}
else { // Rest beat; loop times delay
for (int j = 0; j < rest_count; j++) { // See NOTE on rest_count
delayMicroseconds(duration);
}
}
}

void loop() {

reading1 = digitalRead(button1);
reading2 = digitalRead(button2);

if(reading1 == LOW) {
if(counter < plays) {
for (int i=0; i<MAX_COUNT; i++) {
//tone = melody[i];
tone = happybirthday[i];
//tone = heartandsoul[i];
//beat = beats[i];
beat = beatsHB[i];
//beat = beatsHS[i];

duration = beat * tempo; // Set up timing

playTone();
// A pause between notes…
delayMicroseconds(pause);

if (DEBUG) { // If debugging, report loop, tone, beat, and duration
Serial.print(i);
Serial.print(“:”);
Serial.print(beat);
Serial.print(” “);
Serial.print(tone);
Serial.print(” “);
Serial.println(duration);
}
}
counter = counter + 1;
}
}
else if (reading2 == LOW) {
if(counter < plays) {
for (int i=0; i<MAX_COUNT; i++) {
//tone = melody[i];
//tone = happybirthday[i];
tone = heartandsoul[i];
//beat = beats[i];
//beat = beatsHB[i];
beat = beatsHS[i];

duration = beat * tempo; // Set up timing

playTone();
// A pause between notes…
delayMicroseconds(pause);

if (DEBUG) { // If debugging, report loop, tone, beat, and duration
Serial.print(i);
Serial.print(“:”);
Serial.print(beat);
Serial.print(” “);
Serial.print(tone);
Serial.print(” “);
Serial.println(duration);
}
}
counter = counter + 1;
}
}
else {
//do nothing
}
counter = 0;
}

light sensing scarf

For the second exercise, I attached a blue LED, a green LED, and a light sensor to a scarf to alert the wearer when the light in the area has been low too often.  The green LED grows brighter and the blue LED becomes dimmer when there is more light, and the opposite happens as there is less light.  If the light sensor detects a very low level of light 3 times, the blue and green LEDs will flash 10 times as a warning.

Code:

/*
Analog Input and Output
Justine
*/

int sensorIn = 3;   // input pin for light sensor
int bluePin = 11;   // blue LED pin
int greenPin = 10;  // green LED pin
int inval = 0;      // variable to store value coming from the sensor
int val = 0;        // variable to store value after dividing
int counter = 0;    // variable to store counter for light level
boolean lowLight = false;  //boolean to store whether there is low light

void setup() {
pinMode(bluePin, OUTPUT);  // declare bluePin as an OUTPUT
pinMode(greenPin, OUTPUT); // declare greenPin as an OUTPUT
Serial.begin(9600);       // start comunication with the computer
}

void loop() {
inval = analogRead(sensorIn);    // read the value from the sensor range 0 – 1024
val = inval/4;                  // divide the value by 4 so it is between 0 and 255
//Serial.println(val);         // Send val to the pc, can be seen using Serial Monitor

//blue light gets dimmer and green light gets brighter as light gets brighter
analogWrite(bluePin, val);        //make the blue light shine at the brightness of val
analogWrite(greenPin, 255-val);  //make the green light shine at the opposite of the blue

if (lowLight == false && val > 225) {  //if light has just become low
counter = counter + 1;                //update counter
lowLight = true;                      //update boolean to show low light
//Serial.println(counter);            //send counter to the pc for testing purposes
}

if (val < 215) {                  //if light becomes high again
lowLight = false;              //update boolean
}

// if light has been low 3 times, flash a warning
if (counter >= 3) {
for (int i=0; i<10; i++) {
analogWrite(bluePin, 255);
delay(200);
analogWrite(bluePin, 0);
analogWrite(greenPin, 255);
delay(200);
analogWrite(greenPin, 0);
}
counter = 0;
}

}

Another idea I was considering (or maybe an accessory?) with the same code, light sensing earrings:

Red Sox victory hat

I updated a hat to blink a red LED when the wearer presses the “B,” and to turn it off when the “B” is pressed again.  This could used by a fan to display when his or her favorite team wins, which, since it’s the Red Sox, means the hat would be blinking a lot.

Code:

int inPin = 2;         // the number of the input pin
int ledPin = 13;       // the number of the output pin

int state = HIGH;      // the current state of the output pin
int reading;           // the current reading from the input pin
int previous = LOW;    // the previous reading from the input pin

// the follow variables are long’s because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

void setup()
{
pinMode(inPin, INPUT);
pinMode(ledPin, OUTPUT);
}

void loop()
{
reading = digitalRead(inPin);

// if the input just went from LOW and HIGH and we’ve waited long enough
// to ignore any noise on the circuit, toggle the output pin and remember
// the time
if (reading == HIGH && previous == LOW && millis() – time > debounce) {
if (state == HIGH)
state = LOW;
else
state = HIGH;

time = millis();
}

digitalWrite(ledPin, state);  //Light or turn off LED based on state
delay(100);
digitalWrite(ledPin, LOW);    //turn LED off, causes blinking of state=HIGH
delay(100);

previous = reading;          //update previous to current reading
}