Software serial, for when you are out of serial pins

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

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers SoftSerial_tx.cpp Source File

SoftSerial_tx.cpp

00001 #include "SoftSerial.h"
00002 
00003 int SoftSerial::_putc(int c)
00004 {
00005     while(!writeable());
00006     prepare_tx(c);
00007     tx_bit = 0;
00008     txticker.prime();
00009     tx_handler();
00010     return 0;
00011 }
00012 
00013 void SoftSerial::send_break(void) {
00014     while(!writeable());
00015     tx_bit = 0;         //Just to make sure it appears as non-writable to other threads/IRQs
00016     tx->write(0);
00017     wait_us((bit_period * _total_bits * 3) / 2);
00018     tx->write(1);
00019     tx_bit = -1;
00020 }
00021 
00022 int SoftSerial::writeable(void)
00023 {
00024     if (!tx_en)
00025         return false;
00026     if (tx_bit == -1)
00027         return true;
00028     return false;
00029 }
00030 
00031 void SoftSerial::tx_handler(void)
00032 {
00033     if (tx_bit == _total_bits) {
00034         tx_bit = -1;
00035         fpointer[TxIrq].call();
00036         return;
00037     }
00038 
00039     //Flip output
00040     int cur_out = tx->read();
00041     tx->write(!cur_out);
00042 
00043     //Calculate when to do it again
00044     int count = bit_period;
00045     tx_bit++;
00046     while(((_char >> tx_bit) & 0x01) == !cur_out) {
00047         count+=bit_period;
00048         tx_bit++;
00049     }
00050 
00051     txticker.setNext(count);
00052 }
00053 
00054 void SoftSerial::prepare_tx(int c)
00055 {
00056     _char = c << 1;
00057 
00058     bool parity;
00059     switch (_parity) {
00060         case Forced1:
00061             _char |= 1 << (_bits + 1);
00062         case Even:
00063             parity = false;
00064             for (int i = 0; i<_bits; i++) {
00065                 if (((_char >> i) & 0x01) == 1)
00066                     parity = !parity;
00067             }
00068             _char |= parity << (_bits + 1);
00069         case Odd:
00070             parity = true;
00071             for (int i = 0; i<_bits; i++) {
00072                 if (((_char >> i) & 0x01) == 1)
00073                     parity = !parity;
00074             }
00075             _char |= parity << (_bits + 1);
00076     }
00077     
00078     _char |= 0xFFFF << (1 + _bits + (bool)_parity);
00079     _char &= ~(1<<_total_bits);
00080 }