Serial Communicate Control Class. This has printf() and Tx & Rx buffer with (RxIRQ) RingBuffer, andmore can add user rxFunc to RxIrq.

Dependencies:   RingBuffer

mySerial.cpp

Committer:
AkinoriHashimoto
Date:
2016-11-15
Revision:
3:3658415b257b
Parent:
2:d234f6f65fb9

File content as of revision 3:3658415b257b:

#include "mySerial.h"

mySerial::mySerial(PinName TX, PinName RX)
    : serial(TX, RX)
{
}
void mySerial::init(int baudrate, int bit, int parity, int stop, bool CRLN)
{
    serial.baud(baudrate);

    // 力技
    if      (parity == SerialBase::Odd)
        serial.format(bit, SerialBase::Odd,  stop);
    else if (parity == SerialBase::Even)
        serial.format(bit, SerialBase::Even, stop);     // 8bit, NonParity, 1stopbit
    else// if (parity == SerialBase::None)
        serial.format(bit, SerialBase::None, stop);     // 8bit, NonParity, 1stopbit

    // attach rxIrq. because, rx buf of serial equals to 16 Bytes.
    this->serial.attach(this, &mySerial::_readIrq, Serial::RxIrq);
    // Tx Buf empty Interrupt.
    this->serial.attach(this, &mySerial::putcIrq, Serial::TxIrq);

    CR= '\r';
    if(CRLN)
        CR= "\r\n";
    return;
}

void mySerial::setAttachRx(void (*fptr)(char))
{
    // Serial.attachから呼ばれる_readIrq()内から、fptrをCall.
    fptrRxIrq= fptr;
    return;
}

bool mySerial::readable()
{
    return serial.readable() || !ringBufRx.empty();
}

string mySerial::get() // public:
{
    _read();
    if(ringBufRx.empty())
        return "";
    return ringBufRx.get();
}

string mySerial::getLine()
{
    _read();
    // RingBuf is empty of doesm't find CR.
    if(ringBufRx.empty() || !ringBufRx.chkCR())
        return "";

    return ringBufRx.getLine();
}

void mySerial::sendLine(string str, bool addCR)
{
    if(addCR)
        str += "\r\n";
    this->printf(str.c_str());   // _putc()が呼ばれるはず
    return;
}

int mySerial::_putc(int val)     // for printf()
{
    ringBufTx.set(val);
//    serial.putc(val);
    putcIrq();
    return val;
}

int mySerial::_getc()       // for "Stream"
{
    return ringBufRx.getc();
//    return -1;//mySerial.getc();
}

void mySerial::putcIrq(void)
{
    if(!serial.writeable() || ringBufTx.empty())
        return;
    
    serial.putc(ringBufTx.getc());
    return;
}

// Internal READ()
void mySerial::_readIrq(void)
{
    if(!serial.readable())
        return;

    char chr= serial.getc();
    ringBufRx.set(chr);

    if(this->fptrRxIrq == NULL)
        return;
        
    fptrRxIrq(chr);
    return;
}
void mySerial::_read()
{
    // Bufferを吸い尽くす
    while(serial.readable())
        ringBufRx.set((char)serial.getc());
    return;         // Bufferになくなった
}

// EOF