Back to Parent

//Exercise 1: Combine a switch and potentiometer.
//The switch should turn on and off the light while the potentiometer will fade up and down the light (but only when its on).

int potPin = A5;
int potReading = 0; //create a variable to hold the pot reading

int ledPin = D2;
int ledBrightness = 0; //create a variable to store the LED brightness

int switchPin = D3;

void setup() {

    pinMode(ledPin,OUTPUT); //set pin as output
    pinMode(switchPin,INPUT_PULLUP); //set pin as input
    Spark.variable("pot", potReading ); //create a cloud variable of type integer

void loop() {
    int switchState = digitalRead(switchPin);
    //use analogRead to read the potentiometer reading
    //This gives us a value rom 0 to 4095
    if (switchState == LOW)
        digitalWrite(ledPin, HIGH);
        potReading = analogRead(potPin); //0-4095
        //Map this value into the PWM range (0-255)
        //And store as the led brightness
        int ledBrightness = map(potReading,0,4095,0,255);
        //fade the LED to the desired brightness
        analogWrite(ledPin, ledBrightness ); //0-255

        //wait 1/10th of a second and then loop
        digitalWrite(ledPin, LOW);
Click to Expand

Content Rating

Is this a good/useful/informative piece of content to include in the project? Have your say!