Patrick WU / 96b8cc1ba38f

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers SerialBuffered.cpp Source File

SerialBuffered.cpp

00001 #include "mbed.h"
00002 #include "SerialBuffered.h"
00003  
00004 //extern Serial loggerSerial;
00005  
00006 SerialBuffered::SerialBuffered( size_t bufferSize, PinName tx, PinName rx ) : Serial(  tx,  rx ) 
00007 {
00008     m_buffSize = 0;
00009     m_contentStart = 0;
00010     m_contentEnd = 0;
00011     m_timeout = 1.0;
00012    
00013     
00014     attach( this, &SerialBuffered::handleInterrupt );
00015     
00016     m_buff = (uint8_t *) malloc( bufferSize );
00017     if( m_buff == NULL )
00018     {
00019         //loggerSerial.printf("SerialBuffered - failed to alloc buffer size %d\r\n", (int) bufferSize );
00020     }
00021     else
00022     {
00023         m_buffSize = bufferSize;
00024     }
00025 }
00026  
00027  
00028 SerialBuffered::~SerialBuffered()
00029 {
00030     if( m_buff )
00031         free( m_buff );
00032 }
00033  
00034 void SerialBuffered::setTimeout( float seconds )
00035 {
00036     m_timeout = seconds;
00037 }
00038     
00039 size_t SerialBuffered::readBytes( uint8_t *bytes, size_t requested )
00040 {
00041     int i = 0;
00042  
00043     for( ; i < requested; )
00044     {
00045         int c = getc();
00046         if( c < 0 )
00047             break;
00048         bytes[i] = c;
00049         i++;
00050     }
00051     
00052     return i;
00053         
00054 }
00055  
00056  
00057 int SerialBuffered::getc()
00058 {
00059     m_timer.reset();
00060     m_timer.start();
00061     while( m_contentStart == m_contentEnd )
00062     {
00063       
00064  
00065         wait_ms( 1 );
00066         if( m_timeout > 0 &&  m_timer.read() > m_timeout )
00067             return EOF;
00068     }
00069  
00070     m_timer.stop();
00071    
00072     uint8_t result = m_buff[m_contentStart++];
00073     m_contentStart =  m_contentStart % m_buffSize;
00074  
00075    
00076     return result;    
00077 }
00078  
00079  
00080 int SerialBuffered::readable()
00081 {
00082     return m_contentStart != m_contentEnd ;
00083 }
00084  
00085 void SerialBuffered::handleInterrupt()
00086 {
00087     
00088     while( Serial::readable())
00089     {
00090         if( m_contentStart == (m_contentEnd +1) % m_buffSize)
00091         {
00092           // loggerSerial.printf("SerialBuffered - buffer overrun, data lost!\r\n" );
00093            Serial::getc();
00094  
00095         }
00096         else
00097         {
00098           
00099             m_buff[ m_contentEnd ++ ] = Serial::getc();
00100             m_contentEnd = m_contentEnd % m_buffSize;
00101             
00102            
00103            
00104         }
00105     }
00106 }
00107  
00108