I need a function that decreases linearly for an Arduino mini-project. I need to somehow program the RGB led to go from blue to green, to yellow to red as the temperature varies and that means that I have to individually control 3 pins.
I have a couple of "if"s for each pin.
While the red pin is easy to control, as I simply have to gradually increase the output from 0 to 255( gradual control of electronics with arduino is achieved through PWM(
pulse width modulation), in this case in 256 steps) in the interval of, say, 45 to 120 degrees C, the green and the blue pin is more complicated.
The blue pin will be simply at its maximum value if the temperature drops bellow 0C, but from 0C to 25C it has to gradually decrease in intensity.
Before going into more details I want to say that Arduino has a special "map" function that takes an interval of values and maps it to another interval. So what I am doing is this:
map(temp, 0, 25, 0, 255);
temp is what the sensor outputs( well it actually outputs a voltage that is used to compute the temperature). 0-25 is the interval that will be mapped to 0-255. I would have made a function that maps the values myself but I have no idea how, but it's kind of redundant since there's already one.
So I have to basically decrease the value from 255 to 0 as the temperature increases from 0 to 25. Is there a magical formula for decreasing linearly? Because using something like f(x)=1/x gives me an asymptote and only the first 2 or 3 values are "visible" on the LED.
For the green pin I have to do a combination of what I'm doing for the blue and red pin. From 15C to 45C it will gradually increase in intensity, but from 45C to 70C it will gradually decrease.
Anyone has any suggestions?
TL;DR I need a function that decreases linearly. Any suggestions?
int green = 0;
if(temp < 45)
{ }
else
{ }
int red = map(temp, 45, 120, 0, 255)
But i still prefer making a protoboard model with analog electronics + LCD screen + micro controller and than plotting it and finishing it on a vitroplast board.
But my curiosity remains - is there a function that decreases linearly?
In case that's really what you're asking:
If you have a value x in the range between a and b, x is [x/(b-a)] distance from a.
If you have another range from c to d, you can get an equivalent point y in that range with y = c+[distance*(d-c)]
Of course distance will need to be a floating point number because it's between 0 and 1.
...
[EDIT] Although that was the function I was looking after, I don't need it anymore. Grim's suggestion to put the values in reverse in the map function actually works. This just saved me from a lot of hassle.