Mark Norman / Mbed 2 deprecated Nottingham

Dependencies:   mbed

BlockingSerial.h

Committer:
merlinsystemscorp
Date:
2010-12-14
Revision:
0:191698f11ceb

File content as of revision 0:191698f11ceb:

#ifndef _BLOCKING_SERIAL
#define _BLOCKING_SERIAL

#include "mbed.h"

class BlockingSerial:public SerialHalfDuplex
{
    public:
    
        BlockingSerial(PinName tx, PinName rx, char * name = NULL): SerialHalfDuplex(tx, rx, name)
        {
        }
        
        int putc(int c)
        {
            if (writeable())
            {
                //printf("++++");        // MPN: for some reason this needs to be here??
                return Serial::putc(c);
            }
            
            return   -1;
        }
        
        int getc( int timeout = 1)
        {
            // if infinite timeout or we have a character, call base getc()
            if ( timeout == -1 || readable() )
                return Serial::getc();
    
              // no character yet  
              bool has_data = false;
              // count elapsed time
              Timer timer;
              timer.start();
              // loop until we have data or timeout elapses
              while ( !has_data && timer.read_ms() < timeout )
              {
                // wait a short time
                wait_ms(1);
                // check again
                has_data = readable();
              }
              // do we have anything?
              if ( has_data )
                // yes, read it
                return Serial::getc();
              else
                // no, timed out
                return -1;
       };

};
#endif _BLOCKING_SERIAL