stm32rcos
 
読み取り中…
検索中…
一致する文字列を見つけられません
uart_dma.hpp
[詳解]
1#pragma once
2
3#include <cstddef>
4#include <cstdint>
5#include <vector>
6
7#include "stm32rcos/core.hpp"
8#include "stm32rcos/hal.hpp"
9
10#include "../uart_type.hpp"
11
12namespace stm32rcos {
13namespace peripheral {
14namespace detail {
15
16template <UartType TxType> class UartTx;
17template <UartType RxType> class UartRx;
18
19template <> class UartTx<UartType::DMA> {
20public:
21 UartTx(UART_HandleTypeDef *huart) : huart_{huart} {}
22
23 bool transmit(const uint8_t *data, size_t size, uint32_t timeout) {
24 if (HAL_UART_Transmit_DMA(huart_, data, size) != HAL_OK) {
25 HAL_UART_AbortTransmit_IT(huart_);
26 return false;
27 }
28 core::TimeoutHelper timeout_helper;
29 while (huart_->gState != HAL_UART_STATE_READY) {
30 if (timeout_helper.is_timeout(timeout)) {
31 HAL_UART_AbortTransmit_IT(huart_);
32 return false;
33 }
34 osDelay(1);
35 }
36 return true;
37 }
38
39private:
40 UART_HandleTypeDef *huart_;
41
42 UartTx(const UartTx &) = delete;
43 UartTx &operator=(const UartTx &) = delete;
44};
45
46template <> class UartRx<UartType::DMA> {
47public:
48 UartRx(UART_HandleTypeDef *huart, size_t buf_size)
49 : huart_{huart}, buf_(buf_size) {
50 HAL_UART_Receive_DMA(huart, buf_.data(), buf_.size());
51 }
52
53 ~UartRx() { HAL_UART_Abort_IT(huart_); }
54
55 bool receive(uint8_t *data, size_t size, uint32_t timeout) {
56 core::TimeoutHelper timeout_helper;
57 while (available() < size) {
58 if (timeout_helper.is_timeout(timeout)) {
59 return false;
60 }
61 osDelay(1);
62 }
63 for (size_t i = 0; i < size; ++i) {
64 data[i] = buf_[read_idx_];
65 advance(1);
66 }
67 return true;
68 }
69
70 void flush() { advance(available()); }
71
72 size_t available() {
73 size_t write_idx = buf_.size() - __HAL_DMA_GET_COUNTER(huart_->hdmarx);
74 return (buf_.size() + write_idx - read_idx_) % buf_.size();
75 }
76
77private:
78 UART_HandleTypeDef *huart_;
79 std::vector<uint8_t> buf_;
80 size_t read_idx_ = 0;
81
82 UartRx(const UartRx &) = delete;
83 UartRx &operator=(const UartRx &) = delete;
84
85 void advance(size_t len) { read_idx_ = (read_idx_ + len) % buf_.size(); }
86};
87
88} // namespace detail
89} // namespace peripheral
90} // namespace stm32rcos
Definition utility.hpp:12
bool is_timeout(uint32_t &timeout)
Definition utility.hpp:16
size_t available()
Definition uart_dma.hpp:72
UartRx(UART_HandleTypeDef *huart, size_t buf_size)
Definition uart_dma.hpp:48
bool receive(uint8_t *data, size_t size, uint32_t timeout)
Definition uart_dma.hpp:55
UartTx(UART_HandleTypeDef *huart)
Definition uart_dma.hpp:21
bool transmit(const uint8_t *data, size_t size, uint32_t timeout)
Definition uart_dma.hpp:23
Definition uart.hpp:21
Definition can.hpp:18
UartType
Definition uart_type.hpp:6
@ DMA
Definition uart_type.hpp:9
Definition mutex.hpp:9