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
================================
================================
Using 4 legs Switch
================================
/* Oscar's project 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); } |
================================
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.
/* 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); } |