Software serial, for when you are out of serial pins

Dependents:   BufferedSoftSerial neurGAI_Seeed_BLUETOOTH LPC-SD-35 ESP-WROOM-02_test ... more

Revision:
0:8edaa7abe724
Child:
1:f8b4b764ace7
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SoftSerial_tx.cpp	Sat Apr 26 14:46:03 2014 +0000
@@ -0,0 +1,77 @@
+#include "SoftSerial.h"
+
+int SoftSerial::_putc(int c) {
+    while(!writeable());
+    tx_bit = 0;
+    _char = c;
+    tx_handler();
+    return 0;
+    }
+
+int SoftSerial::writeable(void) {
+    if (!tx_en)
+        return false;
+    if (tx_bit == -1)
+        return true;
+    return false;
+}
+
+void SoftSerial::tx_handler(void) {
+    if (get_bit(tx_bit) == -1) {
+        tx_bit = -1;
+        return;
+    }
+    
+    //Flip output
+    int cur_out = tx->read();
+    tx->write(!cur_out);
+         
+    //Calculate when to do it again
+    int count = bit_period;
+    tx_bit++;
+    while(get_bit(tx_bit) == !cur_out) {
+        count+=bit_period;
+        tx_bit++;
+    }
+    
+    timeout.attach_us(this, &SoftSerial::tx_handler, count);
+}
+
+int SoftSerial::get_bit(int bit) {
+    //Start bit is never asked
+    
+    //Data bits
+    if (bit <= _bits )
+        return ((_char >> (bit - 1)) & 0x01);
+    
+    //Parity
+    bool retval;
+    if (bit == _bits + 1) {
+        switch (_parity) {
+            case Forced1:
+                return 1;
+            case Forced0:
+                return 0;
+            case Even:
+                retval = false;
+                for (int i = 0; i<_bits; i++) {
+                    if (((_char >> i) & 0x01) == 1)
+                        retval = !retval;
+                }
+                return retval;
+            case Odd:
+                retval = true;
+                for (int i = 0; i<_bits; i++) {
+                    if (((_char >> i) & 0x01) == 1)
+                        retval = !retval;
+                }
+                return retval;
+        }
+    }
+    
+    //Stop bits:
+    if (bit < 1 + _bits + (bool)_parity + _stop_bits) 
+        return 1;
+    
+    return -1;   
+}
\ No newline at end of file