This example is the same as the first simple example but with added code to calculate the speed of sound based on the temperature from the CPX's thermistor. That temperature is then used to calculate the divisor for distance calculations.
This code introduces a new variable to store the temperature read from the thermistor in degrees Celsius. The speed of sound is then calculated using a formula. The number 273.15 may be familiar - it's being used to convert the temperature to Kelvin.
The potential flaw from the original code is fixed with the addition of a 62 millisecond delay when the distance is out of range for a beep. At 120bpm, a demisemiquaver (1/32 note) is 4 * 60 / 120 / 32 * 1000 = 62.5ms.
The temperature is also logged to allow it to inspected to ensure the value is reasonable and accurate.
A good question is whether the temperature needs to be calculated every time a new distance is measured. As temperature does not typically change much this could be performed once. A single calculation would be problematic if the code was expected to run for a long time or the temperature was expected to change rapidly. At the cost of increased complexity of code, one compromise solution would be to calculate it periodically with the period based on the likely rate of change. Sample rate decisions like this become more relevant when the calculation is more intensive and there are limited resources.