Thames & Kosmos Code Gamer Experiment Manual page 39

Coding workshop ? game with kosmobits
Table of Contents

Advertisement

PROJECT 9
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
You know all about the
through N times, or 20 times in this case.
With each pass through the loop, another measurement
reading will be added to the current
pause of 10 milliseconds before each subsequent reading
When the loop is abandoned, the sum of the 20
X
measurement readings is saved in the
To calculate the average from that, the total must be
divided by the number of readings. That happens in the
average = average / N;
Finally,
return average;
average.
It's simple:
pinMode(sensorPin, INPUT);
as the input pin. Finally, the resting value is
sensorPin
calculated and stored in the
In the main loop, a current sensor value is first read and
saved in
value
from the average and save it in the
The deviation always has to be positive. Since you don't
know if the current sensor reading is greater than or less
than
restingValue
decide between two cases: If
restingValue
value - restingValue
restingValue - value
Now,
pixel.setColor()
independently of the
difference, the higher the red portion, and the lower the
green portion.
CodeGamer manual inside english.indd 37
variable.
loop now. It will be passed
for
average
average
line.
returns the calculated
sets the
variable.
restingValue
. Now it's time to determine the deviation
difference
, the
instruction will be used to
if
is greater than
value
,
is calculated as
difference
; otherwise, it is calculated as
.
is used to set the NeoPixel color
value: The greater the
difference
int determineRestingValue() {
const int N = 20;
float average = 0;
for (int i = 0; i < 20; ++i) {
average = average + analogRead(sensorPin);
delay(10);
}
average = average / N;
. There is a
return average;
}
variable.
void setup() {
pinMode(sensorPin, INPUT);
restingValue = determineRestingValue();
}
void loop() {
int value = analogRead(sensorPin);
variable.
int difference;
if (value > restingValue) {
difference = value - restingValue;
} else {
difference = restingValue - value;
}
pixel.setColor(2 * difference, 100 - 2 *
difference, 0, difference);
// brightness.
delay(10);
}
CodeGamer
</>
// measurement numbers
// RGB value and
7/19/16 12:32 PM
37

Advertisement

Table of Contents
loading

Table of Contents