APM:Libraries
Semaphores.cpp
Go to the documentation of this file.
1 /*
2  * This file is free software: you can redistribute it and/or modify it
3  * under the terms of the GNU General Public License as published by the
4  * Free Software Foundation, either version 3 of the License, or
5  * (at your option) any later version.
6  *
7  * This file is distributed in the hope that it will be useful, but
8  * WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10  * See the GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License along
13  * with this program. If not, see <http://www.gnu.org/licenses/>.
14  *
15  * Code by Andrew Tridgell and Siddharth Bharat Purohit
16  */
17 #include <AP_HAL/AP_HAL.h>
18 #include "Semaphores.h"
19 
20 #if CH_CFG_USE_MUTEXES == TRUE
21 
22 extern const AP_HAL::HAL& hal;
23 
24 using namespace ChibiOS;
25 
27 {
28  chMtxUnlock(&_lock);
29  return true;
30 }
31 
32 bool Semaphore::take(uint32_t timeout_ms)
33 {
34  if (timeout_ms == HAL_SEMAPHORE_BLOCK_FOREVER) {
35  chMtxLock(&_lock);
36  return true;
37  }
38  if (take_nonblocking()) {
39  return true;
40  }
41  uint64_t start = AP_HAL::micros64();
42  do {
43  hal.scheduler->delay_microseconds(200);
44  if (take_nonblocking()) {
45  return true;
46  }
47  } while ((AP_HAL::micros64() - start) < timeout_ms*1000);
48  return false;
49 }
50 
52 {
53  return chMtxTryLock(&_lock);
54 }
55 
56 #endif // CH_CFG_USE_MUTEXES
57 
const AP_HAL::HAL & hal
Definition: AC_PID_test.cpp:14
#define HAL_SEMAPHORE_BLOCK_FOREVER
Definition: Semaphores.h:5
uint64_t micros64()
Definition: system.cpp:162
bool take(uint32_t timeout_ms)
Definition: Semaphores.cpp:32
virtual void delay_microseconds(uint16_t us)=0
AP_HAL::Scheduler * scheduler
Definition: HAL.h:114