Assignment 4.2

Post date: Jun 28, 2010 3:54:20 AM

I attached a bit of wire to each glove on the giraffe and taped one arm so it was always out. I attached wires together so I could get a length where I could easily move the giraffe around without moving the whole breadboard. The wires are attached to pin 2 using the basic push button example. Every time the arm not taped down is pressed, the wires touch, completing the circuit, and causing the Serial Monitor to display a different message each time. It will cycle through the messages, displaying "BAM," "POW," "THUNK," "KAPOW," and then "K.O."

Here's the code:

int switchPin = 2; // switch is connected to pin 2

int val; // variable for reading the pin status

int buttonState; // variable to hold the button state

int buttonPresses; // how many times the button has been pressed

void setup() {

pinMode(switchPin, INPUT); // Set the switch pin as input

Serial.begin(9600); // Set up serial communication at 9600bps buttonState = digitalRead(switchPin); // read the initial state

}

void loop(){

val = digitalRead(switchPin); // read input value and store it in val

if (val != buttonState) { // the button state has changed!

if (val == LOW) { // check if the button is pressed

if (buttonPresses == 0) { // if number of buttons pressed is this much

buttonPresses = 1; } // run this function

else{ // if not, do this:

if (buttonPresses == 1) {

buttonPresses = 2; }

else{

if (buttonPresses == 2) {

buttonPresses = 3; }

else{

if (buttonPresses == 3) {

buttonPresses = 4; }

else{

if (buttonPresses == 4) {

buttonPresses = 5;

}

}

}

}

}

}

buttonState = val; // save the new state in our variable

if (buttonPresses == 1) { // if buttonPresses is this many,

Serial.println("BAM"); // display this message and

buttonPresses = 2; // change variable to this value

}

if (buttonPresses == 2) {

Serial.println("POW");

buttonPresses = 3;

}

if (buttonPresses == 3) {

Serial.println("THUNK");

buttonPresses = 4;

}

if (buttonPresses == 4) {

Serial.println("KAPOW");

buttonPresses = 5;

}

if (buttonPresses == 5) {

Serial.println("K.O.");

buttonPresses = 0; // resets value to 0

}

}

}