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