1 /*
2 * Copyright (c) 2022 HPMicro
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "uart.h"
17 #include "los_arch_interrupt.h"
18 #include "los_interrupt.h"
19 #include "riscv_hal.h"
20
21 #ifdef __cplusplus
22 #if __cplusplus
23 extern "C" {
24 #endif
25 #endif
26
27 #define RX_BUF_SIZE 128
28 static uint8_t rx_buf[RX_BUF_SIZE];
29 static uint16_t rx_index;
30 static uint16_t tx_index;
31
UartPutc(INT32 c,VOID * file)32 INT32 UartPutc(INT32 c, VOID *file)
33 {
34 (VOID) file;
35 if (c == '\n') {
36 uart_send_byte(HPM_UART0, (UINT8)'\r');
37 }
38 uart_send_byte(HPM_UART0, (UINT8)c);
39 return c;
40 }
41
UartGetc(VOID)42 INT32 UartGetc(VOID)
43 {
44 uint8_t c = 0;
45 if (tx_index != rx_index) {
46 c = rx_buf[tx_index++];
47 tx_index %= RX_BUF_SIZE;
48 }
49 return c;
50 }
51
UartInit(VOID)52 VOID UartInit(VOID)
53 {
54 HPM_IOC->PAD[IOC_PAD_PA00].FUNC_CTL = IOC_PA00_FUNC_CTL_UART0_TXD;
55 HPM_IOC->PAD[IOC_PAD_PA01].FUNC_CTL = IOC_PA01_FUNC_CTL_UART0_RXD;
56
57 uart_config_t config = {0};
58 clock_set_source_divider(clock_uart0, clk_src_osc24m, 1U);
59 uart_default_config(HPM_UART0, &config);
60 config.src_freq_in_hz = clock_get_frequency(clock_uart0);
61 config.baudrate = 115200;
62 uart_init(HPM_UART0, &config);
63 }
64
UartReceiveHandler(VOID)65 VOID UartReceiveHandler(VOID)
66 {
67 if (uart_get_irq_id(HPM_UART0) & uart_intr_id_rx_data_avail) {
68 uint8_t c;
69 if (status_success == uart_receive_byte(HPM_UART0, &c)) {
70 rx_buf[rx_index++] = c;
71 rx_index %= RX_BUF_SIZE;
72 if (rx_index == tx_index) {
73 tx_index++;
74 tx_index %= RX_BUF_SIZE;
75 }
76 (void)LOS_EventWrite(&g_shellInputEvent, 0x1);
77 }
78 }
79 return;
80 }
81
Uart0RxIrqRegister(VOID)82 VOID Uart0RxIrqRegister(VOID)
83 {
84 uart_enable_irq(HPM_UART0, uart_intr_rx_data_avail_or_timeout);
85
86 uint32_t ret = LOS_HwiCreate(HPM2LITEOS_IRQ(IRQn_UART0), OS_HWI_PRIO_HIGHEST, 0, (HWI_PROC_FUNC)UartReceiveHandler, 0);
87 if (ret != LOS_OK) {
88 return;
89 }
90 HalIrqEnable(HPM2LITEOS_IRQ(IRQn_UART0));
91 }
92
93 #ifdef __cplusplus
94 #if __cplusplus
95 }
96 #endif /* __cplusplus */
97 #endif /* __cplusplus */
98