header
Connect Temperature Sensor
connect temperature sensor
/*
 Connect TMP36 sensor and output temperature on LCD screen
 
 TMP36
 Middle pin to Analog A0
 */

// include the library code
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12,11,5,4,3,2);

// initialize our variables
int sensorPin = 0;
int tempReading;
float voltage;
int tempC;

void setup() {
  // set up the LCD's number of columns and rows: 
  lcd.begin(16, 2);
}

void loop() {
  tempReading = analogRead(sensorPin);
  
  // convert the reading to a voltage
  voltage = tempReading * 3.6;
  voltage /= 1024.0;
  // convert the voltage to a temperature
  tempC = (voltage - 0.5) * 100;
  
  lcd.setCursor(0,0);
  lcd.print(tempC); lcd.print((char)223); lcd.print("C");
 
  delay(200);
}

After you upload this code to the arduino, you should see a temperature in celsius displayed on the first line of your lcd screen.


Refactoring

Once you have code that's working, it's usually helpful to change it to make it easier to read. That's what we're going to do here. In this code, we're basically doing two things. First we're reading the temperature from a pin and secondly we're displaying the temperature on the lcd screen. For our first refactoring, let's move the reading of the temperature to a separate function.

// include the library code
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12,11,5,4,3,2);

// initialize our variables
int sensorPin = 0;
int tempC;

void setup() {
  // set up the LCD's number of columns and rows: 
  lcd.begin(16, 2);
}

void loop() {  
  tempC = get_temperature(sensorPin);
  
  lcd.setCursor(0,0);
  lcd.print(tempC); lcd.print(" "); lcd.print((char)223); lcd.print("C");
 
  delay(200);
}
  
int get_temperature(int pin) {
  // We need to tell the function which pin the sensor is hooked up to. We're using
  // the variable pin for that above
  
  // Read the value on that pin
  int temperature = analogRead(pin);
  
  // Calculate the temperature based on the reading and send that value back
  float voltage = temperature * 5.0;
  voltage = voltage / 1024.0;
  return ((voltage - 0.5) * 100);
}

Again, since this was just refactoring, you should see exactly the same thing on your lcd screen that you saw before, which is just a temperature in celsius.

Next: Display the temperature in fahrenheit