Latest version of my quadcopter controller with an LPC1768 and MPU9250.

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers SerialBuffered.cpp Source File

SerialBuffered.cpp

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