I'm trying to make a program that detects how many out of four buttons are pressed, and display that number on a 7 segment display, but the display shows "8" now matter how many buttons are pressed, even if none are. I have the pins of the display connected to Arduino pins 2-8, and the buttons connected to Arduino pins 9-12. The buttons are getting power from the 5V pin on the Arduino, and the display is using GND. Here is the code:
/*
Sketch Author: xxxxxxxx
Date Started: 2/12/2011
Date Finished: 2/13/2011
Desc: This sketch detects how many (not which) buttons are
pressed, and displays that number on the 7 segment display.
*/
//define pin numbers
//7 segment display
const int a = 2;
const int b = 3;
const int c = 4;
const int d = 5;
const int e = 6;
const int f = 7;
const int g = 8;
//buttons
const int b1 = 9;
const int b2 = 10;
const int b3 = 11;
const int b4 = 12;
//define varables
int b1State = 0;
int b2State = 0;
int b3State = 0;
int b4State = 0;
int numPressed = 0;
void setup()
{
pinMode(a, OUTPUT);
pinMode(b, OUTPUT);
pinMode(c, OUTPUT);
pinMode(d, OUTPUT);
pinMode(e, OUTPUT);
pinMode(f, OUTPUT);
pinMode(g, OUTPUT);
pinMode(b1, INPUT);
pinMode(b2, INPUT);
pinMode(b3, INPUT);
pinMode(b4, INPUT);
}
void loop()
{
if (digitalRead(b1) == HIGH) //find out if button 1 is pressed
{
b1State = 1;
}
else
{
b1State = 0;
}
if (digitalRead(b2) == HIGH) //find out if button 2 is pressed
{
b2State = 1;
}
else
{
b2State = 0;
}
if (digitalRead(b3) == HIGH) //find out if button 3 is pressed
{
b3State = 1;
}
else
{
b3State = 0;
}
if (digitalRead(b4) == HIGH) //find out if button 4 is pressed
{
b4State = 1;
}
else
{
b4State = 0;
}
numPressed = b1State + b2State + b3State + b4State; //add up how many buttons are pressed
switch (numPressed)
{
case 1: //displays the number 1
digitalWrite(a, LOW);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, LOW);
digitalWrite(e, LOW);
digitalWrite(f, LOW);
digitalWrite(g, LOW);
case 2: //displays the number 2
digitalWrite(a, HIGH);
digitalWrite(b, HIGH);
digitalWrite(c, LOW);
digitalWrite(d, HIGH);
digitalWrite(e, HIGH);
digitalWrite(f, LOW);
digitalWrite(g, HIGH);
case 3: //displays the number 3
digitalWrite(a, HIGH);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, HIGH);
digitalWrite(e, LOW);
digitalWrite(f, LOW);
digitalWrite(g, HIGH);
case 4: //displays the number 4
digitalWrite(a, LOW);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, LOW);
digitalWrite(e, LOW);
digitalWrite(f, HIGH);
digitalWrite(g, HIGH);
default: //displays the number 0
digitalWrite(a, HIGH);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, HIGH);
digitalWrite(e, HIGH);
digitalWrite(f, HIGH);
digitalWrite(g, LOW);
}
}