![Thames & Kosmos Code Gamer Скачать руководство пользователя страница 39](http://html1.mh-extra.com/html/thames-and-kosmos/code-gamer/code-gamer_experiment-manual_1099224039.webp)
X
Y
Z
int determineRestingValue() {
const int N = 20;
// measurement numbers
float average = 0;
for (int i = 0; i < 20; ++i) {
average = a analogRead(sensorPin);
delay(10);
}
average = average / N;
return average;
}
void setup() {
pinMode(sensorPin, INPUT);
restingValue = determineRestingValue();
}
void loop() {
int value = analogRead(sensorPin);
int difference;
if (value > restingValue) {
difference = value - restingValue;
} else {
difference = restingValue - value;
}
pixel.setColor(2 * difference, 100 - 2 *
difference, 0, difference);
// RGB value and
// brightness.
delay(10);
}
</>
To determine the resting value, calculate the average of 20
readings. The number of readings will be saved in the N
constant, so it can easily be changed. The average is stored
in the
average
variable.
You know all about the
for
loop now. It will be passed
through N times, or 20 times in this case.
With each pass through the loop, another measurement
reading will be added to the current
average
. There is a
pause of 10 milliseconds before each subsequent reading
When the loop is abandoned, the sum of the 20
measurement readings is saved in the
average
variable.
To calculate the average from that, the total must be
divided by the number of readings. That happens in the
average = average / N;
line.
Finally,
return average;
returns the calculated
average.
It’s simple:
pinMode(sensorPin, INPUT);
sets the
sensorPin
as the input pin. Finally, the resting value is
calculated and stored in the
restingValue
variable.
In the main loop, a current sensor value is first read and
saved in
value
. Now it’s time to determine the deviation
from the average and save it in the
difference
variable.
The deviation always has to be positive. Since you don’t
know if the current sensor reading is greater than or less
than
restingValue
, the
if
instruction will be used to
decide between two cases: If
value
is greater than
restingValue
,
difference
is calculated as
value - restingValue
; otherwise, it is calculated as
restingValue - value
.
Now,
pixel.setColor()
is used to set the NeoPixel color
independently of the
difference
value: The greater the
difference, the higher the red portion, and the lower the
green portion.
Do you have your own ideas about
how the NeoPixel color should react
to the deviation from the resting
value? Try it! You’re sure to come up
with all sorts of interesting
variations.
37
PROJECT 9
CodeGamer
CodeGamer manual inside english.indd 37
7/19/16 12:32 PM