void setup() {
10
Serial.begin(BAUD_RATE);
-
}
-
-
void loop() {
-
unsigned long current_millis = millis();
15
if (abs(current_millis - last_measurement) >= 1000) {
-
current_temperature = get_temperature();
-
last_measurement = current_millis;
-
}
-
Serial.print(scaled_value(current_temperature));
20
Serial.print(",");
-
const unsigned long duration = measure_distance();
-
Serial.println(scaled_value(microseconds_to_cm(duration)));
-
}
-
25
long scaled_value(const float value) {
-
float round_offset = value < 0 ? -0.5 : 0.5;
-
return (long)(value * 100 + round_offset);
-
}
-
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
-
const float microseconds_per_cm() {
-
return 1 / ((331.5 + (0.6 * current_temperature)) / 10000);
-
}
-
40
const float sensor_offset() {
-
return SENSOR_GAP * microseconds_per_cm() * 2;
-
}
-
-
const float microseconds_to_cm(const unsigned long microseconds) {
45
const float net_distance = max(0, microseconds - sensor_offset());
-
return net_distance / microseconds_per_cm() / 2;
-
}
-
-
const unsigned long measure_distance() {
50
pinMode(PING_SENSOR_IO_PIN, OUTPUT);
-
digitalWrite(PING_SENSOR_IO_PIN, LOW);
-
delayMicroseconds(2);
-
digitalWrite(PING_SENSOR_IO_PIN, HIGH);
-
delayMicroseconds(5);
55
digitalWrite(PING_SENSOR_IO_PIN, LOW);
-
pinMode(PING_SENSOR_IO_PIN, INPUT);
-
return pulseIn(PING_SENSOR_IO_PIN, HIGH);
-
}
-
report erratum • discuss
Increasing Precision Using a Temperature Sensor • 91
www.it-ebooks.info