Practical 9
Practical 9
void setup() {
void loop() {
float voltage = sensorValue * (5.0 / 1023.0); // Convert the analog value to voltage
Serial.print("Temperature: ");
Serial.print(temperatureC);
Serial.println(" °C");
}
Here’s a detailed line-by-line explanation of the Arduino code for reading temperature from the TMP36
sensor:
cpp
Copy code
const int tmp36Pin = A0;: Defines a constant integer named tmp36Pin and assigns it the value A0. This is
the analog pin on the Arduino where the TMP36 sensor’s output is connected. Using const ensures that
this pin number cannot be changed accidentally later in the code.
cpp
Copy code
void setup() {
void setup(): The setup function is called once when the Arduino starts or resets. It is used to initialize
settings.
Serial.begin(9600);: Initializes serial communication at a baud rate of 9600 bits per second (bps). This
allows the Arduino to send data to the Serial Monitor on your computer.
cpp
Copy code
void loop() {
float voltage = sensorValue * (5.0 / 1023.0); // Convert the analog value to voltage
Serial.print("Temperature: ");
Serial.print(temperatureC);
Serial.println(" °C");
void loop(): The loop function runs repeatedly after the setup function has finished. This is where you
place code that needs to run continuously.
int sensorValue = analogRead(tmp36Pin);: Reads the analog value from the pin defined by tmp36Pin
(A0). The analogRead() function converts the voltage on the pin (from 0V to 5V) into a value between 0
and 1023 (10-bit ADC resolution).
float voltage = sensorValue * (5.0 / 1023.0);: Converts the analog reading into a voltage. The Arduino’s
ADC converts the 10-bit value (0-1023) into a voltage between 0V and 5V. This formula converts the
integer reading into a corresponding voltage:
float temperatureC = (voltage - 0.5) * 100;: Converts the voltage to temperature in Celsius. The TMP36
sensor outputs 500mV (0.5V) at 0°C, and the output increases by 10mV per °C:
Multiplying by 100 converts the voltage to temperature (since 10mV/°C = 100mV/°C per 1°C).
Serial.print("Temperature: ");: Sends the string "Temperature: " to the Serial Monitor.
Serial.println(" °C");: Sends " °C" to the Serial Monitor and moves to the next line.
delay(1000);: Pauses the program for 1000 milliseconds (1 second) before repeating the loop. This
reduces the frequency of readings and updates in the Serial Monitor.
Summary
Loop: Reads analog values, converts them to temperature, prints the result, and then pauses for 1
second before repeating.
This code will continuously read the temperature from the TMP36 sensor and display it on the Serial
Monitor in Celsius.