Software serial, for when you are out of serial pins

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

SoftSerial_tx.cpp

Committer:
Sissors
Date:
2014-04-26
Revision:
0:8edaa7abe724
Child:
1:f8b4b764ace7

File content as of revision 0:8edaa7abe724:

#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;   
}