// Define which analog input pin we have connected to the temperature sensor
#define TEMP_SENSOR_PIN 0
#define ANALOG_VOTLAGE_REFERENCE 5
void setup() {
Serial.begin(115200);
}
void loop() {
// prints the currrent temperature with 2 place after the decimal point
printFloat(getTemperature(), 2);
// print a carriage return
Serial.println();
// rest 1000 milliseconds
delay(1000);
}
float CtoF(float c) {
return ((c -32.0) * 5.0 / 9.0 ) * 9.0 / 5.0 + 32.0 ;
}
float analogInToDegreesC(int inputValue) {
return inputValue / 1023.0 * ANALOG_VOTLAGE_REFERENCE * 100.0;
}
float getTemperature() {
return CtoF(analogInToDegreesC(analogRead(TEMP_SENSOR_PIN)));
}
void printFloat(float value, int places) {
int digit;
float tens = 0.1;
int tenscount = 0;
int i;
float tempfloat = value;
float d = 0.5;
if (value < 0)
d *= -1.0;
// divide by ten for each decimal place
for (i = 0; i < places; i++)
d/= 10.0;
// this small addition, combined with truncation will round our values properly
tempfloat += d;
if (value < 0)
tempfloat *= -1.0;
while ((tens * 10.0) <= tempfloat) {
tens *= 10.0;
tenscount += 1;
}
// write out the negative if needed
if (value < 0)
Serial.print(‘-’);
if (tenscount == 0)
Serial.print(0, DEC);
for (i=0; i< tenscount; i++) {
digit = (int) (tempfloat/tens);
Serial.print(digit, DEC);
tempfloat = tempfloat - ((float)digit * tens);
tens /= 10.0;
}
// if no places after decimal, stop now and return
if (places <= 0)
return;
// otherwise, write the point and continue on
Serial.print(‘.’);
for (i = 0; i < places; i++) {
tempfloat *= 10.0;
digit = (int) tempfloat;
Serial.print(digit,DEC);
// once written, subtract off that digit
tempfloat = tempfloat - (float) digit;
}
}