How do I convert multiMap function to library?


I have a working Sketch in which I use the multiMap function. Now I want to turn the multiMap into library files but I’m not really sure how to do it. I understand the principals of classes and objects and that I need a header and source file but I can’t figure out how to declare and use the variables.


The Sketch:

int pinSpd = A0; // select the input pin for the potentiometer
int pinThr = A1; // select the input pin for the throttle
int ledPin = 9; // select the pin for the LED
int spd = 0; // variable to store the value coming from the sensor
int thr =0;
int outLow = {0,50,100,150,200,250,300,350,400,450,512}; // 11
int outHigh = {0,100,200,300,400,500,600,700,700,700,700}; // 11
int in = {0,100,200,300,400,500,600,700,800,900,1023};
int x =0;
int xL =0;
int xH =0;

void setup() {
// declare the ledPin as an OUTPUT:
pinMode(ledPin, OUTPUT);

void loop() {
// read the value from the sensor:
spd = analogRead(pinSpd);
thr = analogRead(pinThr);
xL = multiMap(spd, in, outLow, 11);
xH = multiMap(spd, in, outHigh, 11);
x = map(thr, 0, 1023, xL, xH); // Scale throttle to outLow and outHigh
analogWrite(ledPin, x/4);
Serial.println(x, DEC);

int multiMap(int val, int* _in, int* _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 map(val, _in[pos-1], _in[pos], _out[pos-1], _out[pos]);

The variables are declared, in a class, just like they are in a sketch. The initialization of the variables can not be combined with the declaration, though, since the declaration occurs in the header (.h) file, and the initialization occurs in the implementation (.c/.cpp) file.


int outLow[11];
int outHigh[11];
int in[11];


outLow[0] = 0;
outLow[1] = 50;
outLow[10] = 512;

Similar code is needed for the other variables.

Where in the files the declaration and initialization code goes depends on whether you want to define a class, or not.