Hardware Reference
In-Depth Information
Example 4-3. Reading a force sensitive resistor
#define FSR_PIN 0
//
void
setup
()
{
Serial
.
begin
(
9600
);
}
void
loop
()
{
int
sensorReading
=
analogRead
(
FSR_PIN
);
//
if
(
sensorReading
<
10
)
{
//
Serial
.
println
(
"I don't feel much at all!"
);
}
else
if
(
sensorReading
<
600
)
{
//
Serial
.
println
(
"Thanks for the squeeze!"
);
}
else
{
//
Serial
.
println
(
"Ouch!"
);
}
delay
(
1000
);
}
Tell the compiler to replace all instances of
FSR_PIN
with 0 before
compiling the sketch.
Take the analog reading from
FSR_PIN
(pin 0) and store it in an integer
variable called
sensorReading
.
If the
sensorReading
is less than 10, print “I don't feel much at all!” via
serial.
Otherwise, if
sensorReading
is less than 600, print “Thanks for the
squeeze!” via serial.
Otherwise, print “Ouch!” via serial. Based on the previous
if
statements, this would only be executed if
sensorReading
is greater
than or equal to 600.
Code and Syntax Notes
Not only did you use
analogRead()
to try out the FSR in
Example 4-3
, there
are also a couple of new coding concepts:
#define
and
else if
.
#define
#define
is considered a
preprocessor directive
. It tells the compiler to do a
“find and replace” before it compiles. In the case of
Example 4-3
, all instances
of
FSR_PIN
are replaced with
0
and then the code is compiled.