23
23
24
24
// Constructors ////////////////////////////////////////////////////////////////
25
25
26
- USARTClass::USARTClass ( Usart* pUsart, IRQn_Type dwIrq, uint32_t dwId, RingBuffer* pRx_buffer, volatile RingBuffer* pTx_buffer )
26
+ USARTClass::USARTClass ( Usart* pUsart, IRQn_Type dwIrq, uint32_t dwId, RingBuffer* pRx_buffer, RingBuffer* pTx_buffer )
27
27
{
28
28
_rx_buffer = pRx_buffer;
29
29
_tx_buffer = pTx_buffer;
@@ -33,7 +33,6 @@ USARTClass::USARTClass( Usart* pUsart, IRQn_Type dwIrq, uint32_t dwId, RingBuffe
33
33
_dwId=dwId ;
34
34
}
35
35
36
-
37
36
// Public Methods //////////////////////////////////////////////////////////////
38
37
39
38
void USARTClass::begin ( const uint32_t dwBaudRate )
@@ -66,6 +65,10 @@ void USARTClass::begin( const uint32_t dwBaudRate, const uint32_t config )
66
65
// Enable UART interrupt in NVIC
67
66
NVIC_EnableIRQ ( _dwIrq ) ;
68
67
68
+ // make sure both ring buffers are initialized back to empty.
69
+ _rx_buffer->_iHead = _rx_buffer->_iTail = 0 ;
70
+ _tx_buffer->_iHead = _tx_buffer->_iTail = 0 ;
71
+
69
72
// Enable receiver and transmitter
70
73
_pUsart->US_CR = US_CR_RXEN | US_CR_TXEN ;
71
74
}
@@ -91,6 +94,14 @@ int USARTClass::available( void )
91
94
return (uint32_t )(SERIAL_BUFFER_SIZE + _rx_buffer->_iHead - _rx_buffer->_iTail ) % SERIAL_BUFFER_SIZE ;
92
95
}
93
96
97
+ int USARTClass::availableForWrite (void )
98
+ {
99
+ int head = _tx_buffer->_iHead ;
100
+ int tail = _tx_buffer->_iTail ;
101
+ if (head >= tail) return SERIAL_BUFFER_SIZE - 1 - head + tail;
102
+ return tail - head - 1 ;
103
+ }
104
+
94
105
int USARTClass::peek ( void )
95
106
{
96
107
if ( _rx_buffer->_iHead == _rx_buffer->_iTail )
@@ -142,17 +153,20 @@ void USARTClass::IrqHandler( void )
142
153
uint32_t status = _pUsart->US_CSR ;
143
154
144
155
// Did we receive data ?
145
- if ((status & US_CSR_RXRDY) == US_CSR_RXRDY)
146
- _rx_buffer->store_char ( _pUsart->US_RHR ) ;
147
-
156
+ if ((status & US_CSR_RXRDY) == US_CSR_RXRDY)
157
+ {
158
+ _rx_buffer->store_char (_pUsart->US_RHR );
159
+ }
148
160
// Do we need to keep sending data?
149
161
if ((status & US_CSR_TXRDY) == US_CSR_TXRDY)
150
162
{
151
- _pUsart->US_THR = _tx_buffer->_aucBuffer [_tx_buffer->_iTail ];
152
- _tx_buffer->_iTail = (unsigned int )(_tx_buffer->_iTail + 1 ) % SERIAL_BUFFER_SIZE;
153
- if (_tx_buffer->_iTail == _tx_buffer->_iHead ) // if this is true we have no more data to transmit
163
+ if (_tx_buffer->_iTail != _tx_buffer->_iHead ) { // just in case
164
+ _pUsart->US_THR = _tx_buffer->_aucBuffer [_tx_buffer->_iTail ];
165
+ _tx_buffer->_iTail = (unsigned int )(_tx_buffer->_iTail + 1 ) % SERIAL_BUFFER_SIZE;
166
+ }
167
+ else
154
168
{
155
- _pUsart->US_IDR = US_IDR_TXRDY; // mask off transmit interrupt so we don't get it anymore
169
+ _pUsart->US_IDR = US_IDR_TXRDY; // mask off transmit interrupt so we don't get it anymore
156
170
}
157
171
}
158
172
0 commit comments