Reputation: 23
I need to implement an algorithm that adapts to the rate of change of a variable. Lets say I have an integer HumidityPercent and an external sensor feeding data on real time. I found several ways to detect if my var has changed:
private float HumChange
{
get { return HumidityPercent; }
set
{
HumidityPercent = value;
if (HumidityPercent != 100)
{
// Do what?
}
}
}
I have a timer (a stopwatch) to calculate milliseconds passed. Thing is: How can I invoke a change in a new variable to store both milliseconds and the new value?
private double newHum = (HumidityPercent, timer.TotalMilliseconds);
But after that how can I differentiate?
Any help would be appreciated.
Upvotes: 1
Views: 3704
Reputation: 23
After a thorough search (and a lot of learning on my side) I built up on @ChrisF code and made a consise snipet that is efficient and elegant.
public void InitTimer()
{
timer = new System.Timers.Timer();
timer.Enabled = true;
timer.Elapsed += timer_Tick;
timer.Interval = 200;
}
public void timer_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
timer.Enabled = false;
System.Threading.Interlocked.Increment(ref current);
if (current == 0)
{
current = HumidityPercent;
}
else
{
previous = current;
current = HumidityPercent;
RateOfChange = (current-previous)/5;
Thread.Sleep(200);
}
timer.Enabled = true;
}
Noticed that I have to call the InitTimer method once, so I used:
if (firstrun == true)
{
InitTimer();
firstrun = false;
}
Also notice that I have sandwiched the tick in a stop-start event, put a Thread.Sleep and also added the very handy and efficient System.Threading.Interlocked.Increment(ref current).
Thank you all for your contribution!
Upvotes: 1
Reputation: 137158
If you need the rate of change then you need to have three things:
If you have a timer running then the first time it fires all it needs to do is store the humidity.
The next time it fires it needs to move the "current" value into the "previous" value, update the "current" value and do the rate of change calculation.
So if you have your values as nullable doubles you can test to see if you have a previous value or not:
private double? previous;
private double current;
private double rateOfChange;
private void TimerTick(....)
{
if (previous == null)
{
current = GetHumidity();
}
else
{
previous = current;
current = GetHumidity();
rateOfChange = (current - previous) / time;
}
}
Upvotes: 1