Video/TvThermometer/TvThermometer.ino
void loop() {
Line 1
unsigned long current_millis = millis();
-
if (abs(current_millis - last_measurement) >= 1000) {
-
current_temperature = get_temperature();
-
last_measurement = current_millis;
5
int y_pos = mapfloat(
-
current_temperature, MIN_TEMP, MAX_TEMP, SCALE_Y_MAX, SCALE_Y_MIN);
-
TV.draw_rect(
-
SCALE_X_MIN, SCALE_Y_MIN, SCALE_WIDTH, SCALE_HEIGHT, BLACK, BLACK);
-
TV.draw_rect(
10
SCALE_X_MIN, y_pos, SCALE_WIDTH, SCALE_Y_MAX - y_pos, WHITE, WHITE);
-
TV.select_font(font6x8);
-
TV.set_cursor(53, 1);
-
TV.print("Current");
-
TV.set_cursor(40, 11);
15
TV.print("Temperature:");
-
TV.select_font(font8x8);
-
TV.set_cursor(50, 25);
-
TV.print(current_temperature, 1);
-
TV.print(" C");
20
TV.draw_circle(88, 27, 1, WHITE);
-
}
-
}
-
-
const float mapfloat(
25
float x, float in_min, float in_max, float out_min, float out_max)
-
{
-
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
-
}
-
30
const float get_temperature() {
-
const int sensor_voltage = analogRead(TEMP_SENSOR_PIN);
-
const float voltage = sensor_voltage * SUPPLY_VOLTAGE / 1024;
-
return (voltage * 1000 - 500) / 10;
-
}
35
We make sure that we measure the current temperature only once per second.
Whenever we determine the current temperature, we calculate the new upper
Y position of the thermometer’s scale in line 6. The
map_float
function maps
the current temperature to a value on our thermometer’s scale.
Then we use the
draw_rect
method (which draws a rectangle on the screen)
twice. The first call erases the thermometer’s scale completely. This is neces-
sary because the temperature can rise or fall. We could clear and redraw the
whole screen every time, but that would be overkill. The second call draws a
white rectangle on our scale that represents the current temperature.
Chapter 8. Generating Video Signals with an Arduino • 138
report erratum • discuss
www.it-ebooks.info