Jewelbots Tutorials Lesson 6: Pushing buttons

Up to this point, every program we’ve coded for the Jewelbot has been written inside the loop function, so when you upload the program and then unplug your Jewelbot the program starts running right away.

We can also write programs that don’t start running right away: instead, they start when you press the magic button on the face of the Jewelbot.

To do this, we use a new function that the creators of Jewelbots have made. It’s called button_press. Let’s try it out!

Add the function in — put it below void setup and void loop. We have to write void before it, just as with setup and loop.

void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}
void button_press(){   // here’s our new function!
}

Let’s have an LED light up in blue for one second when you press the magic button.

In your program, after void button_press(), we now put the lines of code that turn the LED on in blue, have it stay on for one minute, and then turn it off:

void button_press(){   // here’s our new function!
LED led;
Timer timer;
led.turn_on_single(NE, BLUE);
timer.pause (1000);
led.turn_off_single(NE);
}

Upload this new program to your Jewelbot, unplug the Jewelbot from the computer, and press the button!

You should see the Jewelbot light up for one second.

We can also make the Jewelbot do something different when the magic button is pressed for a longer amount of time (around 3 seconds). To do this, we use the button_press_long function. Let’s try lighting up a different LED in green when the button is pressed for three seconds:

void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}
void button_press(){
LED led;
Timer timer;
led.turn_on_single(NE, BLUE);
timer.pause (1000);
led.turn_off_single(NE);
}
void button_press_long(){
LED led;
Timer timer;
led.turn_on_single(NW, GREEN);
timer.pause(1000);
led.turn_off_single(NW);
}

Upload this program to your Jewelbot and unplug the Jewelbot from your computer. Now you’ll see that if you press the button for one second the northeast LED turns on in blue, and if you press the button for three seconds the northwest LED turns on in green. That’s pretty cool — you can program your Jewelbot to do two different things depending on how long you press the magic button!

In the next lesson, we’ll dive into the concept of variables, and how they can help you to program more efficiently!