Hiroshi Yamaguchi / m0-PwmOut

Files at this revision

API Documentation at this revision

Comitter:
yamaguch
Date:
Thu Dec 22 04:29:40 2011 +0000
Commit message:

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Thu Dec 22 04:29:40 2011 +0000
@@ -0,0 +1,64 @@
+#include "mbed.h"
+
+/**
+ * PwmOut for M0
+ */
+class M0PwmOut {
+public:
+    M0PwmOut(PinName pwm, float period = 0.001) : pwm(pwm), period(period), duty(0) {
+        this->pwm = 0;
+    }
+
+    void write(float duty) {
+        if (duty <= 0.0) {
+            this->duty = 0;
+            pwm = 0;
+            ticker.detach();
+        } else if (duty >= 1.0) {
+            this->duty = 1;
+            pwm = 1;
+            ticker.detach();
+        } else {
+            this->duty = duty;
+            ticker.attach(this, &M0PwmOut::onTicker, period);
+        }
+    }
+
+    float read() {
+        return duty;
+    }
+    
+    void operator=(float value) {
+        write(value);
+    }
+
+    operator float() {
+        return read();
+    }
+private:
+    DigitalOut pwm;
+    Ticker ticker;
+    Timeout timeout;
+    float period;
+    float duty;
+
+    void onTicker() {
+        this->pwm = 1;
+        timeout.attach(this, &M0PwmOut::onTimeout, duty * period);
+    }
+
+    void onTimeout() {
+        this->pwm = 0;
+    }
+};
+
+int main () {
+    M0PwmOut leds[] = {LED1, LED2, LED3, LED4};
+
+    for (int i = 0; i < 600; i++) {
+        for (int j = 0; j < 4; j++)
+            leds[j] = ((i + 5 * j) % 31) / 30.0;
+        wait(0.2);
+    }
+    for (int i = 0; i < 4; i++) leds[i] = 0;
+}