Use switch and potentiometer to control a LED

by Oscar
In our first project, I will be showing you the basic connections of a LED circuit.
To make it more interesting and challenging, I later on replace the switch with a potentiometer, to control the brightness.
================================
Using 4 legs Switch
================================
potentiometer

[sourcecode language=”cpp”]
/*
Oscar’s project

Some of the links on this page are affiliate links. I receive a commission (at no extra cost to you) if you make a purchase after clicking on one of these affiliate links. This helps support the free content for the community on this website. Please read our Affiliate Link Policy for more information.

turn LED on and off with a switch

*/

// constants type won’t change (just good practice, can declare without)
// set pin numbers:
const int buttonPin = 1; // the number of the pushbutton pin
const int ledPin = 2; // the number of the LED pin

// variables will change:
int buttonState = 0; // variable for reading the pushbutton status

void setup() {

// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}

void loop() {

// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);

// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH)
// turn LED on:
digitalWrite(ledPin, HIGH);
else
// turn LED off:
digitalWrite(ledPin, LOW);

// have some delay (optional)
delay(30);
}
[/sourcecode]

================================
Using Potentiometer
================================
When you are connecting to different Digital outputs, you will find some doesn’t give you the change of brightness effect, but a switching on/off effect, such as 2. Port 3 is the first PWM output in order, so we will use that.The reason is because we need to have PWM (pulse-width modulation) output to have an analogue-like effect, otherwise we will only have a pure digital output which is only on and off. Read more about PWM here XXX.
 
 
 

[sourcecode language=”cpp”]
/*
Oscar’s project
adjust LED lightness using potential meter

*/

int brightness = 0; // how bright the LED is
int ledPin = 3; // PWM output

void setup() {
// declare pin 9 to be an output:
pinMode(ledPin, OUTPUT);
}

void loop() {
int sensorValue = analogRead(A0);

// sensorValue 0 – 1023
// brightness 0 – 255
brightness = sensorValue/4;

// set the brightness of pin 9:
analogWrite(ledPin, brightness);

// wait for 30 milliseconds to see the dimming effect
delay(30);
}
[/sourcecode]

Leave a Comment

By using this form, you agree with the storage and handling of your data by this website. Note that all comments are held for moderation before appearing.

1 comment

(0)(o)-^^',-',-',-',-',-',-',-',-',-- 8th November 2013 - 5:38 pm

I guess the led symbol is wrongly drawn.

Reply