SuperHouse / esp-open-rtos

Open source FreeRTOS-based ESP8266 software framework
BSD 3-Clause "New" or "Revised" License
1.53k stars 491 forks source link

Pwm (Timer FRC1) and printf problem #495

Open Zaltora opened 6 years ago

Zaltora commented 6 years ago

I found a problem with printf and timer. I use a brushless motor. When you use printf, the motor signal is disturbing. The effect is bigger when you print a lot of characters. The motor controller don't like this and can stop to work (motor off). To get around the problem of printf, i use uart_putc and everything work properly. Why printf got a different behavior ?

ourairquality commented 6 years ago

Newlib implements locking for thread safety. Currently this just uses critical regions so disables interrupts which might be causing the problems you see. See ld/program.ld _lock_acquire = vPortEnterCritical; etc Could you try actually a mutex and mapping _lock_acquire etc to FreeRTOS functions using?

Zaltora commented 6 years ago

Sry, don't understand what i need to do. Create my own function ? void _lock_acquire(_lock_t *lock) I will use mutex to protect "printf" function from interupt ?

ourairquality commented 6 years ago

Newlib uses these lock functions for protecting other operations too, such as allocating memory. If these could be defined to use a FreeRTOS mutex then that would mean that interrupts are not being disabled for this and it would not be blocking the timer interrupt. The timer thread runs at a relatively high priority so these should then preempt most other threads even if they are in printf lock-held regions. If you can design your timer handler to not require this same newlib mutex then it will avoid priority inversions that might otherwise cause some delay.

meowthink commented 6 years ago

@Zaltora Please have a try of my repo at https://github.com/meowthink/esp-open-rtos.git Those lock* symbols in newlib are dummies and declared weak, thus an implementation ourselves will replace them.

Zaltora commented 6 years ago

Hi, @meowthink, Thank you. I have test your change (last commit) with current RTOS version and adding #define configUSE_RECURSIVE_MUTEXES 1 to my config project. printf didn't disturb pwm signal ! my motor run fine. Nice implementation. Can't do better with my current knowledge of FreeRTOS. Thank you both of you for yours help.

Zaltora commented 6 years ago

Just a question for optimization: uart_putc is faster i guess ?

meowthink commented 6 years ago

You're welcome, Zaltora. That's just a dirty hack of ourairquaility's idea. I think I'll open a PR later, after I got clear about coding guidelines here. btw uart_putc should be faster imho.

ourairquality commented 6 years ago

Fwiw there was an interesting thread on the newlib list and it was suggested to try sniprintf() and claimed this did not use malloc, also that there are a series of similar functions and there is an iprintf(). Perhaps these would help.