Ben Katz / mbed-dev_spine

Dependents:   SPIne CH_Communicatuin_Test CH_Communicatuin_Test2 MCP_SPIne ... more

Fork of mbed-dev-f303 by Ben Katz

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers DeepSleepLock.h Source File

DeepSleepLock.h

00001 /* mbed Microcontroller Library
00002  * Copyright (c) 2017 ARM Limited
00003  *
00004  * Licensed under the Apache License, Version 2.0 (the "License");
00005  * you may not use this file except in compliance with the License.
00006  * You may obtain a copy of the License at
00007  *
00008  *     http://www.apache.org/licenses/LICENSE-2.0
00009  *
00010  * Unless required by applicable law or agreed to in writing, software
00011  * distributed under the License is distributed on an "AS IS" BASIS,
00012  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013  * See the License for the specific language governing permissions and
00014  * limitations under the License.
00015  */
00016 #ifndef MBED_DEEPSLEEPLOCK_H
00017 #define MBED_DEEPSLEEPLOCK_H
00018 
00019 #include <limits.h>
00020 #include "platform/mbed_sleep.h"
00021 #include "platform/mbed_critical.h"
00022 
00023 namespace mbed {
00024 
00025 
00026 /** RAII object for disabling, then restoring the deep sleep mode
00027   * Usage:
00028   * @code
00029   *
00030   * void f() {
00031   *     // some code here
00032   *     {
00033   *         DeepSleepLock lock;
00034   *         // Code in this block will run with the deep sleep mode locked
00035   *     }
00036   *     // deep sleep mode will be restored to their previous state
00037   * }
00038   * @endcode
00039   */
00040 class DeepSleepLock {
00041 private:
00042     uint16_t _lock_count;
00043 
00044 public:
00045     DeepSleepLock(): _lock_count(1)
00046     {
00047         sleep_manager_lock_deep_sleep();
00048     }
00049 
00050     ~DeepSleepLock()
00051     {
00052         if (_lock_count) {
00053             sleep_manager_unlock_deep_sleep();
00054         }
00055     }
00056 
00057     /** Mark the start of a locked deep sleep section
00058      */
00059     void lock()
00060     {
00061         uint16_t count = core_util_atomic_incr_u16(&_lock_count, 1);
00062         if (1 == count) {
00063             sleep_manager_lock_deep_sleep();
00064         }
00065         if (0 == count) {
00066             error("DeepSleepLock overflow (> USHRT_MAX)");
00067         }
00068     }
00069 
00070     /** Mark the end of a locked deep sleep section
00071      */
00072     void unlock()
00073     {
00074         uint16_t count = core_util_atomic_decr_u16(&_lock_count, 1);
00075         if (count == 0) {
00076             sleep_manager_unlock_deep_sleep();
00077         }
00078         if (count == USHRT_MAX) {
00079             core_util_critical_section_exit();
00080             error("DeepSleepLock underflow (< 0)");
00081         }
00082     }
00083 };
00084 
00085 }
00086 
00087 #endif