ben winstone
/
ucam
As of Monday morning, so this is the code we showed at Uncraftivism.
Embed:
(wiki syntax)
Show/hide line numbers
SerialBuffered.cpp
00001 #include "stdafx.h" 00002 #include "mbed.h" 00003 #include "SerialBuffered.h" 00004 00005 00006 extern Logger pcSerial; 00007 00008 SerialBuffered::SerialBuffered( size_t bufferSize, PinName tx, PinName rx ) : Serial( tx, rx ) 00009 { 00010 m_buffSize = 0; 00011 m_contentStart = 0; 00012 m_contentEnd = 0; 00013 m_timeout = 1.0; 00014 00015 00016 attach( this, &SerialBuffered::handleInterrupt ); 00017 00018 m_buff = (uint8_t *) malloc( bufferSize ); 00019 if( m_buff == NULL ) 00020 { 00021 pcSerial.printf("SerialBuffered - failed to alloc buffer size %d\r\n", (int) bufferSize ); 00022 } 00023 else 00024 { 00025 m_buffSize = bufferSize; 00026 } 00027 } 00028 00029 00030 SerialBuffered::~SerialBuffered() 00031 { 00032 if( m_buff ) 00033 free( m_buff ); 00034 } 00035 00036 void SerialBuffered::setTimeout( float seconds ) 00037 { 00038 m_timeout = seconds; 00039 } 00040 00041 size_t SerialBuffered::readBytes( uint8_t *bytes, size_t requested ) 00042 { 00043 int i = 0; 00044 00045 for( ; i < requested; ) 00046 { 00047 int c = getc(); 00048 if( c < 0 ) 00049 break; 00050 bytes[i] = c; 00051 i++; 00052 } 00053 00054 return i; 00055 00056 } 00057 00058 00059 int SerialBuffered::getc() 00060 { 00061 m_timer.reset(); 00062 m_timer.start(); 00063 00064 #ifdef ON_DESKTOP 00065 handleInterrupt(); 00066 #endif 00067 00068 while( m_contentStart == m_contentEnd ) 00069 { 00070 00071 wait_ms( 1 ); 00072 if( m_timeout > 0 && m_timer.read() > m_timeout ) 00073 { 00074 pcSerial.printf("SerialBuffered - timeout\r\n"); 00075 00076 return EOF; 00077 } 00078 00079 #ifdef ON_DESKTOP 00080 handleInterrupt(); 00081 #endif 00082 } 00083 00084 m_timer.stop(); 00085 00086 uint8_t result = m_buff[m_contentStart++]; 00087 00088 m_contentStart = m_contentStart % m_buffSize; 00089 00090 00091 return result; 00092 } 00093 00094 00095 int SerialBuffered::readable() 00096 { 00097 #ifdef ON_DESKTOP 00098 handleInterrupt(); 00099 #endif 00100 00101 return m_contentStart != m_contentEnd ; 00102 } 00103 00104 void SerialBuffered::handleInterrupt() 00105 { 00106 00107 while( Serial::readable()) 00108 { 00109 if( m_contentStart == (m_contentEnd +1) % m_buffSize) 00110 { 00111 pcSerial.printf("SerialBuffered - buffer overrun, data lost!\r\n" ); 00112 Serial::getc(); 00113 00114 } 00115 else 00116 { 00117 00118 m_buff[ m_contentEnd ++ ] = Serial::getc(); 00119 00120 m_contentEnd = m_contentEnd % m_buffSize; 00121 00122 00123 00124 } 00125 } 00126 } 00127
Generated on Wed Jul 27 2022 03:18:56 by 1.7.2