Make It Better

Light Switch

If you feel the initial example is a bit underwhelming ("I don't need a metro to do this!"), let's use the metro to do something a bit more complicated. We are going to make a light-switch. One of the buttons on your breadboard is going to turn on the light, and the other is going to turn it off!

This is super simple, we're just going to change a few lines of code:

Download: file
int ledPin = 13; // choose the pin for the LED
int buttonPin1 = 3; // button 1
int buttonPin2 = 2; // button 2

void setup() {
  pinMode(ledPin, OUTPUT); // declare LED as output
  pinMode(buttonPin1, INPUT); // make button 1 an input
  pinMode(buttonPin1, INPUT); // make button 2 an input
}

void loop() {
  if (digitalRead(buttonPin1) == LOW) {
    digitalWrite(ledPin, LOW); // turn LED OFF
  }
  else if (digitalRead(buttonPin2) == LOW) {
    digitalWrite(ledPin, HIGH); // turn LED ON
  }
}

Copy and paste the code into a blank sketch, upload it to the board, and start toggling the LED on and off.

Fading

Let's use the buttons to control an analog signal. To do this, you will need to change the wire connecting the LED from Pin 13 to Pin 9.

In the code, change:

  int ledPin = 13; -> int ledPin = 9;

Next, change the loop() code to read:

Download: file
int value = 0;
void loop() { 
  if(digitalRead(buttonPin1) == LOW){
    value--;
  }
  else if(digitalRead(buttonPin2) == LOW){
    value++;
  }
  value = constrain(value, 0, 255);
  analogWrite(ledPin, value);
  delay(10);
}

Changing Fade Speed

If you would like the LED to fade faster or slower, there is only one line of code that needs to be changed:

     delay(10); -> delay(new #);

To fade faster: make the number smaller

To fade slower: make the number larger.

This guide was first published on Aug 18, 2017. It was last updated on Aug 18, 2017. This page (Make It Better) was last updated on Mar 17, 2020.