int inPin = 2; // pushbutton connected to digital pin 2
int val; // variable to store the read value
void setup() {
Serial.begin(9600);
pinMode(inPin, INPUT);
}
void loop() {
Serial.println(val);
val = digitalRead(inPin);
if (inPin, HIGH)
{
Serial.println("yay");
}
if (inPin, LOW)
{
Serial.println("nooooo");
}
}
It all depends on how you have your button wired. Don't make the mistake of thinking HIGH is on and LOW is off. They are just arbitrary states of the pin. They can mean anything you want them to. It's more common for us to wire a button so that when it's closed the input pin state is LOW and when it's open the input pin state is HIGH. The reason is that allows you to use the internal pull-up resistors of the microcontroller instead of needing to add external pull-down resistors to your circuit:
Do you see how that code is now self explanatory without even adding a comment? You could forget about that sketch and come back to it after a year and it would still make perfect sense. Whereas with this code:
if(digitalRead(buttonPin) == LOW) {
You might have to spend a little time to figure out what the LOW state indicates.
Valeriya:
Fair enough, but can you just tell me how come when I press the button it's 0 and when not pressing it's 1? Shouldn't it be the other way around?
Need a wiring diagram to tell for sure but most physical buttons as well as other devices are wired such that LOW is the "active" state. So, as pert said, don't read much into HIGH and LOW as they are just descriptions of the state of the input.