I need to create a timer that when it is fired, the callback function release a specific semaphore that is blocking another task, how can I make the semaphore already taken, specially because the task will try to take the semaphore first
First, after you create the semaphore, just first do a take (maybe with a 0 block time) to make sure it starts taken as part of your initialization routine.
Then your timer call back just needs to call the semaphore give function. If you want to make a general callback, you could even create it with the semaphore handle stored as the timer ID, so the callback could get the ID to get the handle for the semaphore to give.
i created the semaphore as global, if i did a take as global also, in the timercallback is it even possible to do the give?, I think it will produce a deadlock
Right after the statement to create the semaphore, add the take (In C, you can make the handle a global, but you need some code to actually create the semaphore, so you put the take right after you create it). Note, if you use xSemaphoreCreateBinary to make the semaphore, it starts out as taken, so you don’t need to do the take. That is one reason I said use a 0 timeout, that way if the semaphore was created take, it doesn’t cause the block to happen.
Also note, xSemaphoreGive NEVER blocks, so can’t itself create a deadlock. Just as the take with a 0 block time just makes sure it is in the taken state without the ability to create a deadlock.
You MAY be under the impression here that a semaphore is something like a mutex that tracks ownership or is under other restrictions to be “given.” It’s not. A semaphore can be released by any piece of code once it has been created (of course under the usual restrictions, that is, ISRs must use the …FromISR version of the API call and must not run on a higher pri than MAX_Syscall), and it can be released as many times as one wishes, even if it is already fully released. You may get an error return if you try to do that, but that’s all that happens.
If you look at one of the standard applications of a semaphore usage - an ISR signalling reception of data on the ISR level for a task to do deferred input processing later - you’ll see that the ISR signalling the semaphore never bothers to see what the state of the signal is. It simply submits the signal via a give for the processor task to wait on.