uartio.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 tail;
  13. static uint8_t tx_cplt = 1;
  14. static UART_HandleTypeDef *uart_handle;
  15. void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
  16. {
  17. if(huart == uart_handle)
  18. tx_cplt = 1;
  19. }
  20. void UARTIO_Init(UART_HandleTypeDef *huart)
  21. {
  22. uart_handle = huart;
  23. tail = 0;
  24. HAL_UART_Receive_DMA(uart_handle, uart_rx_buffer, UART_RX_BUF_SIZE);
  25. }
  26. uint32_t UARTIO_DataAvailable(void)
  27. {
  28. uint32_t head = UART_RX_BUF_SIZE - uart_handle->hdmarx->Instance->CNDTR;
  29. if(head >= tail)
  30. return (head - tail);
  31. else
  32. return (UART_RX_BUF_SIZE - tail + head);
  33. }
  34. int UARTIO_Receive(uint8_t *buf, uint32_t len)
  35. {
  36. //uint32_t dma_ptr = (UART_RX_BUF_SIZE - huart->hdmarx->Instance->CNDTR);
  37. uint32_t head = UART_RX_BUF_SIZE - uart_handle->hdmarx->Instance->CNDTR;
  38. if(tail == head)
  39. return (-1);
  40. if(tail > head)
  41. {
  42. uint32_t cap_avail = UART_RX_BUF_SIZE - tail + head;
  43. if((UART_RX_BUF_SIZE - tail) >= len)
  44. {
  45. memcpy(buf, &uart_rx_buffer[tail], len);
  46. tail = (tail + len) % UART_RX_BUF_SIZE;
  47. }
  48. else
  49. {
  50. if(len > cap_avail)
  51. len = cap_avail;
  52. uint32_t blk1_sz = UART_RX_BUF_SIZE - tail;
  53. memcpy(buf, &uart_rx_buffer[tail], blk1_sz);
  54. tail = 0;
  55. memcpy(&buf[blk1_sz], &uart_rx_buffer[tail], (len - blk1_sz));
  56. tail = (len - blk1_sz) % UART_RX_BUF_SIZE;
  57. }
  58. }
  59. else
  60. {
  61. if(len > (head - tail))
  62. len = head - tail;
  63. memcpy(buf, &uart_rx_buffer[tail], len);
  64. tail = (tail + len) % UART_RX_BUF_SIZE;
  65. }
  66. return (len);
  67. }
  68. int UARTIO_Transmit(uint8_t *buf, uint32_t len)
  69. {
  70. if(!tx_cplt)
  71. return (-1);
  72. memcpy(uart_tx_buffer, buf, len);
  73. HAL_UART_Transmit_DMA(uart_handle, uart_tx_buffer, len);
  74. tx_cplt = 0;
  75. return len;
  76. }