summaryrefslogtreecommitdiff
path: root/bsp/hifive1/drivers/drv_usart.c
blob: 935d39105f0dac843411e71ea7dd23a4cb749f6e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 */

#include <rtdevice.h>

#include <encoding.h>
#include <platform.h>
#include <interrupt.h>

static void usart_handler(int vector, void *param)
{
    rt_hw_serial_isr((struct rt_serial_device *)param, RT_SERIAL_EVENT_RX_IND);
}

static rt_err_t usart_configure(struct rt_serial_device *serial,
                                struct serial_configure *cfg)
{
    RT_ASSERT(serial != RT_NULL);
    RT_ASSERT(cfg != RT_NULL);

    GPIO_REG(GPIO_IOF_SEL) &= ~IOF0_UART0_MASK;
    GPIO_REG(GPIO_IOF_EN) |= IOF0_UART0_MASK;

    UART0_REG(UART_REG_DIV) = get_cpu_freq() / cfg->baud_rate - 1;
    UART0_REG(UART_REG_TXCTRL) |= UART_TXEN;
    UART0_REG(UART_REG_RXCTRL) |= UART_RXEN;
    UART0_REG(UART_REG_IE) = UART_IP_RXWM;

    return RT_EOK;
}

static rt_err_t usart_control(struct rt_serial_device *serial,
                              int cmd, void *arg)
{
    RT_ASSERT(serial != RT_NULL);

    switch (cmd)
    {
    case RT_DEVICE_CTRL_CLR_INT:
        break;
    case RT_DEVICE_CTRL_SET_INT:
        break;
    }

    return RT_EOK;
}

static int usart_putc(struct rt_serial_device *serial, char c)
{
    while (UART0_REG(UART_REG_TXFIFO) & 0x80000000) ;
    UART0_REG(UART_REG_TXFIFO) = c;

    return 0;
}

static int usart_getc(struct rt_serial_device *serial)
{
    rt_int32_t val = UART0_REG(UART_REG_RXFIFO);
    if (val > 0)
        return (rt_uint8_t)val;
    else
        return -1;
}

static struct rt_uart_ops ops =
{
    usart_configure,
    usart_control,
    usart_putc,
    usart_getc,
};

static struct rt_serial_device serial =
{
    .ops = &ops,
    .config.baud_rate = BAUD_RATE_115200,
    .config.bit_order = BIT_ORDER_LSB,
    .config.data_bits = DATA_BITS_8,
    .config.parity    = PARITY_NONE,
    .config.stop_bits = STOP_BITS_1,
    .config.invert    = NRZ_NORMAL,
    .config.bufsz     = RT_SERIAL_RB_BUFSZ,
};

int rt_hw_uart_init(void)
{
    rt_hw_serial_register(
        &serial,
        "dusart",
        RT_DEVICE_FLAG_STREAM
        | RT_DEVICE_FLAG_RDWR
        | RT_DEVICE_FLAG_INT_RX, RT_NULL);

    rt_hw_interrupt_install(
        INT_UART0_BASE,
        usart_handler,
        (void *) & (serial.parent),
        "uart interrupt");

    rt_hw_interrupt_unmask(INT_UART0_BASE);

    return 0;
}
INIT_BOARD_EXPORT(rt_hw_uart_init);