
© Royalty Free/Corbis
More Buttons!
Exercise 1Exercise 2
int led1=8;
int btn1 = 7; // switch is connected to pin 2
int val; // variable for reading the pin status
int btnState; // variable to hold the last button state
boolean lightOn=false;
void setup() {
pinMode( led1, OUTPUT); // Set the switch pin as input
pinMode( btn1, INPUT); // Set the switch pin as input
btnState = digitalRead(btn1); // read the initial state
}
void loop(){
val = digitalRead( btn1); // read input value and store it in val
if (val != btnState) { // the button state has changed!
if (val == HIGH) { // check if the button is pressed
lightOn=!lightOn;
}
}
//control the light here
btnState = val; // save the new state in our variable
}
/*Arduino Example #3- Hit The Lights 2
Purpose: To make a specific number of user-controlled LEDs blink
by using switches or buttons.
*/
void setup(){
Serial.begin(9600); //open up a serial port at 9600 bits per second
}
void loop(){
Serial.println("hello");
Serial.print("hello\n"); // \is an escape sequence used to differentiate a
//character from that in the lanage
delay(500); //slows it down
}
int btn1 = 2; // switch is connected to pin 2
int val; // variable for reading the pin status
int btnState; // variable to hold the button state
int btnPresses = 0; // how many times the button has been pressed
void setup() {
pinMode(btn1, INPUT); // Set the switch pin as input
Serial.begin(9600); // Set up serial communication at 9600bps
btnState = digitalRead(btn1); // read the initial state
}
void loop(){
val = digitalRead(btn1); // read input value and store it in val
if (val != btnState) { // the button state has changed!
if (val == LOW) { // check if the button is pressed
btnPresses++; // increment the buttonPresses variable
Serial.print("Button has been pressed ");
Serial.print(btnPresses);
Serial.println(" times");
}
}
btnState = val; // save the new state in our variable
}