forked

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers Timer.cpp Source File

Timer.cpp

00001 /* mbed Microcontroller Library
00002  * Copyright (c) 2006-2013 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 #include "drivers/Timer.h"
00017 #include "hal/ticker_api.h"
00018 #include "hal/us_ticker_api.h"
00019 #include "platform/mbed_critical.h"
00020 
00021 namespace mbed {
00022 
00023 Timer::Timer() : _running(), _start(), _time(), _ticker_data(get_us_ticker_data()) {
00024     reset();
00025 }
00026 
00027 Timer::Timer(const ticker_data_t *data) : _running(), _start(), _time(), _ticker_data(data) {
00028     reset();
00029 }
00030 
00031 void Timer::start() {
00032     core_util_critical_section_enter();
00033     if (!_running) {
00034         _start = ticker_read_us(_ticker_data);
00035         _running = 1;
00036     }
00037     core_util_critical_section_exit();
00038 }
00039 
00040 void Timer::stop() {
00041     core_util_critical_section_enter();
00042     _time += slicetime();
00043     _running = 0;
00044     core_util_critical_section_exit();
00045 }
00046 
00047 int Timer::read_us() {
00048     return read_high_resolution_us();
00049 }
00050 
00051 float Timer::read() {
00052     return (float)read_us() / 1000000.0f;
00053 }
00054 
00055 int Timer::read_ms() {
00056     return read_high_resolution_us() / 1000;
00057 }
00058 
00059 us_timestamp_t Timer::read_high_resolution_us() {
00060     core_util_critical_section_enter();
00061     us_timestamp_t time = _time + slicetime();
00062     core_util_critical_section_exit();
00063     return time;
00064 }
00065 
00066 us_timestamp_t Timer::slicetime() {
00067     us_timestamp_t ret = 0;
00068     core_util_critical_section_enter();
00069     if (_running) {
00070         ret = ticker_read_us(_ticker_data) - _start;
00071     }
00072     core_util_critical_section_exit();
00073     return ret;
00074 }
00075 
00076 void Timer::reset() {
00077     core_util_critical_section_enter();
00078     _start = ticker_read_us(_ticker_data);
00079     _time = 0;
00080     core_util_critical_section_exit();
00081 }
00082 
00083 Timer::operator float() {
00084     return read();
00085 }
00086 
00087 } // namespace mbed