summaryrefslogtreecommitdiff
path: root/uart/stm32_uart.h
blob: 5e4fd29e0c0274d004e178011347bf54e734d607 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#pragma once

#include <mmio/mmio.h>

#include <type_traits>

struct STM32_UART_reg_v1_t {
	volatile uint32_t SR;
	volatile uint32_t DR;
	volatile uint32_t BRR;
	volatile uint32_t CR1;
	volatile uint32_t CR2;
	volatile uint32_t CR3;
	volatile uint32_t GTPR;
};

struct STM32_UART_reg_v2_t {
	volatile uint32_t CR1;
	volatile uint32_t CR2;
	volatile uint32_t CR3;
	volatile uint32_t BRR;
	volatile uint32_t GTPR;
	volatile uint32_t RTOR;
	volatile uint32_t RQR;
	volatile uint32_t ISR;
	volatile uint32_t ICR;
	volatile uint32_t RDR;
	volatile uint32_t TDR;
	volatile uint32_t PRESC; // Gx, L4+, Wx etc
};

struct STM32_UART_reg_lpv1_t {
	volatile uint32_t CR1;
	volatile uint32_t CR2;
	volatile uint32_t CR3;
	volatile uint32_t BRR;
	uint32_t _1[2];
	volatile uint32_t RQR;
	volatile uint32_t ISR;
	volatile uint32_t ICR;
	volatile uint32_t RDR;
	volatile uint32_t TDR;
};

template <typename T>
class STM32_UART_t : public mmio_ptr<T> {
    public:
        using mmio_ptr<T>::ptr;

	bool txe() const {
		if constexpr (std::is_same_v<T, STM32_UART_reg_v1_t>) {
			return ptr()->SR & (1 << 7);
		} else {
			return ptr()->ISR & (1 << 7);
		}
	}

	bool rxne() const {
		if constexpr (std::is_same_v<T, STM32_UART_reg_v1_t>) {
			return ptr()->SR & (1 << 5);
		} else {
			return ptr()->ISR & (1 << 5);
		}
	}

	uint8_t read() const {
		if constexpr (std::is_same_v<T, STM32_UART_reg_v1_t>) {
			return ptr()->DR;
		} else {
			return ptr()->RDR;
		}
	}

	void write(uint8_t data) const {
		if constexpr (std::is_same_v<T, STM32_UART_reg_v1_t>) {
			ptr()->DR = data;
		} else {
			ptr()->TDR = data;
		}
	}

	uint8_t read_blocking() const {
		while(!rxne());
		return read();
	}

	void write_blocking(uint8_t data) const {
		while(!txe());
		write(data);
	}
};