I have created a simple program in MSP430 using Energia for counting the button presses from 0 up to 9 and displaying them in a Seven Segment Display.
The code including the definitions of the pins, the state of the pins (set as Input or Output) and the trivial displaying routine is omitted as it would be far too long. If there is any need for it tell me and I will edit my question.
The essential code is:
void loop()
{
ButtonState=digitalRead(Button);
if (ButtonState!=LastButtonState)
{
if (ButtonState==HIGH)
{
ButtonCounter++;
}
}
LastButtonState=ButtonState;
if(ButtonCounter==0)
{
Zero();
}
else if(ButtonCounter==1)
{
...
}
I couldn't make the display start from 0 at the beginning when I hadn't pressed the button but it was always beginning displaying 1 until I changed:
if (ButtonState==HIGH)
to
if (ButtonState==LOW)
And it is working perfectly! But it seems to me very weird.
Why is this happening? When I am not pressing the button isn't its state LOW? As it is beginning from 1 it means that its state when not pressed is HIGH. Shouldn't the correct be:
if (ButtonState==HIGH)
so to chech if the button is pressed and then increment the counter? With LOW as the comparison then it is checking when the button is not pressed, so why it works perfectly?
The schematic for the button can be found here.
Best Answer
I think there's some incorrect documentation. If you followed the schematic from the link you provided, then when the button is not pressed, the state would HIGH.
The code explanation says
But this isnt the case. The hardware says when the button is pressed, the button state will be LOW.
What they did was copy the arduino button tutorial and just modified it slightly for use with the Energia board. If you look at the Arduino schematic, it's more inline with what you are expecting. So their code description is incorrect.
If you use the Energia schematic, then you need to be using LOW and if you are using the Arduino schematic then you need to be using HIGH.