Back to Parent

// define pins
int ledPin = D2;
int switchPin = D3;
int lightSensorPin = A2;
// create a variable to store light sensor reading
int lightReading = 0;
// create a variable to store LED brightness
int ledBrightness = 0;

void setup() {
    // define switchPin as INPUT_PULLUP
    pinMode(switchPin, INPUT_PULLUP);
    // define ledPin as OUTPUT
    pinMode(ledPin, OUTPUT);
    // create a cloud variable
    Particle.variable("light", lightReading);

}

void loop() {
    // read button state
    int buttonState = digitalRead(switchPin);
    
    if(buttonState == LOW){
        digitalWrite(ledPin, HIGH);
        
        // use analogRead to read light sensor (analogRead gives range 0-4095)
        lightReading = analogRead(lightSensorPin);
        
        // map lightReading to PWM range (0-255) and store it as ledBrightness
        ledBrightness = map(lightReading, 4095, 2000, 0, 255);
        
        // fade the LED to the desired brighness
        analogWrite(ledPin, ledBrightness);
        
        delay(100);
    }
    else{
        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!

0