Coding a Switch in Arduino – Part Two

To further extend my understanding (and my disequilibrium) around coding switches I have taken a project from the book I mentioned previously, Introduction to Arduino: A piece of cake!, by Alan G. Smith, September 30, 2011, that uses two buttons, one LED, a resistor, and code that uses Pulse Width Modulation (PWM). I’ve seen the PWM before in another exercise and this project has helped reinforce the notion.

Breadboard with one LED, two switches, one resistor. +/- are wired into right column.

Breadboard with one LED, two switches, one resistor. +/- are wired into right column.

const int kPinButton1 = 2;
const int kPinButton2 = 3;
const int kPinLed = 9;

void setup() {
pinMode(kPinButton1, INPUT);
pinMode(kPinButton2, INPUT);
pinMode(kPinLed, OUTPUT);
digitalWrite(kPinButton1, HIGH);
digitalWrite(kPinButton2, HIGH);

int ledBrightness = 128;
void loop()
{
if(digitalRead(kPinButton1) == LOW){
ledBrightness–;
}
else if(digitalRead(kPinButton2) == LOW){
ledBrightness++;
}

ledBrightness = constrain(ledBrightness, 0, 255);
analogWrite(kPinLed, ledBrightness);
delay(20);
}

• Which coding concepts were introduced by coding two switches?

Just adding another switch wouldn’t have been too interesting without using PWM to differentiate between the use of the two switches. What makes this project interesting is introducing ‘– and ++’ to make the LED brighter and dimmer.

ledBrightness = constrain(ledBrightness, 0, 255); “guarantees the value of ledBrightness will be between 0 and 255 (including 0 and 255)”

analogWrite(kPinLed, ledBrightness); “uses analogWrite to tell Arduino to perform PWM on that pin with the set value.”

delay(20); “delays for 20 milliseconds so that we won’t make adjustments faster than 50 times in a second. (You can adjust this to find where you think the best response is to your pressing the buttons.) The reason we do this is that people are much slower than the Arduino. If we didn’t do this, then this program would appear that pressing the first button turns the LED off and pressing the second button turns it on.”

• Describe the computational thinking that you are practicing when creating/coding two switches:

Change of state through a variable. Taking human factors in mind when programming – without the delay the LED would look like it’s just turning off.

Leave a Reply