TinkerKit Tutorial: Basics: 06 – Button & IF function

Basic Lessons:

  1. Introduction
  2. Project Setup
  3. Arduino Software
  4. Starting with the code
  5. Sensors and Actuators
  6. Button & IF statement
  7. Serial Communication
  8. Connect Sensors and Actuators
  9. Button States
  10. FOR Loop
  11. Traffic Light

but

 

We’re going to make a classic: button and LED. We can start by turning the LED on when the button is pressed. Connect a button and an LED to the shield, respectively on port I0 and O0.

The button is a digital sensor, the values that it returns are only two: HIGH and LOW. To see if it is pressed or not there’s the method read().
It’s time to introduce a logic condition called IF. It is used to execute some code only IF something is true. Its syntax is rather intuitive and is:

if (condition) {
  do something
}

an example can be:

if (it’s cold) {
  put a sweater on
}

but how can we say when it’s cold? We need to write it in numbers. For this, we have a set of logic operators:

> greater than
< lesser than
== is equal to
>= greater or equal to
<= lesser or equal to

so our function becomes:

if (temperature < 17) {
  put a sweater on
}

Ok, let’s get back to our button. Can you figure out how can we say “Turn the LED on when the button is pressed” in the Arduino / TinkerKit language? Try to write it by yourself before reading further.

The answer is:

if (button.read() == HIGH) {
  led.on();
}

If we put everything in the right Arduino syntax the result is:

TKLed led(O0);
TKButton button(I0);
void setup() {
}
void loop() {
  if (button.read() == HIGH) {
    led.on();
  }
}

This is correct but once we upload this code into the TinkerKit!, we notice that once we press the button, the LED remains on even when we release the button. That’s because we never say to the LED to turn off. To do that, we can write another “if” function, something like:

if (button.read() == HIGH) {
  led.on();
}
if (button.read() == LOW) {
  led.off();
}

But there’s a smarter way to achieve the same result; the “if” function in fact can be followed by an “else” operator, that is executed when the “if” condition is false. This is how our code looks like with the if-else function:

if (button.read() == HIGH) {
  led.on();
} else {
  led.off();
}

This works because our button can only be HIGH and LOW, pressed or not pressed, so the only way our condition is false, is when button.read() == LOW.

Note that our outcome is exactly the same as the Button example.


 

CHALLENGE:

Before the next tutorial, try to turn the button into a switch, so that every time it is pressed, the LED toggles between on and off.

HINT: look in the reference for a specific button method that might come in handy. If you want to try the hard way, without using other button methods, you need a variable.

 

Prev Section: Sensors and Actuators

Next Section: Serial Communication

Leave a Reply

Your email address will not be published. Required fields are marked *