Pranav Thakur / Mbed 2 deprecated daplink-validation

Dependencies:   mbed

Fork of daplink-validation by Russ Butler

Revision:
2:204ef796ee06
Parent:
1:db2a55107c7e
Child:
3:ffa3bbc3725f
--- a/main.cpp	Fri Sep 11 14:50:00 2015 +0000
+++ b/main.cpp	Sun Sep 13 01:52:37 2015 +0000
@@ -3,6 +3,53 @@
 
 Serial pc(USBTX, USBRX);
 
+class ByteBuffer
+{
+private:
+    uint32_t head;
+    uint32_t tail;
+    const size_t size;
+    uint8_t* buffer;
+public:
+    ByteBuffer(size_t buffer_size): size(buffer_size) {
+        head = 0;
+        tail = 0;
+        buffer = new uint8_t[buffer_size];
+    }
+
+    ~ByteBuffer() {
+        delete[] buffer;
+    }
+
+    bool empty() {
+        return head == tail;
+    }
+
+    bool full() {
+        return (head + 1) % size == tail;
+    }
+
+    void enqueue(uint8_t data) {
+        if (full()) {
+            error("Queue full\n");
+        }
+        buffer[tail] = data;
+        tail++;
+
+    }
+
+    uint8_t dequeue() {
+        uint8_t data;
+        if (empty()) {
+            error("Queue empty\n");
+        }
+        data = buffer[head];
+        head++;
+        return data;
+    }
+
+};
+
 int main()
 {
     uint32_t baud;
@@ -10,16 +57,23 @@
     uint32_t index;
     uint32_t val;
     uint8_t str[64];
-
+    ByteBuffer buf(512);
     count = 0;
     index = 0;
 
     pc.baud(115200);
     pc.printf("{init}");
-    while(1) {
-        while (1) {
+    while (1) {
+        
+        // Enqueue data as it arrives
+        if (pc.readable()) {
             val = pc.getc();
-
+            buf.enqueue(val);
+        }
+        
+        // Process and send data
+        if (pc.writeable() && !buf.empty()) {
+            val = buf.dequeue();
             // Check for overflow. Leave space for
             // a null terminating character
             if (index >= sizeof(str) - 1) {
@@ -48,7 +102,9 @@
             if (count == 1) {
                 wait(0.01f);
                 pc.baud(baud);
-                wait(0.01f);
+                // Make sure pc has enough time
+                // LCP11u35 requires ~0.1us while K20D requires ~0.01us
+                wait(0.1f);
                 pc.printf("{change}");
                 count = 0;
             }