Skip to content

Commit 22cbcd5

Browse files
peterhinchdpgeorge
authored andcommitted
stmhal: Properly handle RTS/CTS flow control for buf/unbuf transfers.
Fixes issues adafruit#1912 and adafruit#1913. UART documentation is also updated.
1 parent 3177ef5 commit 22cbcd5

2 files changed

Lines changed: 122 additions & 23 deletions

File tree

docs/library/pyb.UART.rst

Lines changed: 81 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,8 @@ using the standard stream methods::
4040

4141
To check if there is anything to be read, use::
4242

43-
uart.any() # returns True if any characters waiting
43+
uart.any() # returns the number of characters waiting
44+
4445

4546
*Note:* The stream functions ``read``, ``write``, etc. are new in MicroPython v1.3.4.
4647
Earlier versions use ``uart.send`` and ``uart.recv``.
@@ -57,7 +58,7 @@ Constructors
5758
initialised (it has the settings from the last initialisation of
5859
the bus, if any). If extra arguments are given, the bus is initialised.
5960
See ``init`` for parameters of initialisation.
60-
61+
6162
The physical pins of the UART busses are:
6263

6364
- ``UART(4)`` is on ``XA``: ``(TX, RX) = (X1, X2) = (PA0, PA1)``
@@ -66,20 +67,24 @@ Constructors
6667
- ``UART(3)`` is on ``YB``: ``(TX, RX) = (Y9, Y10) = (PB10, PB11)``
6768
- ``UART(2)`` is on: ``(TX, RX) = (X3, X4) = (PA2, PA3)``
6869

70+
The Pyboard Lite supports UART(1), UART(2) and UART(6) only. Pins are as above except:
71+
72+
- ``UART(2)`` is on: ``(TX, RX) = (X1, X2) = (PA2, PA3)``
73+
6974
Methods
7075
-------
7176

7277
.. only:: port_pyboard
7378

74-
.. method:: uart.init(baudrate, bits=8, parity=None, stop=1, \*, timeout=1000, flow=None, timeout_char=0, read_buf_len=64)
79+
.. method:: uart.init(baudrate, bits=8, parity=None, stop=1, \*, timeout=1000, flow=0, timeout_char=0, read_buf_len=64)
7580

7681
Initialise the UART bus with the given parameters:
7782

7883
- ``baudrate`` is the clock rate.
7984
- ``bits`` is the number of bits per character, 7, 8 or 9.
8085
- ``parity`` is the parity, ``None``, 0 (even) or 1 (odd).
8186
- ``stop`` is the number of stop bits, 1 or 2.
82-
- ``flow`` sets the flow control type. Can be None, ``UART.RTS``, ``UART.CTS``
87+
- ``flow`` sets the flow control type. Can be 0, ``UART.RTS``, ``UART.CTS``
8388
or ``UART.RTS | UART.CTS``.
8489
- ``timeout`` is the timeout in milliseconds to wait for the first character.
8590
- ``timeout_char`` is the timeout in milliseconds to wait between characters.
@@ -103,16 +108,18 @@ Methods
103108

104109
.. method:: uart.any()
105110

106-
Returns the number of characters waiting (may be 0).
111+
Returns the number of bytes waiting (may be 0).
107112

108113
.. method:: uart.writechar(char)
109114

110115
Write a single character on the bus. ``char`` is an integer to write.
111-
Return value: ``None``.
116+
Return value: ``None``. See note below if CTS flow control is used.
112117

113118
.. method:: uart.read([nbytes])
114119

115120
Read characters. If ``nbytes`` is specified then read at most that many bytes.
121+
If ``nbytes`` are available in the buffer, returns immediately, otherwise returns
122+
when sufficient characters arrive or the timeout elapses.
116123

117124
.. only:: port_pyboard
118125

@@ -124,9 +131,9 @@ Methods
124131

125132
.. method:: uart.readall()
126133

127-
Read as much data as possible.
134+
Read as much data as possible. Returns after the timeout has elapsed.
128135

129-
Return value: a bytes object or ``None`` on timeout.
136+
Return value: a bytes object or ``None`` if timeout prevents any data being read.
130137

131138
.. method:: uart.readchar()
132139

@@ -144,9 +151,11 @@ Methods
144151

145152
.. method:: uart.readline()
146153

147-
Read a line, ending in a newline character.
154+
Read a line, ending in a newline character. If such a line exists, return is
155+
immediate. If the timeout elapses, all available data is returned regardless
156+
of whether a newline exists.
148157

149-
Return value: the line read or ``None`` on timeout.
158+
Return value: the line read or ``None`` on timeout if no data is available.
150159

151160
.. method:: uart.write(buf)
152161

@@ -157,7 +166,8 @@ Methods
157166
bytes are used for each character (little endian), and ``buf`` must contain
158167
an even number of bytes.
159168

160-
Return value: number of bytes written or ``None`` on timeout.
169+
Return value: number of bytes written. If a timeout occurs and no bytes
170+
were written returns ``None``.
161171

162172
.. method:: uart.sendbreak()
163173

@@ -173,4 +183,63 @@ Constants
173183
.. data:: UART.RTS
174184
.. data:: UART.CTS
175185

176-
to select the flow control type
186+
to select the flow control type.
187+
188+
Flow Control
189+
------------
190+
191+
.. only:: port_pyboard
192+
193+
On Pyboards V1 and V1.1 ``UART(2)`` and ``UART(3)`` support RTS/CTS hardware flow control
194+
using the following pins:
195+
196+
- ``UART(2)`` is on: ``(TX, RX, nRTS, nCTS) = (X3, X4, X2, X1) = (PA2, PA3, PA1, PA0)``
197+
- ``UART(3)`` is on :``(TX, RX, nRTS, nCTS) = (Y9, Y10, Y7, Y6) = (PB10, PB11, PB14, PB13)``
198+
199+
On the Pyboard Lite only ``UART(2)`` supports flow control on these pins:
200+
201+
``(TX, RX, nRTS, nCTS) = (X1, X2, X4, X3) = (PA2, PA3, PA1, PA0)``
202+
203+
In the following paragraphs the term "target" refers to the device connected to
204+
the UART.
205+
206+
When the UART's ``init()`` method is called with ``flow`` set to one or both of
207+
``UART.RTS`` and ``UART.CTS`` the relevant flow control pins are configured.
208+
``nRTS`` is an active low output, ``nCTS`` is an active low input with pullup
209+
enabled. To achieve flow control the Pyboard's ``nCTS`` signal should be connected
210+
to the target's ``nRTS`` and the Pyboard's ``nRTS`` to the target's ``nCTS``.
211+
212+
CTS: target controls Pyboard transmitter
213+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
214+
215+
If CTS flow control is enabled the write behaviour is as follows:
216+
217+
If the Pyboard's ``uart.write(buf)`` method is called, transmission will stall for
218+
any periods when ``nCTS`` is ``False``. This will result in a timeout if the entire
219+
buffer was not transmitted in the timeout period. The method returns the number of
220+
bytes written, enabling the user to write the remainder of the data if required. In
221+
the event of a timeout, a character will remain in the UART pending ``nCTS``. The
222+
number of bytes composing this character will be included in the return value.
223+
224+
If ``uart.writechar()`` is called when ``nCTS`` is ``False`` the method will time
225+
out unless the target asserts ``nCTS`` in time. If it times out ``OSError 116``
226+
will be raised. The character will be transmitted as soon as the target asserts ``nCTS``.
227+
228+
RTS: Pyboard controls target's transmitter
229+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
230+
231+
If RTS flow control is enabled, behaviour is as follows:
232+
233+
If buffered input is used (``read_buf_len`` > 0), incoming characters are buffered.
234+
If the buffer becomes full, the next character to arrive will cause ``nRTS`` to go
235+
``False``: the target should cease transmission. ``nRTS`` will go ``True`` when
236+
characters are read from the buffer.
237+
238+
Note that the ``any()`` method returns the number of bytes in the buffer. Assume a
239+
buffer length of ``N`` bytes. If the buffer becomes full, and another character arrives,
240+
``nRTS`` will be set False, and ``any()`` will return the count ``N``. When
241+
characters are read the additional character will be placed in the buffer and will
242+
be included in the result of a subsequent ``any()`` call.
243+
244+
If buffered input is not used (``read_buf_len`` == 0) the arrival of a character will
245+
cause ``nRTS`` to go ``False`` until the character is read.

stmhal/uart.c

Lines changed: 41 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,10 @@ int uart_rx_char(pyb_uart_obj_t *self) {
320320
data = self->read_buf[self->read_buf_tail];
321321
}
322322
self->read_buf_tail = (self->read_buf_tail + 1) % self->read_buf_len;
323+
if (__HAL_UART_GET_FLAG(&self->uart, UART_FLAG_RXNE) != RESET) {
324+
// UART was stalled by flow ctrl: re-enable IRQ now we have room in buffer
325+
__HAL_UART_ENABLE_IT(&self->uart, UART_IT_RXNE);
326+
}
323327
return data;
324328
} else {
325329
// no buffering
@@ -347,6 +351,11 @@ STATIC bool uart_tx_wait(pyb_uart_obj_t *self, uint32_t timeout) {
347351
}
348352

349353
STATIC HAL_StatusTypeDef uart_tx_data(pyb_uart_obj_t *self, uint8_t *data, uint16_t len) {
354+
if (self->uart.Init.HwFlowCtl & UART_HWCONTROL_CTS) {
355+
// CTS can hold off transmission for an arbitrarily long time. Apply
356+
// the overall timeout rather than the character timeout.
357+
return HAL_UART_Transmit(&self->uart, data, len, self->timeout);
358+
}
350359
// The timeout specified here is for waiting for the TX data register to
351360
// become empty (ie between chars), as well as for the final char to be
352361
// completely transferred. The default value for timeout_char is long
@@ -385,25 +394,25 @@ void uart_irq_handler(mp_uint_t uart_id) {
385394
}
386395

387396
if (__HAL_UART_GET_FLAG(&self->uart, UART_FLAG_RXNE) != RESET) {
388-
#if defined(MCU_SERIES_F7)
389-
int data = self->uart.Instance->RDR; // clears UART_FLAG_RXNE
390-
#else
391-
int data = self->uart.Instance->DR; // clears UART_FLAG_RXNE
392-
#endif
393-
data &= self->char_mask;
394397
if (self->read_buf_len != 0) {
395398
uint16_t next_head = (self->read_buf_head + 1) % self->read_buf_len;
396399
if (next_head != self->read_buf_tail) {
397-
// only store data if room in buf
400+
// only read data if room in buf
401+
#if defined(MCU_SERIES_F7)
402+
int data = self->uart.Instance->RDR; // clears UART_FLAG_RXNE
403+
#else
404+
int data = self->uart.Instance->DR; // clears UART_FLAG_RXNE
405+
#endif
406+
data &= self->char_mask;
398407
if (self->char_width == CHAR_WIDTH_9BIT) {
399408
((uint16_t*)self->read_buf)[self->read_buf_head] = data;
400409
} else {
401410
self->read_buf[self->read_buf_head] = data;
402411
}
403412
self->read_buf_head = next_head;
413+
} else { // No room: leave char in buf, disable interrupt
414+
__HAL_UART_DISABLE_IT(&self->uart, UART_IT_RXNE);
404415
}
405-
} else {
406-
// TODO set flag for buffer overflow
407416
}
408417
}
409418
}
@@ -427,14 +436,23 @@ STATIC void pyb_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_k
427436
} else {
428437
mp_printf(print, "%u", self->uart.Init.Parity == UART_PARITY_EVEN ? 0 : 1);
429438
}
439+
if (self->uart.Init.HwFlowCtl) {
440+
mp_printf(print, ", flow=");
441+
if (self->uart.Init.HwFlowCtl & UART_HWCONTROL_RTS) {
442+
mp_printf(print, "RTS%s", self->uart.Init.HwFlowCtl & UART_HWCONTROL_CTS ? "|" : "");
443+
}
444+
if (self->uart.Init.HwFlowCtl & UART_HWCONTROL_CTS) {
445+
mp_printf(print, "CTS");
446+
}
447+
}
430448
mp_printf(print, ", stop=%u, timeout=%u, timeout_char=%u, read_buf_len=%u)",
431449
self->uart.Init.StopBits == UART_STOPBITS_1 ? 1 : 2,
432450
self->timeout, self->timeout_char,
433451
self->read_buf_len == 0 ? 0 : self->read_buf_len - 1); // -1 to adjust for usable length of buffer
434452
}
435453
}
436454

437-
/// \method init(baudrate, bits=8, parity=None, stop=1, *, timeout=1000, timeout_char=0, read_buf_len=64)
455+
/// \method init(baudrate, bits=8, parity=None, stop=1, *, timeout=1000, timeout_char=0, flow=0, read_buf_len=64)
438456
///
439457
/// Initialise the UART bus with the given parameters:
440458
///
@@ -444,6 +462,7 @@ STATIC void pyb_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_k
444462
/// - `stop` is the number of stop bits, 1 or 2.
445463
/// - `timeout` is the timeout in milliseconds to wait for the first character.
446464
/// - `timeout_char` is the timeout in milliseconds to wait between characters.
465+
/// - `flow` is RTS | CTS where RTS == 256, CTS == 512
447466
/// - `read_buf_len` is the character length of the read buffer (0 to disable).
448467
STATIC mp_obj_t pyb_uart_init_helper(pyb_uart_obj_t *self, mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
449468
static const mp_arg_t allowed_args[] = {
@@ -847,7 +866,7 @@ STATIC mp_uint_t pyb_uart_write(mp_obj_t self_in, const void *buf_in, mp_uint_t
847866
return MP_STREAM_ERROR;
848867
}
849868

850-
// wait to be able to write the first character
869+
// wait to be able to write the first character. EAGAIN causes write to return None
851870
if (!uart_tx_wait(self, self->timeout)) {
852871
*errcode = EAGAIN;
853872
return MP_STREAM_ERROR;
@@ -859,6 +878,17 @@ STATIC mp_uint_t pyb_uart_write(mp_obj_t self_in, const void *buf_in, mp_uint_t
859878
if (status == HAL_OK) {
860879
// return number of bytes written
861880
return size;
881+
} else if (status == HAL_TIMEOUT) { // UART_WaitOnFlagUntilTimeout() disables RXNE interrupt on timeout
882+
if (self->read_buf_len > 0) {
883+
__HAL_UART_ENABLE_IT(&self->uart, UART_IT_RXNE); // re-enable RXNE
884+
}
885+
// return number of bytes written
886+
if (self->char_width == CHAR_WIDTH_8BIT) {
887+
return size - self->uart.TxXferCount - 1;
888+
} else {
889+
int written = self->uart.TxXferCount * 2;
890+
return size - written - 2;
891+
}
862892
} else {
863893
*errcode = mp_hal_status_to_errno_table[status];
864894
return MP_STREAM_ERROR;

0 commit comments

Comments
 (0)