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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
|
/**
* @file cordic.cpp
* @brief Provides mathematical functions for algorithms.
*
* Copyright (C) 2023 Clyne Sullivan
*
* Distributed under the GNU GPL v3 or later. You should have received a copy of
* the GNU General Public License along with this program.
* If not, see <https://www.gnu.org/licenses/>.
*/
#include "cordic.hpp"
#include "hal.h"
#if !defined(TARGET_PLATFORM_L4)
namespace cordic {
void init()
{
RCC->AHB2ENR |= RCC_AHB2ENR_CORDICEN;
}
static void prepare() {
while (CORDIC->CSR & CORDIC_CSR_RRDY)
asm("mov r0, %0" :: "r" (CORDIC->RDATA));
}
static uint32_t dtoq(double) {
uint32_t res;
asm("vcvt.s32.f64 d0, d0, #31;"
"vmov %0, r5, d0"
: "=r" (res));
return res;
}
__attribute__((naked))
static double qtod(uint32_t) {
asm("eor r1, r1;"
"vmov d0, r0, r1;"
"vcvt.f64.s32 d0, d0, #31;"
"bx lr");
return 0;
}
__attribute__((naked))
double mod(double, double) {
asm("vdiv.f64 d2, d0, d1;"
"vrintz.f64 d2;"
"vmul.f64 d1, d1, d2;"
"vsub.f64 d0, d0, d1;"
"bx lr");
return 0;
}
double cos(double x) {
x = mod(x, 2 * math::PI) / math::PI;
auto input = dtoq(x > 1. ? x - 2 : x);
prepare();
CORDIC->CSR = CORDIC_CSR_NARGS | CORDIC_CSR_NRES |
(6 << CORDIC_CSR_PRECISION_Pos) |
(0 << CORDIC_CSR_FUNC_Pos);
CORDIC->WDATA = input;
CORDIC->WDATA = input;
while (!(CORDIC->CSR & CORDIC_CSR_RRDY));
double cosx = qtod(CORDIC->RDATA) / x;
[[maybe_unused]] auto sinx = CORDIC->RDATA;
return cosx;
}
double sin(double x) {
x = mod(x, 2 * math::PI) / math::PI;
auto input = dtoq(x > 1. ? x - 2 : x);
prepare();
CORDIC->CSR = CORDIC_CSR_NARGS | CORDIC_CSR_NRES |
(6 << CORDIC_CSR_PRECISION_Pos) |
(1 << CORDIC_CSR_FUNC_Pos);
CORDIC->WDATA = input;
CORDIC->WDATA = input;
while (!(CORDIC->CSR & CORDIC_CSR_RRDY));
double sinx = qtod(CORDIC->RDATA) / x;
[[maybe_unused]] auto cosx = CORDIC->RDATA;
return sinx;
}
double tan(double x) {
x = mod(x, 2 * math::PI) / math::PI;
auto input = dtoq(x > 1. ? x - 2 : x);
prepare();
CORDIC->CSR = CORDIC_CSR_NARGS | CORDIC_CSR_NRES |
(6 << CORDIC_CSR_PRECISION_Pos) |
(1 << CORDIC_CSR_FUNC_Pos);
CORDIC->WDATA = input;
CORDIC->WDATA = input;
while (!(CORDIC->CSR & CORDIC_CSR_RRDY));
double sinx = qtod(CORDIC->RDATA) / x;
double tanx = sinx * x / qtod(CORDIC->RDATA);
return tanx;
}
}
#else // L4
#include <cmath>
namespace cordic {
void init() {}
float mod(float a, float b) {
return a - (b * std::floor(a / b));
}
float cos(float x) { return std::cos(x); }
float sin(float x) { return std::sin(x); }
float tan(float x) { return std::tan(x); }
}
#endif
|