Your new topic does not fit any of the above??? Check first. Then post here. Thanks.

Moderator: igrr

User avatar
By spy king
#38263 I would like to use my Esp-12 to fade some LED's. I have the hardware part up and running fine now, but am having some issues with the software side.

I currently have a simple TCP server running on the ESP, and when it receives a command command, it runs a for loop to fade smoothly to the required brightness level.
However, I would like to avoid the blocking nature of that loop and hence would like suggestions for alternatives!

Would it be alright to call attach a ticker function that is called at 5ms intervals to perform the fading?
User avatar
By WereCatf
#38368 How about this pseudocode:
Code: Select allbool ledflag = false;
uint16_t ledtargetval;
uint16_t ledcurrentval = 0;

//set up your system, whatever
//attach a timer to timerfunction() at 5ms intervals when you receive a request to change the led's status

void timerfunction(){
if(ledtargetval == ledcurrentval){ /*detach your timerfunction here since you reached the requested value*/ }
  else {
  if(ledtargetval < ledcurrentval) ledcurrentval--;
  else ledcurrentval++;
  ledflag = true;
  }
}

loop(){
//do whatever
if(ledflag) analogWrite(pin, ledcurrentval);
}


Pros: This approach is non-block and is easily extensible for all sorts of uses, and generally-speaking you shouldn't do any heavy-lifting in a timer-function -- they should be kept light and fast and all the heavy-lifting should be done in the main-loop. It's good manners to teach yourself the habit from the get-go.
Cons: It's more complicated than just doing it in a timer-function, and if you add a lot of code in your loop() that takes more than 5ms to execute you'll miss out on some led-fading steps -- though the time to fade the led stays the same.