DEV Community

Cover image for ESP32 Standard Library Embedded Rust: Analog Temperature Sensing using the ADC
Omar Hiari
Omar Hiari

Posted on • Updated on

ESP32 Standard Library Embedded Rust: Analog Temperature Sensing using the ADC

This blog post is the sixth of a multi-part series of posts where I explore various peripherals in the ESP32C3 using standard library embedded Rust and the esp-idf-hal. Please be aware that certain concepts in newer posts could depend on concepts in prior posts.

If you find this post useful, and if Embedded Rust interests you, stay in the know and skyrocket your learning curve by subscribing to The Embedded Rustacean newsletter:

Subscribe Now to The Embedded Rustacean

Introduction

NTC thermistors, or Negative Temperature Coefficient thermistors, are temperature-sensitive resistors made from materials that exhibit a change in resistance with temperature variations. As the temperature increases, the resistance of an NTC thermistor decreases (thus the negative naming), and conversely, when the temperature decreases, the resistance increases. This unique property makes NTC thermistors invaluable in temperature measurement and control applications. They are widely used as temperature sensors in electronic circuits, household appliances, automotive systems, industrial processes, and medical devices. NTC thermistors enable accurate temperature monitoring, providing feedback for maintaining stable operating conditions, triggering alarms, and regulating various processes with high precision.

In this post, I will be configuring and setting up an esp32c3-hal ADC using the esp-idf-hal to measure ambient temperature using a 10k (NTC) Thermistor. The ADC collected value will be converted to temperature and sent to the terminal output.

πŸ“š Knowledge Pre-requisites

To understand the content of this post, you need the following:

  • Basic knowledge of coding in Rust.

  • Familiarity with the working principles of NTC Thermistors. This page is a good resource.

πŸ’Ύ Software Setup

All the code presented in this post is available on the apollolabs ESP32C3 git repo. Note that if the code on the git repo is slightly different then it means that it was modified to enhance the code quality or accommodate any HAL/Rust updates.

Additionally, the full project (code and simulation) is available on Wokwi here.

πŸ›  Hardware Setup

Materials

⚑ Connections

  • Temperature sensor signal pin connected to pin gpio4. In Wokwi this is a direct connection. However, if you have the individual NTC component (not integrated on a board), you need to set it up in a voltage divider configuration with a 10K Ohm resistor (circuit in next section).

πŸ”Œ Circuit Analysis

The temperature sensor used is a negative temperature coefficient (NTC) sensor. This means the resistance of the sensor increases as the temperature increases. The following figure shows the schematic of the temperature sensor circuit:

NTC Circuit

It is shown that the NTC Thermistor is connected in a voltage divider configuration with a 10k resistor. As such, the voltage at the positive terminal of the op-amp V+V_{+} is equal to the voltage on the signal terminal and expressed as:

V+=Vccβˆ—R1R1+RNTCV_{\text{+}} = V_{cc}* \frac{R_{1}}{R_{1}} + R_{\text{NTC}}

Where R1=10kΞ©R_1 = 10k\Omega and the resistance value of (RNTC(R_{\text{NTC}} is the one that needs to be calculated to obtain the temperature. This means that later in the code, I would need to retrieve back the value of RNTCR_{\text{NTC}} from the V+V_{\text{+}} value that is being read by the ADC. With some algebraic manipulation, we can move all the known variables to the right-hand side of the equation to reach the following expression:

RNTC=(VccV+βˆ’1)βˆ—R1R_{\text{NTC}} = \left( \frac{ V_{cc} }{ V_{\text{+}} } -1 \right) * R_{1}

After extracting the value of RNTCR_{\text{NTC}} , I would need to determine the temperature. Following the equations in the datasheet, I leverage the Steinhart-Hart NTC equation that is presented as follows:

Ξ²=ln(RNTCR0)(1Tβˆ’1T0)\beta = \frac{ln(\frac{R_{\text{NTC}}}{R_0})}{(\frac{1}{T}-\frac{1}{T_0})}

where Ξ²\beta is a constant and equal to 3950 for our NTC as stated by Wokwi and TT is the temperature we are measuring. T0T_0 and R0R_0 refer to the ambient temperature (typically 25 Celcius) and nominal resistance at ambient temperature, respectively. The value of the resistance at 25 Celcius ( T0T_0 ) is equal to 10kΞ©10k\Omega ( R0R_0 ). With more algebraic manipulation we solve for TT to get:

T=11Ξ²βˆ—ln(RNTCR0)+1T0T = \frac{1}{\frac{1}{\beta} * ln(\frac{R_{\text{NTC}}}{R_0}) +\frac{1}{T_0}}

Take note that the Ξ²\beta value is typically obtained by manufacturers based on Kelvin temperatures. As such, when doing the calculations we'd have to convert back to Celcius.

πŸ‘¨β€πŸŽ¨ Software Design

Now that we know the equations from the prior section, an algorithm needs to be developed and is quite straightforward in this case. After configuring the device, the algorithmic steps are as follows:

  1. Kick off the ADC and obtain a reading/sample.

  2. Calculate the temperature in Celcius.

  3. Print the temperature value on the terminal.

  4. Go back to step 1.

πŸ‘¨β€πŸ’»Code Implementation

πŸ“₯ Crate Imports

In this implementation, the following crates are required:

  • The esp_idf_hal crate to import the needed device hardware abstractions.

  • The libm crate to provide an implementation for a natural logarithm.

use esp_idf_hal::adc::config::Config;
use esp_idf_hal::adc::*;
use esp_idf_hal::peripherals::Peripherals;
use esp_idf_hal::gpio::Gpio4;
use libm::log;
Enter fullscreen mode Exit fullscreen mode

πŸŽ› Initialization/Configuration Code

⌨️ GPIO Peripheral Configuration:

1️⃣ Obtain a handle for the device peripherals: In embedded Rust, as part of the singleton design pattern, we first have to take the device peripherals. This is done using the take() method. Here I create a device peripheral handler named peripherals as follows:

let peripherals = Peripherals::take().unwrap();
Enter fullscreen mode Exit fullscreen mode

2️⃣ Configure and Obtain a handle for the ADC driver: The ADC is configured in two steps in the esp-idf-hal first by setting up the AdcDriver that configures the ADC, and second setting up the channel that will configure the channel/pin settings. From the ESP32C3 reference manual, the following table exists:

ADC Channels

The table shows which ADC channels are connected to which ADC. In this case, since we are using gpio4 , then ADC1 is the one we should be configuring. To configure ADC1, there exists the AdcDriver new method that allows us to create an instance of a configured ADC. The new method takes two parameters which are the ADC peripheral instance (adc1 according to the table above) and a configuration instance. As such I create an adc handle as follows:

let mut adc = AdcDriver::new(peripherals.adc1, &Config::new()).unwrap();
Enter fullscreen mode Exit fullscreen mode

Config comes from the esp_idf_hal::adc::config module and contains configuration information like the resolution of the ADC. By default, the resolution used is 12-bits.

3️⃣Configure and Obtain a handle for the ADC channel: At this point, we configured the ADC but not yet the pin/channel. This is done using the AdcChannelDriver new method. The new method takes only one argument, which is an instance of a pin. I create an adc_pin handle that represents a configured channel as follows:

let mut adc_pin: esp_idf_hal::adc::AdcChannelDriver<'_, Gpio4, Atten11dB<_>> =
        AdcChannelDriver::new(peripherals.pins.gpio4).unwrap();
Enter fullscreen mode Exit fullscreen mode

Note how an attenuation Atten11dB is specified in the type parameters. This is necessary to define the attenuation level of the pin and thus the voltage range the pin will be able to measure. The documentation specifies four different attenuation levels of which the 11dB level supports the range of 0 mV ~ 2500 mV which is what we're going to use.

This is it for configuration! Let's now jump into the application code.

πŸ“±Application Code

Following the design described earlier, before entering my loop, I first need to set up a couple of constants that I will be using in my calculations. This includes keying in the constant values for \( \beta \) and VMAX as follows:

const B: f64 = 3950.0; // B value of the thermistor
const VMAX: f64 = 2500.0; // Full Range Voltage
Enter fullscreen mode Exit fullscreen mode

πŸ” The Application Loop

After entering the program loop, as the software design stated earlier, first thing I need to do is kick off the ADC to obtain a sample/reading. This is done through the read method that takes a mutable reference to the adc_pin instance and returns a Result:

 let sample: u16 = adc.read(&mut adc_pin).unwrap();
Enter fullscreen mode Exit fullscreen mode

Note here that the read method in the esp-idf-hal, unlike the read method in the no_std libraries returns a voltage, not a raw value. Next, I convert the sample value to a temperature by implementing the earlier derived equations as follows:

let temperature = 1. / (log(1. / (VMAX / sample as f64 - 1.)) / B + 1.0 / 298.15) - 273.15;
Enter fullscreen mode Exit fullscreen mode

A few things to note here; First, recall from the read method that sample is a u16, so I had to use as f64 to cast it as an f64 for the calculation. Second, log is the natural logarithm obtained from the libm library that I imported earlier. Third, and last, the temperature is calculated in Kelvins, the 273.15 is what converts it to Celcius. Like mentioned earlier the Beta parameter is determined based on Kelvins.

Finally, now that the temperature is available, I send it over to the console using the println! macro as follows:

println!("Temperature {:02} Celcius\r", temperature);
Enter fullscreen mode Exit fullscreen mode

This is it!

πŸ“±Full Application Code

Here is the full code for the implementation described in this post. You can additionally find the full project and others available on the apollolabs ESP32C3 git repo. Also, the Wokwi project can be accessed here.

/*
For a detailed explanation of this code check out the associated blog post:


GitHub Repo containing source code and other examples:
https://github.com/apollolabsdev

For notifications on similar examples and more, subscribe to newsletter here:
https://subscribepage.io/apollolabsnewsletter
*/

use esp_idf_sys::{self as _}; // If using the `binstart` feature of `esp-idf-sys`, always keep this module imported

use esp_idf_hal::adc::config::Config;
use esp_idf_hal::adc::*;
use esp_idf_hal::peripherals::Peripherals;
use esp_idf_hal::gpio::Gpio4;
use libm::log;

fn main() -> anyhow::Result<()> {
    let peripherals = Peripherals::take().unwrap();

    // Configure ADC Driver
    let mut adc = AdcDriver::new(peripherals.adc1, &Config::new()).unwrap();

    // Configure ADC Channel
    let mut adc_pin: esp_idf_hal::adc::AdcChannelDriver<'_, Gpio4, Atten11dB<_>> =
        AdcChannelDriver::new(peripherals.pins.gpio4).unwrap();

    const B: f64 = 3950.0; // B value of the thermistor
    const VMAX: f64 = 2500.0; // Full Range Voltage

    // Algorithm
    // 1) Get adc reading
    // 2) Convert to temperature
    // 3) Send over Serial
    // 4) Go Back to step 1

    loop {
        // Get ADC Reading
        let sample: u16 = adc.read(&mut adc_pin).unwrap();

        //Convert to temperature
        let temperature = 1. / (log(1. / (VMAX / sample as f64 - 1.)) / B + 1.0 / 298.15) - 273.15;

        // Print the temperature output
        println!("Temperature {:02} Celcius\r", temperature);
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this post, an analog temperature measurement application was created by leveraging the esp-idf-hal ADC peripheral for the ESP32C3. The resulting measurement is also sent over to terminal output. Additionally, all code was created at the HAL level using the esp32c3-hal. Have any questions? Share your thoughts in the comments below πŸ‘‡.

If you found this post useful, and if Embedded Rust interests you, stay in the know and skyrocket your learning curve by subscribing to The Embedded Rustacean newsletter:

Subscribe Now to The Embedded Rustacean

Top comments (0)