uartio.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * uartio.c
  3. *
  4. * Created on: Jan 21, 2022
  5. * Author: radioman
  6. */
  7. #include "main.h"
  8. #include "uartio.h"
  9. #include <string.h>
  10. static uint8_t uart_rx_buffer[UART_RX_BUF_SIZE];
  11. static uint8_t uart_tx_buffer[UART_TX_BUF_SIZE];
  12. static uint32_t rd_ptr;
  13. static uint8_t tx_cplt = 1;
  14. void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
  15. {
  16. tx_cplt = 1;
  17. }
  18. void UARTIO_Init(UART_HandleTypeDef *huart)
  19. {
  20. HAL_UART_Receive_DMA(huart, uart_rx_buffer, UART_RX_BUF_SIZE);
  21. rd_ptr = 0;
  22. }
  23. uint32_t UARTIO_DataAvail(UART_HandleTypeDef *huart)
  24. {
  25. if((UART_RX_BUF_SIZE - huart->hdmarx->Instance->CNDTR) >= rd_ptr)
  26. return (UART_RX_BUF_SIZE - huart->hdmarx->Instance->CNDTR) - rd_ptr;
  27. else
  28. return (2 * UART_RX_BUF_SIZE) - rd_ptr - huart->hdmarx->Instance->CNDTR;
  29. }
  30. uint32_t UARTIO_Receive(UART_HandleTypeDef *huart, uint8_t *buf)
  31. {
  32. uint32_t dma_ptr = (UART_RX_BUF_SIZE - huart->hdmarx->Instance->CNDTR);
  33. if(dma_ptr > rd_ptr)
  34. {
  35. uint32_t data_avail = dma_ptr - rd_ptr;
  36. memcpy(&buf[0], &uart_rx_buffer[rd_ptr], data_avail);
  37. rd_ptr = dma_ptr;
  38. return (data_avail);
  39. }
  40. else if(dma_ptr < rd_ptr)
  41. {
  42. uint32_t blk1_sz = UART_RX_BUF_SIZE - rd_ptr;
  43. memcpy(&buf[0], &uart_rx_buffer[rd_ptr], blk1_sz);
  44. memcpy(&buf[blk1_sz], &uart_rx_buffer[0], dma_ptr);
  45. rd_ptr = dma_ptr;
  46. return (blk1_sz + dma_ptr);
  47. }
  48. else
  49. {
  50. return 0;
  51. }
  52. }
  53. uint32_t UARTIO_Transmit(UART_HandleTypeDef *huart, uint8_t *buf, uint32_t len)
  54. {
  55. memcpy(uart_tx_buffer, buf, len);
  56. while(!tx_cplt);
  57. HAL_UART_Transmit_DMA(huart, uart_tx_buffer, len);
  58. tx_cplt = 0;
  59. return len;
  60. }