Instruction:
Code:
- A push-button is connected to pin number 2.
- Write a program that will count the number of time the button is pressed. Whenever a button is pressed the program will send the count including the latest one. That is the program will send the count if and only if button is pressed.
Code:
/* Name: Switch Counter
*/
int pin_2 = 2; //button pin
int buttonState; //button state
int val;
int cnt = 0; //button press counter
void setup() {
pinMode(pin_2, INPUT); //setup button pin as input
Serial.begin(9600); //initialize serial
buttonState = digitalRead(pin_2); //read the button state
}
void loop(){
val = digitalRead(pin_2); //read the button state
if (val != buttonState) {
if (val == HIGH) {
cnt++; //increment button counter
Serial.println(cnt); //print the value of button press counter
}
}
buttonState = val;
}
No comments:
Post a Comment