first lib

Dependents:   17robo_fuzi 17robo_tokyo_kaede

Files at this revision

API Documentation at this revision

Comitter:
echo_piyo
Date:
Sun Sep 24 06:19:24 2017 +0000
Commit message:
(??)???????????????

Changed in this revision

servo.cpp Show annotated file Show diff for this revision Revisions of this file
servo.h Show annotated file Show diff for this revision Revisions of this file
diff -r 000000000000 -r 41758331f8d1 servo.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servo.cpp	Sun Sep 24 06:19:24 2017 +0000
@@ -0,0 +1,65 @@
+
+#include "servo.h"
+#include "mbed.h"
+
+static float clamp(float value, float min, float max) {
+    if(value < min) {
+        return min;
+    } else if(value > max) {
+        return max;
+    } else {
+        return value;
+    }
+}
+
+void Servo::setRange(float maxrange, float minrange){
+    maxRange = maxrange;
+    minRange = minrange;    
+}
+
+void Servo::setMax(){
+    write(maxRange);
+}
+
+void Servo::setMin(){
+    write(minRange);
+}
+
+Servo::Servo(PinName pin) : _pwm(pin) {
+    calibrate();
+    write(0.5);
+}
+
+void Servo::write(float percent) {
+    float offset = _range * 2.0 * (percent - 0.5);
+    _pwm.pulsewidth(0.0015 + clamp(offset, -_range, _range));
+    _p = clamp(percent, 0.0, 1.0);
+}
+
+void Servo::position(float degrees) {
+    float offset = _range * (degrees / _degrees);
+    _pwm.pulsewidth(0.0015 + clamp(offset, -_range, _range));
+}
+
+void Servo::calibrate(float range, float degrees) {
+    _range = range;
+    _degrees = degrees;
+}
+
+float Servo::read() {
+    return _p;
+}
+
+Servo& Servo::operator= (float percent) { 
+    write(percent);
+    return *this;
+}
+
+Servo& Servo::operator= (Servo& rhs) {
+    write(rhs.read());
+    return *this;
+}
+
+Servo::operator float() {
+    return read();
+}
diff -r 000000000000 -r 41758331f8d1 servo.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/servo.h	Sun Sep 24 06:19:24 2017 +0000
@@ -0,0 +1,43 @@
+/*
+
+
+*/
+
+#ifndef MBED_SERVO_H
+#define MBED_SERVO_H
+#include "mbed.h"
+
+class Servo {
+
+public:
+    Servo(PinName pin);
+    void write(float percent);
+    void setRange(float maxrange, float minrange);
+    void setMax();
+    void setMin();
+    float read();
+    void position(float degrees);
+    
+    /**  Allows calibration of the range and angles for a particular servo
+     *
+     * @param range Pulsewidth range from center (1.5ms) to maximum/minimum position in seconds
+     * @param degrees Angle from centre to maximum/minimum position in degrees
+     */
+    //range : 1.5msを中心とした、最大最小までのパルス幅の指定
+    //degrees : 中心から最大最小までの角度の指定
+    void calibrate(float range = 0.0005, float degrees = 45.0); 
+        
+    /**  Shorthand for the write and read functions */
+    Servo& operator= (float percent);
+    Servo& operator= (Servo& rhs);
+    operator float();
+
+protected:
+    PwmOut _pwm;
+    float _range;
+    float _degrees;
+    float _p;
+    float maxRange, minRange;
+};
+
+#endif