drv_usart.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /*
  2. * Copyright (c) 2006-2021, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. */
  9. #include <rtdevice.h>
  10. #include <encoding.h>
  11. #include <platform.h>
  12. #include <interrupt.h>
  13. static void usart_handler(int vector, void *param)
  14. {
  15. rt_hw_serial_isr((struct rt_serial_device *)param, RT_SERIAL_EVENT_RX_IND);
  16. }
  17. static rt_err_t usart_configure(struct rt_serial_device *serial,
  18. struct serial_configure *cfg)
  19. {
  20. RT_ASSERT(serial != RT_NULL);
  21. RT_ASSERT(cfg != RT_NULL);
  22. GPIO_REG(GPIO_IOF_SEL) &= ~IOF0_UART0_MASK;
  23. GPIO_REG(GPIO_IOF_EN) |= IOF0_UART0_MASK;
  24. UART0_REG(UART_REG_DIV) = get_cpu_freq() / cfg->baud_rate - 1;
  25. UART0_REG(UART_REG_TXCTRL) |= UART_TXEN;
  26. UART0_REG(UART_REG_RXCTRL) |= UART_RXEN;
  27. UART0_REG(UART_REG_IE) = UART_IP_RXWM;
  28. return RT_EOK;
  29. }
  30. static rt_err_t usart_control(struct rt_serial_device *serial,
  31. int cmd, void *arg)
  32. {
  33. RT_ASSERT(serial != RT_NULL);
  34. switch (cmd)
  35. {
  36. case RT_DEVICE_CTRL_CLR_INT:
  37. break;
  38. case RT_DEVICE_CTRL_SET_INT:
  39. break;
  40. }
  41. return RT_EOK;
  42. }
  43. static int usart_putc(struct rt_serial_device *serial, char c)
  44. {
  45. while (UART0_REG(UART_REG_TXFIFO) & 0x80000000) ;
  46. UART0_REG(UART_REG_TXFIFO) = c;
  47. return 0;
  48. }
  49. static int usart_getc(struct rt_serial_device *serial)
  50. {
  51. rt_int32_t val = UART0_REG(UART_REG_RXFIFO);
  52. if (val > 0)
  53. return (rt_uint8_t)val;
  54. else
  55. return -1;
  56. }
  57. static struct rt_uart_ops ops =
  58. {
  59. usart_configure,
  60. usart_control,
  61. usart_putc,
  62. usart_getc,
  63. };
  64. static struct rt_serial_device serial =
  65. {
  66. .ops = &ops,
  67. .config.baud_rate = BAUD_RATE_115200,
  68. .config.bit_order = BIT_ORDER_LSB,
  69. .config.data_bits = DATA_BITS_8,
  70. .config.parity = PARITY_NONE,
  71. .config.stop_bits = STOP_BITS_1,
  72. .config.invert = NRZ_NORMAL,
  73. .config.bufsz = RT_SERIAL_RB_BUFSZ,
  74. };
  75. int rt_hw_uart_init(void)
  76. {
  77. rt_hw_serial_register(
  78. &serial,
  79. "dusart",
  80. RT_DEVICE_FLAG_STREAM
  81. | RT_DEVICE_FLAG_RDWR
  82. | RT_DEVICE_FLAG_INT_RX, RT_NULL);
  83. rt_hw_interrupt_install(
  84. INT_UART0_BASE,
  85. usart_handler,
  86. (void *) & (serial.parent),
  87. "uart interrupt");
  88. rt_hw_interrupt_unmask(INT_UART0_BASE);
  89. return 0;
  90. }
  91. INIT_BOARD_EXPORT(rt_hw_uart_init);