another clone of servo library
Embed:
(wiki syntax)
Show/hide line numbers
Servo.cpp
00001 00002 00003 /* mbed R/C Servo Library 00004 * 00005 * Copyright (c) 2007-2010 sford, cstyles 00006 * 00007 * Permission is hereby granted, free of charge, to any person obtaining a copy 00008 * of this software and associated documentation files (the "Software"), to deal 00009 * in the Software without restriction, including without limitation the rights 00010 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 00011 * copies of the Software, and to permit persons to whom the Software is 00012 * furnished to do so, subject to the following conditions: 00013 * 00014 * The above copyright notice and this permission notice shall be included in 00015 * all copies or substantial portions of the Software. 00016 * 00017 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 00018 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 00019 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 00020 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 00021 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 00022 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 00023 * THE SOFTWARE. 00024 */ 00025 00026 #include "Servo.h" 00027 #include "mbed.h" 00028 00029 static float clamp(float value, float min, float max) { 00030 if(value < min) { 00031 return min; 00032 } else if(value > max) { 00033 return max; 00034 } else { 00035 return value; 00036 } 00037 } 00038 00039 Servo::Servo(PinName pin) : _pwm(pin) { 00040 calibrate(); 00041 write(0.5); 00042 } 00043 00044 void Servo::write(float percent) { 00045 float offset = _range * 2.0 * (percent - 0.5); 00046 _pwm.pulsewidth(0.0015 + clamp(offset, -_range, _range)); 00047 _p = clamp(percent, 0.0, 1.0); 00048 } 00049 00050 void Servo::position(float degrees) { 00051 float offset = _range * (degrees / _degrees); 00052 _pwm.pulsewidth(0.0015 + clamp(offset, -_range, _range)); 00053 } 00054 00055 void Servo::calibrate(float range, float degrees) { 00056 _range = range; 00057 _degrees = degrees; 00058 } 00059 00060 float Servo::read() { 00061 return _p; 00062 } 00063 00064 Servo& Servo::operator= (float percent) { 00065 write(percent); 00066 return *this; 00067 } 00068 00069 Servo& Servo::operator= (Servo& rhs) { 00070 write(rhs.read()); 00071 return *this; 00072 } 00073 00074 Servo::operator float() { 00075 return read(); 00076 } 00077
Generated on Tue Jul 26 2022 00:15:34 by
1.7.2