In this tutorial, We'll see how to make use of the push buttons on the InduinoX board.
The push-buttons on the InduinoX are designed to work with the internal pull-up resistor on the microcontroller. For your understanding, They will give a low signal when the button is pressed. Enabling the internal pull up on the microcontroller will keep the corresponding pin HIGH unless the button is being pressed. When the button is being pressed, the corresponding pin will go LOW.
The three push-buttons are connected to Digital Pins 7, 8 & 9
So lets try to write a Simple Program to glow an LED while a button is being pressed. Then we will improvise our Binary Counter Program by adding a button to it.
Heres the code, the comments are self-explanatory
void setup()
{
pinMode(7,INPUT); // Declare the 7th pin as a input pin. We will use the button on the 7th pin
digitalWrite(7,HIGH); // enable the internal pullup resistor - Everytime you use a switch on the InduinoX, do this
pinMode(13,OUTPUT); // Our LED
}
void loop()
{
while(digitalRead(7)==0) // digitalRead(7) will read the current state of pin number 7 and give an output of '0' or '1'.
//In our case, the digitalRead() funciton will return a '0' when the button is being pressed and '1' when the button is not being pressed
// The Control will stay inside the while loop till the button is released
{
digitalWrite(13,HIGH); // Turn the LED ON
}
digitalWrite(13,LOW); // Turn the LED OFF when the control exits the While loop
}
Now Here's the switch added to the Binary Counterand Here's the Code
/*
This sketch increases a 3 bit number every time a button is pressed by the user and shows the output on 3 LEDs
*/
int i = 0;
void setup()
{
pinMode(11,OUTPUT); // declare LED pins as output pins
pinMode(12,OUTPUT);
pinMode(13,OUTPUT);
pinMode(7,INPUT);// Declare the 7th pin as a input pin. We will use the button on the 7th pin
digitalWrite(7,HIGH);
}
void loop()
{
if(digitalRead(7)==0) // if the button is pressed
{
if(i<7) // if counter value is less than 7 or 3 bits
i++; // increment counter value
else
i=0; // reset counter to 0
int a=i%2; // calculate LSB
int b=i/2 %2; // calculate middle bit
int c=i/4 %2; // calculate MSB
digitalWrite(11,c); // write MSB
digitalWrite(12,b); // write middle bit
digitalWrite(13,a); // write LSB
while(digitalRead(7)==0); // wait till button is released to avoid incrementing the counter again
delay(100); // small delay to avoid debounce
}
}
Here's an Interesting tutorial you can refer to know more about various configurations for connecting switches