-->
Page 1 of 1

EspArduino - Ticker for pwm fading?

PostPosted: Fri Jan 08, 2016 9:45 pm
by spy king
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?

Re: EspArduino - Ticker for pwm fading?

PostPosted: Sat Jan 09, 2016 5:40 pm
by eduperez
I would try to do the fading inside the loop() changing the brightness one step on each iteration.

Re: EspArduino - Ticker for pwm fading?

PostPosted: Sat Jan 09, 2016 6:14 pm
by WereCatf
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.