Hardware Reference
In-Depth Information
Second, a serial interface is created for debugging. Finally, the sketch is told to
attach a servo motor on pin 9 ( servoPin ), and a default value is written. Ninety
degrees is specii ed, moving the arm to a default position in the middle of the
reading. The sketch is given 1 second to move, which is more than enough time.
On line 20, the loop() function is dei ned. First, the sketch reads the voltage
from A0 , comparing it to 1.1 V. The result, returned as an integer, is stored in
reading . Next, the variable reading is divided by 9.31 (calculated previously),
and the result is stored in a l oating-point number, called tempC . Next, the angle
must be calculated. This is done through map() , by i rst indicating the values
that are expected for the temperature (0 to 50) and next, the values expected as
an angle (135 to 45). The numbers are inverted because this servo motor turns
counterclockwise, and the lowest temperature is expected to be on the left.
On lines 25 to 28, data is printed to the serial port. This is used as debug
information and can be omitted in a i nal version.
Finally, on line 29, the angle is written to the servo pin, and the sketch waits
for one-half a second before repeating.
Congratulations, you have just created a retro thermometer!
Exercises
This sketch is fully functional but requires some tweaking to be optimal. For
example, the servo motor movement may sometimes be a little erratic. Now
look at the serial output to have a better idea:
22.34 Celsius, 86 degrees
22.77 Celsius, 86 degrees
23.20 Celsius, 88 degrees
So, the difference between 22.77 and 22.34 degrees Celsius does not result in
a movement, but the difference between 22.77 and 23.20 degrees Celsius results
in a 2-degree movement? This is the result of the map() function, and because
it “translates” a 50-unit range to a 90-unit range, it will lose a little precision. If
you need more precision, you will have to look at another way of controlling
the servo motor. Try using writeMicroseconds() for greater accuracy.
Also, there is one requirement that was not put into place. Temperatures above
50 degrees Celsius should be ignored, but they aren't. map() specii es values
between 0 and 50, and will “map” them to values between 45 and 135, but this
does not mean that values are limited. If the input value is outside of the input
range, it will also be outside of the output range. Try to limit input or output
values, using min() and max() , or even better, use constrain() .
What solution did you come up with?
 
Search WWH ::




Custom Search