Hi PilotinControl,
You may apply hystersis. The state will be set to 1 if the value goes above three times the upper limit or it will be set to 0 if the value goes below lower limit three times.
#!/usr/bin/perl
use strict;
use warnings;
my $state = 0; # 0 - light off, 1 - light on
my $uplim = 102; # upper limit
my $lolim = 98; # lower limit
my $n = 3; #
my $counter = 0;
# Set initial state
# This part may need more work in order to avoid eventual starting gli
+tch.
my $value = <DATA>;
chomp $value;
if ($value > (($uplim + $lolim) / 2.0)) {
$state = 1;
} else {
$state = 0;
}
# work continuously
while ($value = <DATA>) {
chomp $value;
# Adjust counter
if ($value > $uplim) {
if ($counter < 0) {
$counter = 0;
} else {
$counter++;
}
} elsif ($value < $lolim) {
if ($counter > 0) {
$counter = 0;
} else {
$counter--;
}
} else {
$counter = 0;
}
# Set state
if ($counter > $n) {
$state = 1;
} elsif ($counter < -$n) {
$state = 0;
}
# Print
my ($below, $between, $above);
$below = $between = $above = '---';
if ($value > $uplim) {
$above = $value;
} elsif ($value < $lolim) {
$below = $value;
} else {
$between = $value;
}
printf "state: %d cnt: %+3d %3s<%3d>%3s<%3d>%3s\n", $state, $counter
+, $below, $lolim, $between, $uplim, $above;
}
__DATA__
100
101
102
103
104
105
106
105
104
103
102
101
100
99
98
97
96
95
94
101
102
103
103
102
103
103
104
104
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|