GY-63_MS5611/libraries/MultiMap/MultiMap.h

97 lines
2.3 KiB
C
Raw Normal View History

2020-11-27 05:20:37 -05:00
#pragma once
2014-11-18 13:32:33 -05:00
//
2021-01-29 06:31:58 -05:00
// FILE: MultiMap.h
2014-11-18 13:32:33 -05:00
// AUTHOR: Rob Tillaart
2021-05-28 07:39:42 -04:00
// VERSION: 0.1.4
2020-11-27 05:20:37 -05:00
// DATE: 2011-01-26
// PURPOSE: Arduino library for fast non-linear mapping or interpolation of values
// URL: https://github.com/RobTillaart/MultiMap
2014-11-18 13:32:33 -05:00
// URL: http://playground.arduino.cc/Main/MultiMap
//
2021-01-29 06:31:58 -05:00
// HISTORY:
// 0.0.1 2011-01-26 initial version (see forum)
// .....
// 0.1.0 2015-03-29
// 0.1.1 2020-04-09
// 0.1.2 2020-06-19 fix library.json
// 0.1.3 2021-01-02 add arduino-CI
2021-05-28 07:39:42 -04:00
// 0.1.4 2021-05-27 fix arduino-lint
#define MULTIMAP_LIB_VERSION (F("0.1.4"))
2014-11-18 13:32:33 -05:00
2021-01-29 06:31:58 -05:00
#include "Arduino.h"
2014-11-18 13:32:33 -05:00
// note: the in array should have increasing values
template<typename T>
T multiMap(T val, T* _in, T* _out, uint8_t size)
{
// take care the value is within range
// val = constrain(val, _in[0], _in[size-1]);
if (val <= _in[0]) return _out[0];
if (val >= _in[size-1]) return _out[size-1];
// search right interval
uint8_t pos = 1; // _in[0] allready tested
while(val > _in[pos]) pos++;
// this will handle all exact "points" in the _in array
if (val == _in[pos]) return _out[pos];
// interpolate in the right segment for the rest
return (val - _in[pos-1]) * (_out[pos] - _out[pos-1]) / (_in[pos] - _in[pos-1]) + _out[pos-1];
}
2020-11-27 05:20:37 -05:00
/*
* speed optimized version if inputs do not change often e.g. 2 2 2 2 2 3 3 3 3 5 5 5 5 5 5 8 8 8 8 5 5 5 5 5
2021-01-29 06:31:58 -05:00
*
2020-11-27 05:20:37 -05:00
// note: the in array should have increasing values
2021-01-29 06:31:58 -05:00
2020-11-27 05:20:37 -05:00
template<typename T>
T multiMap(T val, T* _in, T* _out, uint8_t size)
2014-11-18 13:32:33 -05:00
{
2021-01-29 06:31:58 -05:00
static T lastvalue = -1;
static T cache = -1;
2014-11-18 13:32:33 -05:00
2021-01-29 06:31:58 -05:00
if (val == lastvalue)
{
return cache;
}
lastvalue = val;
// take care the value is within range
// val = constrain(val, _in[0], _in[size-1]);
if (val <= _in[0])
{
cache = _out[0];
}
else if (val >= _in[size-1])
{
cache = _out[size-1];
}
else
{
// search right interval; index 0 _in[0] already tested
uint8_t pos = 1;
while(val > _in[pos]) pos++;
// this will handle all exact "points" in the _in array
if (val == _in[pos])
{
cache = _out[pos];
}
2020-11-27 05:20:37 -05:00
else
2021-01-29 06:31:58 -05:00
{
// interpolate in the right segment for the rest
cache = (val - _in[pos-1]) * (_out[pos] - _out[pos-1]) / (_in[pos] - _in[pos-1]) + _out[pos-1];
}
}
return cache;
2014-11-18 13:32:33 -05:00
}
*/
2020-11-27 05:20:37 -05:00
2021-05-28 07:39:42 -04:00
2020-11-27 05:20:37 -05:00
// -- END OF FILE --