Powering LEDs that can turn on in either direction, and the controller keeps crashing

Hey all! I’ve been toying with some code that is able to turn on many LED filaments in either orientation, using a square wave AC output I have designed in my code. Pin A0 and A5 are currently alternating being outputs and grounds. With this A0 will be on while A5 is ground and vise versa. With what I have now, I am able to toggle between an off, low, medium, and high PWM output, however the more I toggle between the three, the more susceptible the device has been to crashing and rebooting. Could somebody look at my code and see if there is a bug causing this? Perhaps something to do with returning values? There isn’t much to it as I’m not much of a coder (yet haha). Thanks!
Here is the code:

int led1 = A0;
int led2 = A5;


void setup()
{

   
   pinMode(led1, OUTPUT);
   pinMode(led2, OUTPUT);
  
   Particle.function("led",ledToggle);
  
   digitalWrite(led1, LOW);
   digitalWrite(led2, LOW);

}


int ledToggle(String command) {
  
    while (command=="off") {
        analogWrite(led1,0);
        analogWrite(led2,0);
        delay(5);
        analogWrite(led1,0);
        analogWrite(led2,0);
        delay(5);
    }
    while (command=="l") {
        analogWrite(led1,64);
        analogWrite(led2,0);
        delay(5);
        analogWrite(led1,0);
        analogWrite(led2,64);
        delay(5);
    }
    while (command=="m") {
        analogWrite(led1,120);
        analogWrite(led2,0);
        delay(5);
        analogWrite(led1,0);
        analogWrite(led2,120);
        delay(5);
    }
    while (command=="h") {
        analogWrite(led1,255);
        analogWrite(led2,0);
        delay(5);
        analogWrite(led1,0);
        analogWrite(led2,255);
        delay(5);
    }
    
}

You mustnot trap the code in your function handler with while loops.
With each call you open one loop and never return from that since command for that function call will never ever change again. Over time this will have dozens of ledToggle() instances running, each of them eating intol your stack space eventually exhausting it and causing a system crash.

Particle.function() handlers need to enter, act and leave as quickly as possible.

In that function handler you should set a global variable (e.g. int state) and in your loop() (which you should implement to do regular stuff) you check that state and act upon it (best with a switch(state) block).

BTW, a function that states it will return a vlaue (int in this case) also has to do so, your code is missing the respective return statement.

3 Likes