Thermocouple Sensor Interfacing with ESP32

Overview of Thermocouple

K-Type Thermocouple Sensor with MAX6675

 

Thermocouple consists of two different conductors forming an electrical junction at different temperatures.

Due to the thermo effect, thermocouples produce a voltage that is dependent on temperature.

Temperature can be found out from this voltage.

ADC output of this voltage can be processed by a microcontroller to give the temperature.

For more information about thermocouples and how to use them, refer the topic Thermocouple in the sensors and modules section.

 

MAX6675 Specifications and Pin Details

  • MAX6675  is cold junction compensation and digitizes the input signal from a K-type thermocouple.
  • 12-bit output resolution (0.25°C Resolution)
  • SPI Interface for communication
  • It measures a minimum 0°C to maximum 1024°C temperature
  • Available in 8 Pin SO package
  • For more information, please find the datasheet in the attachment.

 

Pin Diagram of MAX6675

 

K-Type Thermocouple MAX6675 Hardware Connection with ESP32

ESP32 interfacing to Thermocouple using MAX6675

 

 

Measure Temperature using K-Type Thermocouple with MAX6675 and ESP32

Now, let’s interface the Thermocouple sensor with MAX6675 to ESP32 and display the surrounding temperature on the serial monitor.

Install required libraries

Here we are using Adafruit libraries for the above example. We need to install Adafruit’s MAX6675 library using the Arduino Library Manager.

  • Open the Arduino IDE
  • Navigate to Sketch  Include Library  Manage Libraries…

 

  • The library Manager window will pop up. Now enter MAX6675 into the search box, and click Install on the MAX6675 library by Adafruit option to install version 1.1.0 or higher.

 

  • After installation open the serialthermocouple example using the below path.

Go to File ► Example ► MAX6675 library ► serialthermocouple

 

  • Here we have modified the below example as per the above interfacing diagram connection.

Code for K-Type Thermocouple Serial Output using ESP32

// this example is public domain. enjoy!
// https://learn.adafruit.com/thermocouple/

/*
____________________________________________________
 SPI pin name | ESP32 pin (SPI2) | ESP32 pin (SPI3)|
----------------------------------------------------
     CS      |       15         |        5       |
     SCLK    |       14         |      18        |
     MISO    |       12         |      19        |
     MOSI    |       13         |      23        |
----------------------------------------------------
*/

// this example is public domain. enjoy!
// https://learn.adafruit.com/thermocouple/

#include "max6675.h"

int thermoDO = 12;
int thermoCS = 15;
int thermoCLK = 14;

MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);

void setup() {
  Serial.begin(9600);

  Serial.println("MAX6675 test");
  // wait for MAX chip to stabilize
  delay(500);
}

void loop() {
  // basic readout test, just print the current temp
 
   Serial.print("C = "); 
   Serial.println(thermocouple.readCelsius());
   Serial.print("F = ");
   Serial.println(thermocouple.readFahrenheit());
 
   // For the MAX6675 to update, you must delay AT LEAST 250ms between reads!
   delay(1000);
}

 

  • Now upload the code. (While uploading the code make sure your ESP32 board is in the boot mode.)
  • After uploading the code open the serial monitor and set the baud rate to 9600 to see the output.

 

ESP32 Serial Output for K-Type Thermocouple Sensor using max6675

 

Let’s Understand the code

The header file includes all definitions related to max6675 chip

#include "max6675.h"

Define the SPI pins of ESP32 for max6675 chip

int thermoDO = 12;
int thermoCS = 15;
int thermoCLK = 14;

MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);

 

In Setup function

We have initiated the serial communication with a 9600 Baud rate.

Serial.begin(9600);

 

In loop function

In the loop function, we are reading the temperature in Celsius and Fahrenheit and displaying it on the serial monitor.

The below function is used to read the temperature in Celsius.

thermocouple.readCelsius();

The below function is used to read the temperature in Fahrenheit.

thermocouple.readFahrenheit();

 

Temperature Measurement using K-Type Thermocouple over ESP32 Web Server

Let’s interface the K-type Thermocouple sensor to ESP32 and display the temperature in degree Celsius and degree Fahrenheit on the web server.

Before uploading the code make sure you have added your SSID and Password as follows.

const char* ssid = "*Your SSID*";         /*Enter Your SSID*/
const char* password = "*Your Password*"; /*Enter Your Password*/

 

Code for K-Type Thermocouple WebServer Measurement using ESP32

// this example is public domain. enjoy!
// https://learn.adafruit.com/thermocouple/

/*
____________________________________________________
 SPI pin name | ESP32 pin (SPI2) | ESP32 pin (SPI3)|
----------------------------------------------------
     CS      |       15         |        5       |
     SCLK    |       14         |      18        |
     MISO    |       12         |      19        |
     MOSI    |       13         |      23        |
----------------------------------------------------
*/

#include <WiFi.h>
#include <WebServer.h>
#include "html.h"
#include "max6675.h"

int thermoDO = 12;
int thermoCS = 15;
int thermoCLK = 14;

MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);

WebServer server(80);

const char* ssid = "*Your SSID*";         /*Enter Your SSID*/
const char* password = "*Your Password*"; /*Enter Your Password*/

long temp_C, temp_F;

void MainPage() {
  String _html_page = html_page;              /*Read The HTML Page*/
  server.send(200, "text/html", _html_page);  /*Send the code to the web server*/
}

void Web_Thermo() {
  String data = "[\""+String(temp_C)+"\",\""+String(temp_F)+"\"]";
  server.send(200, "text/plane", data);
}

void setup(void){
  Serial.begin(115200);                   /*Set the baudrate to 115200*/
  WiFi.mode(WIFI_STA);                    /*Set the WiFi in STA Mode*/
  WiFi.begin(ssid, password);
  Serial.print("Connecting to ");
  Serial.println(ssid);
  delay(1000);                            /*Wait for 1000mS*/
  while(WiFi.waitForConnectResult() != WL_CONNECTED){Serial.print(".");} /*Wait while connecting to WiFi*/
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("Your Local IP address is: ");
  Serial.println(WiFi.localIP());         /*Print the Local IP*/

  server.on("/", MainPage);               /*Display the Web/HTML Page*/
  server.on("/readWeb_Thermo", Web_Thermo); /*Display the updated Distance value(CM and INCH)*/
  server.begin();                         /*Start Server*/
  delay(1000);                            /*Wait for 1000mS*/
}

void loop(void){
  // For the MAX6675 to update, you must delay AT LEAST 250ms between reads!
  temp_C = thermocouple.readCelsius();    /*Read Temperature on °C*/
  temp_F = thermocouple.readFahrenheit(); /*Read Temperature on °F*/
  Serial.print("°C = "); 
  Serial.println(temp_C);
  Serial.print("°F = ");
  Serial.println(temp_F);
  server.handleClient();
  delay(1000);                            /*Wait for 1000mS*/
}

 

  • Now upload the code. (While uploading the code make sure your ESP32 board is in the boot mode.)
  • After uploading the code open the serial monitor and set the baud rate to 115200 then reset the ESP32 board and check the IP address as shown in the below image

 

 

  • Now open any mobile browser and type the IP address which is shown in the serial monitor and hit the enter button. 
  • If all are ok, then the web page will start the showing current temperature on the web server like in the below image.

Note: make sure your ESP32 and mobile are connected to the same router/server, if they are connected to the same router or server then only you will be able to visible the web page.

 

Final Output on the webserver

 

Let’s Understand the code

To understand this code, please refer the basics guide of “How to create the ESP32 Server”.

Once you get the basics of ESP32 server creation, it will be very simple to understand the code.

This code starts with important header files and libraries, In WiFi.h file contains all ESP32 WiFi related definitions, here we have used them for network connection purposes. 

The WebServer.h file supports handling the HTTP GET and POST requests as well as setting up a server. In the html.h file contains all the web page code and then add max6675.h library.

#include <WiFi.h>
#include <WebServer.h>
#include "html.h"
#include "max6675.h"

Let’s define HTTP port i.e., Port 80 as follows

WebServer server(80);

Set the ESP32 SPI pin numbers which we have connected to the max6675 module.

int thermoDO = 12;
int thermoCS = 15;
int thermoCLK = 14;

 

Setup Function

In setup function, first we set the WiFi as an STA mode and connect to the given SSID and password

WiFi.mode(WIFI_STA);          /*Set the WiFi in STA Mode*/
WiFi.begin(ssid, password);
Serial.print("Connecting to ");
Serial.println(ssid);
delay(1000);                  /*Wait for 1000mS*/
while(WiFi.waitForConnectResult() != WL_CONNECTED){Serial.print(".");}

After successfully connecting to the server print the local IP address on the serial window.

Serial.print("Your Local IP address is: ");
Serial.println(WiFi.localIP());     /*Print the Local IP*/

 

Handling Client Requests and Serving the Page

To handle the client request, we use server.on() function.

It takes two parameters, The first is requested URL path, and the second is the function name, which we want to execute.

As per the below code, when a client requests the root (/) path, the “MainPage()” function executes. 

Also, when a client requests the “/readWeb_Thermo” path, The Web_Thermo() function will be called.

server.on("/", MainPage);           /*Client request handling: calls the function to serve HTML page */
server.on("/readWeb_Thermo", Web_Thermo); /*Display the updated Distance value(CM and INCH)*/
Now start the server using server.begin() function.
server.begin();                     /*Start Server*/

 

Functions for Serving HTML

We have defined the complete HTML page in file named “html.h” and added it in header file. With following function, we are sending complete page to client via server.send() function.

While sending, we are passing the first parameter “200” which is status response code as OK (Standard response for successful HTTP requests). 

Second parameter is content type as “text/html“, and third parameter is html page code.

void MainPage() {
  String _html_page = html_page;              /*Read The HTML Page*/
  server.send(200, "text/html", _html_page);  /*Send HTM page to Client*/
}

Now in the below function only we are sending the updated temperature values to the web page.

void Web_Thermo() {
  String data = "[\""+String(temp_C)+"\",\""+String(temp_F)+"\"]";
  server.send(200, "text/plane", data);
}

 

Loop Function

Now to handle the incoming client requests and serve the relevant HTML page, we can use handleClient() function. It executing relevant server.on() as a callback function although it is defined in void setup()

So, it continuously serves the client requests.

server.handleClient();

 

HTML Web Page Code

This is a code for the web page that shows the measured temperature using a K-type thermocouple using MAX6675 and ESP32.

/*
  ESP32 HTML WebServer Page Code
  http:://www.electronicwings.com
*/

const char html_page[] PROGMEM = R"RawString(
<!DOCTYPE html>
<html>
  <style>
    body {font-family: sans-serif;}
    h1 {text-align: center; font-size: 30px;}
    p {text-align: center; color: #4CAF50; font-size: 40px;}
  </style>

<body>
  <h1>K-Type Thermocouple Sensor with ESP32</h1><br>
  <p>Temperature in &degC = <span id="_C">0</span>&degC</p>
  <p>Temperature in &degF = <span id="_F">0</span>&degF</p>

<script>
  setInterval(function() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        const txt = this.responseText;
        const obj = JSON.parse(txt);
       document.getElementById("_C").innerHTML = obj[0];
       document.getElementById("_F").innerHTML = obj[1];
      }
    };
    xhttp.open("GET", "readWeb_Thermo", true);
    xhttp.send();
  },50);
</script>
</body>
</html>
)RawString";

 

Let’s understand the code step by step

All html pages start with the <!DOCTYPE html> declaration, it is just information to the browser about what type of document is expected.

<!DOCTYPE html>

The html tag is the container of the complete html page which represents on the top of the html code.

<html>

Now here we are defining the style information for a web page using the <style> tag. Inside the style tag we have defined the font name, size, color, and test alignment.

  <style>
    body {font-family: sans-serif;}
    h1 {text-align: center; font-size: 30px;}
    p {text-align: center; color: #4CAF50; font-size: 40px;}
  </style>

 

Inside the body, we are defining the document body, in below we have used headings, and paragraphs if you want you can add images, hyperlinks, tables, lists, etc. also.

In the heading of the page, we are displaying the heading of the page, and inside a paragraph Celsius, and Fahrenheit values. 

Now Celsius and Fahrenheit value updates under the span id which is manipulated with JavaScript using the id attribute.

<body>
  <h1>K-Type Thermocouple Sensor with ESP32</h1><br>
  <p>Temperature in &degC = <span id="_C">0</span>&degC</p>
  <p>Temperature in &degF = <span id="_F">0</span>&degF</p>

Now, this is the javascript that comes under the <script> tag, this is also called a client-side script.

<script>

 

In setInterval() method we are calling the function at every 50mS intervals.

setInterval(function() {},50);

here we are creating the html XMLHttpRequest object

var xhttp = new XMLHttpRequest();

 

The xhttp.onreadystatechange event is triggered every time the readyState changes and the readyState holds the status of the XMLHttpRequest.

Now in the below code, the ready state is 4 means the request finished and response is ready and the status is 200 which means OK.

xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
const myArr = JSON.parse(this.responseText);

Now here is the main thing, we are updating the Celsius and Fahrenheit values in html page using _C and _F id.

document.getElementById("_C").innerHTML = obj[0];
document.getElementById("_F").innerHTML = obj[1];

 

Here we used the AJAX method to send the updated values to the server without refreshing the page.

In the below function we have used the GET method and sent the readWeb_Thermo function which we defined in the main code asynchronously. 

xhttp.open("GET", "readWeb_Thermo", true);

Send the request to the server using xhttp.send(); function.

xhttp.send();

 

Close the script

</script>

Close the body

</body>

Close the html.

</html>

Components Used

MAX6675 K-Thermocouple to Digital Converter
MAX6675 is a an IC by Maxim Integrated that performs cold junction compensation and provides the signal from a K-type thermocouple in a digital form.
1
K TypeThermocouple Glass Braid Insulated
K TypeThermocouple Glass Braid Insulated
1
ESP32 WROOM
WiFi Development Tools - 802.11 ESP32 General Development Kit, embeds ESP32-WROOM-32E, 4MB flash.
1

Downloads

ESP32_Thermocouple_Serial Download
ESP32_Thermocouple_webserver Download
Ad