blob: 1ac994e6c8d5ad118f6b349d6332eeaa830e0504 [file] [log] [blame]
Angel Pons8a3453f2020-04-02 23:48:19 +02001/* SPDX-License-Identifier: GPL-2.0-only */
Kyösti Mälkki3ee16682014-02-17 19:37:52 +02002
Kyösti Mälkki1d7541f2014-02-17 21:34:42 +02003#include <console/uart.h>
Julius Werner1732dcb2018-04-24 16:33:58 -07004#include <types.h>
5#include <timer.h>
Kyösti Mälkki3ee16682014-02-17 19:37:52 +02006
7/* Calculate divisor. Do not floor but round to nearest integer. */
8unsigned int uart_baudrate_divisor(unsigned int baudrate,
9 unsigned int refclk, unsigned int oversample)
10{
11 return (1 + (2 * refclk) / (baudrate * oversample)) / 2;
12}
Lee Leahy14876212016-05-04 13:13:20 -070013
Julius Wernercd49cce2019-03-05 16:53:33 -080014#if !CONFIG(UART_OVERRIDE_INPUT_CLOCK_DIVIDER)
Lee Leahy14876212016-05-04 13:13:20 -070015unsigned int uart_input_clock_divider(void)
16{
17 /* Specify the default oversample rate for the UART.
18 *
19 * UARTs oversample the receive data. The UART's input clock first
20 * enters the baud-rate divider to generate the oversample clock. Then
21 * the UART typically divides the result by 16. The asynchronous
22 * receive data is synchronized with the oversample clock and when a
23 * start bit is detected the UART delays half a bit time using the
24 * oversample clock. Samples are then taken to verify the start bit and
25 * if present, samples are taken for the rest of the frame.
26 */
27 return 16;
28}
29#endif
Lee Leahy6ec72c92016-05-07 09:04:46 -070030
Julius Wernercd49cce2019-03-05 16:53:33 -080031#if !CONFIG(UART_OVERRIDE_REFCLK)
Lee Leahy6ec72c92016-05-07 09:04:46 -070032unsigned int uart_platform_refclk(void)
33{
34 /* Specify the default input clock frequency for the UART.
35 *
36 * The older UART's used an input clock frequency of 1.8432 MHz which
37 * with the 16x oversampling provided the maximum baud-rate of 115200.
38 * Specify this as maximum baud-rate multiplied by oversample so that
39 * it is obvious that the maximum baud rate is 115200 when divided by
40 * oversample clock. Also note that crystal on the board does not
41 * change when software selects another input clock divider.
42 */
43 return 115200 * 16;
44}
45#endif
Julius Werner1732dcb2018-04-24 16:33:58 -070046
47/* Helper function to allow bitbanging an 8n1 UART. */
48void uart_bitbang_tx_byte(unsigned char data, void (*set_tx)(int line_state))
49{
50 const int baud_rate = get_uart_baudrate();
51 int i;
52 struct stopwatch sw;
53 stopwatch_init(&sw);
54
55 /* Send start bit */
56 set_tx(0);
57 while (stopwatch_duration_usecs(&sw) < MHz / baud_rate)
58 stopwatch_tick(&sw);
59
60 /* 'i' counts the total bits sent at the end of the loop */
61 for (i = 2; i < 10; i++) {
62 set_tx(data & 1);
63 data >>= 1;
64 while (stopwatch_duration_usecs(&sw) < i * MHz / baud_rate)
65 stopwatch_tick(&sw);
66 }
67
68 /* Send stop bit */
69 set_tx(1);
70 while (stopwatch_duration_usecs(&sw) < i * MHz / baud_rate)
71 stopwatch_tick(&sw);
72}