Back to Parent

// Define a pin we will place an LED on
int ledPin = D2;

// Create a variable to store the LED brightness
int ledBrightness = 0;

// Define a pin for the button
int buttonPin = D4;

// Create a variable to store if button has been pushed
int buttonState;

// Define a pin that we will place the photo cell on
// Remember this is a 10K Ohm pull-down resistor
int photoCellPin = A0;

// Create a variable to hold the light reading
int photoCellReading = 0;

void setup() {
// For input, we define the
// pushbutton as an input-pullup
// this uses an internal pullup resistor
// to manage consistent reads from the device

pinMode( buttonPin, INPUT_PULLUP); // sets pin as input
  
// Setup the LED for output
pinMode( ledPin, OUTPUT);

// Create a cloud variable of type integer
// called "light" mapped to photoCellReading
Particle.variable("light", &photoCellReading, INT);

}

void loop() {

    // find out if the button is pushed or not by reading from it
    buttonState = digitalRead( buttonPin);
    
    if(buttonState == LOW)
    {
        // Turn sensor "on"
        // Use analogRead to read the photo cell reading
        // This gives us a value from 0 to 4095
        photoCellReading = analogRead(photoCellPin);
  
        // Map this value inti the PWM range (0-255)
        // and store this as the led brightness
        ledBrightness = map(photoCellReading, 0, 4095, 0, 255);
        
        // Fade the LED to the desired brightness
        analogWrite( ledPin, ledBrightness);
        
        }else{
            // Turn sensor "off" 
            // Use analogRead to read the photo cell reading
            // This gives us a value from 0 to 4095
            photoCellReading = 0;
            ledBrightness = map(photoCellReading, 0, 4095, 0, 255);
            // Turn off the LED 
        analogWrite( ledPin, ledBrightness);
    }
    
}
Click to Expand

Content Rating

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

0