SAE Teensy ECU
IIT SAE Microcontroller programming
Loading...
Searching...
No Matches
Util.h
Go to the documentation of this file.
1
12#ifndef __ECU_UTIL_H__
13#define __ECU_UTIL_H__
14
18#define Euler exp(1.0)
19
23#define clamp(v, m, x) min(max(v, m), x)
24
33double EMAvg(double lastVal, double newVal, int memCount);
34
45template <class T, class A, class B, class C, class D>
46T cMap(T x, A inMin, B inMax, C outMin, D outMax) {
47 T mapped = map(x, inMin, inMax, outMin, outMax);
48 if (mapped < outMin)
49 return outMin;
50 if (mapped > outMax)
51 return outMax;
52 return mapped;
53}
54
62template <typename T>
63class AvgVar {
64private:
65 double avg = 0.0;
66 int samples;
67
68public:
74 AvgVar(int samples) {
75 this->samples = samples;
76 }
77
83 operator T() const { return (T)avg; }
84
91 T operator=(T val) {
92 avg = EMAvg(avg, val, samples);
93 return (T)avg;
94 }
95};
96
104template <typename T>
106private:
107 double avg = 0.0;
108 T *pointer;
109 int samples;
110
111public:
118 AvgVarRef(T *pointer, int samples) {
119 this->pointer = pointer;
120 this->samples = samples;
121 }
122
128 operator T() {
129 avg = EMAvg(avg, *pointer, samples);
130 return (T)avg;
131 }
132};
133
134#endif // __ECU_UTIL_H__
T cMap(T x, A inMin, B inMax, C outMin, D outMax)
Map a value from one range to another while clamping the value to boundaries.
Definition Util.h:46
double EMAvg(double lastVal, double newVal, int memCount)
Exponential moving average.
Definition Util.cpp:14
Variable that automaticaly averages itself out when it is set to a value.
Definition Util.h:63
AvgVar(int samples)
Construct a new AvgVar given the number of samples to average the value over.
Definition Util.h:74
T operator=(T val)
Update the internal average value given the next value.
Definition Util.h:91
Variable that automaticaly averages itself out when it is called, that is, it only updates it's avera...
Definition Util.h:105
AvgVarRef(T *pointer, int samples)
Construct a new AvgVar Ref given the number of samples to average the value over and the pointer to t...
Definition Util.h:118