experimental fork to solve timing issues

Dependents:   writable_gatt

Fork of TxIR by Ali Saidi

Revision:
2:cc8371213c85
Parent:
0:7d2088337345
Child:
3:bc64c2d5bc26
--- a/TxIR.cpp	Sun Dec 12 05:40:01 2010 +0000
+++ b/TxIR.cpp	Thu Jun 26 14:18:26 2014 +0000
@@ -26,53 +26,76 @@
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
- 
+ #include "mbed.h"
  #include "TxIR.hpp"
  
+ bool shouldFlip;
+ 
+ Serial pc(USBTX, USBRX);
+ 
+ Timer timer;
 
 void
 TxIR::doAction()
 {
     if (pos >= len) {
-        delete [] data;
-        _inUse = false;
-        txPin.write(0);
         return;
     }
-        
-    delay.attach_us(this, &TxIR::doAction, data[pos++]);
-    if (high)
-        txPin.write(0);
-    else
-        txPin.write(0.5);
-   high = !high;
+    pc.printf("doAction, pos: %i\n", pos);
+    shouldFlip = true;
+    delay.attach_us(this, &TxIR::doAction, data[pos++] * 200);
 }
 
 bool
-TxIR::txSeq(unsigned freq, unsigned _len, const unsigned *_data) 
+TxIR::txSeq(unsigned freq, unsigned len, const unsigned *data) 
 {
+    
     // @todo a lock or semaphore should be used here
     if (inUse())
         return false;
     _inUse = true;
     
     // keep a copy of the data, so it can't change
-    len = _len;
-    data = new unsigned[len];
-    memcpy(data, _data, len * sizeof(unsigned));
     pos = 0;
-    
     // setup the PWM
     txPin.write(0.0);
     txPin.period_us(freq);
     
     // Get the interrupt ready
     delay.detach();
-    high = true;
-    delay.attach_us(this, &TxIR::doAction, data[pos++]);
+    
+    int times[len];
+    for(int i=0;i<len;i++){
+        times[i] = 0;    
+    }
     
-    // Begin
+    int bit = 1;
+    pc.printf("S\n");
     txPin.write(0.5);
-    
+    timer.start();
+    int time = timer.read_us();
+    int old_time = time;
+    int dt = 0;
+    while(pos < len)  {
+        old_time = time;
+        time = timer.read_us();
+        dt += time - old_time;   
+        while(dt > data[pos]) {
+            dt -= data[pos];
+            bit = !bit;
+            txPin.write(0.5 * bit);
+            times[pos] = dt;
+            pos++;
+        }
+    }
+    timer.stop();
+    pc.printf("Success, wrote %i/%i\n", pos, len);
+    pc.printf("Miss timings: [%i", times[0]);
+    for(int i=1;i<len;i++){
+        pc.printf(", %i", times[i]);
+    }
+    txPin.write(0);
+    _inUse = false;
+    delay.detach();
     return true;
 }