Back to Parent

// GPT HELP
    // Since I was able to get the lights blinking back and forth in the Connected_LED app, I realized that this would only make them blink through a single loop.
    // I wanted these LEDs to blink back and forth in a loop when HIGH was called, and stop when LOW was called
    // With GPTs help, I was able to figure out that a global boolean variable would be needed, so that this controls the LEDS by setting true or false statements on their behavior

//Explanation
    // Global Variable blinking: This boolean variable controls whether the LEDs are blinking or not.
    // loop() Function: If blinking is true, the loop() function alternates the LEDs on and off with a 500 ms delay
    // ledControl Function: When HIGH is passed, blinking is set to true, so the LEDs start blinking. When LOW is passed, blinking is set to false, stopping the blinking loop.
    
    // Now, when I call HIGH, the LEDs will continuously blink back and forth until I call LOW.



// Include Particle Device OS APIs
#include "Particle.h"

// Let Device OS manage the connection to the Particle Cloud
SYSTEM_MODE(AUTOMATIC);

// Show system, cloud connectivity, and application logs over USB
// View logs with CLI using 'particle serial monitor --follow'
SerialLogHandler logHandler(LOG_LEVEL_INFO);

// Define LED pins
int led1 = D2; 
int led2 = D3;

// Define a global variable to control the blinking state
bool blinking = false;

// setup() runs once, when the device is first turned on
void setup() {
    // Register our Particle function here
    Particle.function("led", ledControl);

    // Set the LED pins as outputs
    pinMode(led1, OUTPUT);
    pinMode(led2, OUTPUT);

    // Initialize both LEDs to be OFF
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
}

// loop() runs over and over again, as quickly as it can execute.
void loop() {
    // If blinking is true, alternate the LEDs
    if (blinking) {
        digitalWrite(led1, HIGH);    // Turn ON LED1
        digitalWrite(led2, LOW);     // Turn OFF LED2
        delay(500);                  // Wait for 500ms

        digitalWrite(led1, LOW);     // Turn OFF LED1
        digitalWrite(led2, HIGH);    // Turn ON LED2
        delay(500);                  // Wait for 500ms
    } else {
        // Make sure LEDs are off if blinking is false
        digitalWrite(led1, LOW);
        digitalWrite(led2, LOW);
    }
}

// Function to control LEDs via cloud command
int ledControl(String command) {
    if (command == "HIGH") {
        blinking = true; // Start blinking when HIGH is called
    } else if (command == "LOW") {
        blinking = false; // Stop blinking when LOW is called
    } else {
        return -1; // Invalid command
    }
    return 1;
}
Click to Expand

Content Rating

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

0