Simple Stick User Guide - Programming the Push Button
In this tutorial, We'll see how to make use of the push button on the Simple Stick.
Heres the code, the comments are self-explanatory
Simple_Button.ino
Now Here's the switch added to the Binary Counter
Button_Binary_Counter.ino
In this tutorial, We'll see how to make use of the push button on the Simple Stick.
The push-button on the Simple Stick is 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 push-buttons is connected to Digital Pin 11
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 a demo videoHeres the code, the comments are self-explanatory
Simple_Button.ino
/*
This sketch turns on the LED while the button is being pressed
*/
void setup()
{
pinMode(11,INPUT); // Declare the 11th pin as a input pin. The button is on the 11th pin
digitalWrite(11,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(11)==0) // digitalRead(11) 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 Counter
Button_Binary_Counter.ino
/*
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(5,OUTPUT); // declare LED pins as output pins
pinMode(10,OUTPUT);
pinMode(13,OUTPUT);
pinMode(11,INPUT);// Declare the 11th pin - Button - as a input pin.
digitalWrite(11,HIGH);
}
void loop()
{
if(digitalRead(11)==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(5,c); // write MSB
digitalWrite(10,b); // write middle bit
digitalWrite(13,a); // write LSB
while(digitalRead(11)==0); // wait till button is released to avoid incrementing the counter again
delay(100); // small delay to avoid debounce
}
}
No comments:
Post a Comment