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

Dependencies:   RingBuffer

mySerial.h

Committer:
AkinoriHashimoto
Date:
2016-11-15
Revision:
3:3658415b257b
Parent:
0:fa077fb53f44

File content as of revision 3:3658415b257b:

/**     Serial control class with using RTOS.
 *  You can use printf(), rxIrq();
 *
 */
/**
 * @code
#include "mbed.h"
#include "mySerial.h"

DigitalOut led[]= {LED1, LED2, LED3, LED4};
mySerial pc(USBTX, USBRX);

void rcvIrq(char id)
{
    led[0]= !led[0];
    if('2'<=id && id<='4') {   // LED2 ~ 4
        id -= '1';
        led[id]= !led[id];
    }
    return;
}

int main()
{
    pc.init();
    pc.setAttachRx(rcvIrq);
    while(true) {
        pc.printf("@");
        pc.sendLine(pc.get());
        wait(10);
    }
}
// EOF
 * @endcode
*/

#pragma once

#include "mbed.h"
#include <string>
#include "RingBuffer.h"

/**     Serial communicate class with Tx & Rx ringbuf.
 *
 */
class mySerial : public Stream
{
public:
    /** Create Serial port to mySerial.
     *  @param TX, RX;              Serial port.
     */
    mySerial(PinName tx, PinName rx);

    /** init
     *  @param baud-rate;           Baud rate (bps). 9600, 38,400, 115,200, 230,400
     *  @param bit, parity, stop;   Default: 1Stopbit, NoneParity, 1StopBit.
     *                              -- parity select; N(None), O(Odd), E(Even).
     *  @param CRLN;                true -> CR&LN (\r\n), false -> CR only (\r).
     */
    void init(int baudrate= 115200, int bit=8, int parity=SerialBase::None, int stop=1, bool CRLN=true);

    /** add rxFuncPtr to AttachRxIrq.
     *  @param (*fptr)(char chr)
     */
    void setAttachRx(void (*fptr)(char));
    
    /**  check Buffer
     *  @return bool; true->readable.
    */
    bool readable();
    
    /** get string in Rx-RingBuffer.
     *  return string; all chars in ringBuffer.
    */
    string get();
    
    /** get string 1 line in Rx-RingBuffer.
     * 1 line is string until CR (or CR&LN <- cf.init()).
     *  @return string; 1 line chars.
    */
    string getLine();
    
    /** send Line with add CR lineEnd.
     *  @param str; strings
     *  @param addCR; true -> add CR str's end.
    */
    void sendLine(string str, bool addCR=true);

private:
    RawSerial serial;
    string CR;
    RingBuffer ringBufRx;
    RingBuffer ringBufTx;

    // RxIrq function pointer as out of class.
    void (*fptrRxIrq)(char);

    // copy buf of rx to private string.
    void _read();       // copy buf of rx to private string.
    void _readIrq();    // copy buf of rx to private string.

    // virtual func for printf() in Stream-class.
    virtual int _putc(int val);
    virtual int _getc();
    void putcIrq();
};

// EOF