Adicionar primeiro

This commit is contained in:
2025-06-06 21:17:25 +01:00
parent c188084ba4
commit 282e7f517b
841 changed files with 199592 additions and 1 deletions

View File

@@ -0,0 +1 @@
2e4752aa8fc9768365ee9198ba800141402a7466ff3133f617f1beab87bcc2ef

View File

@@ -0,0 +1,15 @@
# ChangeLog
## v0.3.0 - 2024-06-07
- Update parameter and return of ntc_dev_get_temperature API.
## v0.2.0 - 2024-05-11
- Support two circuit mode: NTC connected with VCC or GND.
## v0.1.0 - 2024-4-17
First release version.
- Support ntc_driver

View File

@@ -0,0 +1,6 @@
idf_component_register(SRCS "ntc_driver.c"
REQUIRES esp_adc
INCLUDE_DIRS "include")
include(package_manager)
cu_pkg_define_version(${CMAKE_CURRENT_LIST_DIR})

View File

@@ -0,0 +1,52 @@
# NTC driver Component
[中文版](./README_CN.md)
The NTC driver components are packaged for different thermistor initializations and corresponding temperature readings, and these solutions are managed using an abstraction layer for developers to integrate into their own applications, which are now supported by the ESP32-C2 / ESP32-C3 / ESP32 / ESP32-C6 / ESP32-S3 family of chips.
NTC Driver Applicable Circuit:
Single ADC channel measurement:
When the NTC is on top, as the temperature increases, the resistance value of the NTC decreases, causing the voltage at the NTC terminal in the divider circuit to drop, and the voltage at the fixed resistor side rises, and the final output voltage changes accordingly. The opposite is true when the NTC is below, where a drop in the resistance value of the NTC causes the voltage at the NTC side of the divider circuit to rise, and a drop in the voltage at the fixed resistor side, resulting in a corresponding change in the output voltage. As a result, the NTC will get opposite results above and below, which requires special care when designing and using NTC measurement circuits to ensure that the temperature characteristics of the NTC are properly understood and handled.
When using the following circuits:
Vcc --------> Rt --------> Rref --------> GND
The corresponding circuit mode needs to be selected through the ```circuit_mode``` field in ```ntc_config_t```. When using this circuit mode, ```CIRCUIT_MODE_NTC_VCC``` should be used.
When using the following circuits:
Vcc --------> Rref --------> Rt --------> GND
The corresponding circuit mode needs to be selected through the ```circuit_mode``` field in ```ntc_config_t```. When using this circuit mode, ```CIRCUIT_MODE_NTC_GND``` should be used.
> `Rref` is the voltage dividing resistor; `Rt` is the resistance of the thermistor at T1 temperature.
## Example of NTC thermistor scheme usage
```c
//1.Select the NTC sensor and initialize the hardware parameters
ntc_config_t ntc_config = {
.b_value = 3950,
.r25_ohm = 10000,
.fixed_ohm = 10000,
.vdd_mv = 3300,
.circuit_mode = CIRCUIT_MODE_NTC_GND,
.atten = ADC_ATTEN_DB_11,
.channel = ADC_CHANNEL_3,
.unit = ADC_UNIT_1
};
//2.Create the NTC Driver and Init ADC
ntc_device_handle_t ntc = NULL;
adc_oneshot_unit_handle_t adc_handle = NULL;
ESP_ERROR_CHECK(ntc_dev_create(&ntc_config, &ntc, &adc_handle));
ESP_ERROR_CHECK(ntc_dev_get_adc_handle(ntc, &adc_handle));
//3.Call the temperature function
float temp = 0.0;
if (ntc_dev_get_temperature(ntc, &temp) == ESP_OK) {
ESP_LOGI(TAG, "NTC temperature = %.2f ℃", temp);
}
ESP_ERROR_CHECK(ntc_dev_delete(ntc));
```
## Sample code
[Click here](https://github.com/espressif/esp-iot-solution/tree/master/examples/sensors/ntc_temperature_sensor) Get sample code and instructions for use.

View File

@@ -0,0 +1,52 @@
# NTC 驱动组件概述
[English Version](./README.md)
ntc驱动组件针对于不同热敏电阻初始化以及相应的温度读取做了封装使用一个抽象层管理这些方案便于开发者集成到自己的应用程序中目前 ESP32-C2 / ESP32-C3 / ESP32 / ESP32-C6 / ESP32-S3 系列芯片都已经完成支持。
NTC Driver 适用电路:
单 ADC 通道测量:
当NTC在上面时,随着温度升高, NTC 的电阻值下降,导致分压电路中 NTC 端的电压下降,固定电阻端的电压上升,最终输出电压会随之变化。而当 NTC 在下面时,情况正好相反, NTC 的电阻值下降会导致分压电路中 NTC 端的电压上升,固定电阻端的电压下降,输出电压也会相应变化。因此, NTC 在上面和下面会得到相反的结果,这一点在设计和使用 NTC 测量电路时需要特别注意,确保正确理解和处理 NTC 的温度特性。
当使用以下电路时:
Vcc --------> Rt --------> Rref --------> GND
需要通过 ```ntc_config_t``` 中的 ```circuit_mode``` 字段选择相应的电路模式。当使用这种电路模式时,应该使用 ```CIRCUIT_MODE_NTC_VCC```。
当使用以下电路时:
Vcc --------> Rref --------> Rt --------> GND
需要通过 ```ntc_config_t``` 中的 ```circuit_mode``` 字段选择相应的电路模式。当使用这种电路模式时,应该使用 ```CIRCUIT_MODE_NTC_GND```。
> `Rref` 是分压电阻;`Rt` 是热敏电阻在 T1 温度下的电阻。
## ntc 热敏电阻方案使用示例
```c
//1.选择ntc传感器并进行硬件参数初始化配置
ntc_config_t ntc_config = {
.b_value = 3950,
.r25_ohm = 10000,
.fixed_ohm = 10000,
.vdd_mv = 3300,
.circuit_mode = CIRCUIT_MODE_NTC_GND,
.atten = ADC_ATTEN_DB_11,
.channel = ADC_CHANNEL_3,
.unit = ADC_UNIT_1
};
//2.创建 NTC 驱动并初始化 ADC
ntc_device_handle_t ntc = NULL;
adc_oneshot_unit_handle_t adc_handle = NULL;
ESP_ERROR_CHECK(ntc_dev_create(&ntc_config, &ntc, &adc_handle));
ESP_ERROR_CHECK(ntc_dev_get_adc_handle(ntc, &adc_handle));
//3.调用温度函数
float temp = 0.0;
if (ntc_dev_get_temperature(ntc, &temp) == ESP_OK) {
ESP_LOGI(TAG, "NTC temperature = %.2f ℃", temp);
}
ESP_ERROR_CHECK(ntc_dev_delete(ntc));
```
## 示例代码
[点击此处](https://github.com/espressif/esp-iot-solution/tree/master/examples/sensors/ntc_temperature_sensor) 获取示例代码及使用说明。

View File

@@ -0,0 +1,6 @@
# The following lines of boilerplate have to be in your project's CMakeLists
# in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.16)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(ntc_temperature_sensor)

View File

@@ -0,0 +1,78 @@
# Example of a temperature sensor application
[中文版](./README_CN.md)
This example demonstrates how to develop a thermistor sensor temperature reading application using a 'ntc_driver' component on an ESP32-C2 / ESP32-C3 / ESP32 / ESP32-C6 / ESP32-S3 series chip. The specific features demonstrated are as follows:
- Control based on the lowest level of driver APIs
- Thermistor CMFA103J3950HANT-driven demo
- Optionally configurable with different thermistor drives
CMFA103J3950HANT Sensor wiring diagram:
```
ESP8684-DevKitM-1 CMFA103J3950HANT
--
[ADC1 CHANEL3] --------> | || NTC IO
--
```
## How to use the sample
### Hardware requirements
1. Select the driver to be demonstrated via 'idf.py menuconfig' and configure the driver
2. Hardware Connection:
- For CMFA103J3950HANT drivers, only the signal port needs to be connected to the configured GPIO.
### Compile and burn
1. Go to the '**' directory:
```linux
cd ./esp-iot-solution/examples/sensors/ntc_temperature_sensor
```
2. Use the 'idf.py' tool to set up the compilation chip, and then compile and download it with the following commands:
```linux
# Set up the compilation chip
idf.py set-target esp32c2
# Compile and download
idf.py -p PORT build flash
```
Please replace 'PORT' with the port number you are currently using
3. You can use 'monitor' to view the output of the program, and the command is:
```
idf.py -p PORT monitor
```
### Sample output
Here's the CMFA103J3950HANT-driven test log:
```log
I (333) app_start: Starting scheduler on CPU0
I (337) app_start: Starting scheduler on CPU1
I (337) main_task: Started on CPU0
I (347) main_task: Calling app_main()
I (347) ntc driver: IoT Ntc Driver Version: 0.1.0
I (347) ntc driver: calibration scheme version is Line Fitting
I (357) ntc driver: Calibration Success
I (367) NTC demo: NTC temperature = 23.44 ℃
I (367) NTC demo: NTC temperature = 23.47 ℃
I (377) NTC demo: NTC temperature = 23.47 ℃
I (377) NTC demo: NTC temperature = 23.47 ℃
I (387) NTC demo: NTC temperature = 23.50 ℃
I (387) NTC demo: NTC temperature = 23.50 ℃
I (397) NTC demo: NTC temperature = 23.44 ℃
I (397) NTC demo: NTC temperature = 23.44 ℃
I (407) NTC demo: NTC temperature = 23.43 ℃
I (407) NTC demo: NTC temperature = 23.43 ℃
```

View File

@@ -0,0 +1,78 @@
# 温度传感器应用示例
[English Version](./README.md)
本示例演示了如何在 ESP32-C2 / ESP32-C3 / ESP32 / ESP32-C6 / ESP32-S3 系列芯片上使用 `ntc_driver` 组件开发一个热敏电阻传感器温度读取应用程序。具体演示的功能如下:
- 基于最底层驱动 API 的控制
- 基于热敏电阻 CMFA103J3950HANT 驱动的演示
- 可选择配置不同的热敏电阻驱动
CMFA103J3950HANT传感器接线图
```
ESP8684-DevKitM-1 CMFA103J3950HANT
--
[ADC1 CHANEL3] --------> | || NTC IO
--
```
## 如何使用该示例
### 硬件需求
1. 通过 `idf.py menuconfig` 选择需要演示的驱动,并进行驱动配置
2. 硬件连接:
- 对于 CMFA103J3950HANT 驱动,仅需要将信号端口连接到所配置的 GPIO 上。
### 编译和烧写
1. 进入 `**` 目录:
```linux
cd ./esp-iot-solution/examples/sensors/ntc_temperature_sensor
```
2. 使用 `idf.py` 工具设置编译芯片,随后编译下载,指令分别为:
```linux
# 设置编译芯片
idf.py set-target esp32c2
# 编译并下载
idf.py -p PORT build flash
```
请将 `PORT` 替换为当前使用的端口号
3. 可使用 `monitor` 查看程序输出,指令为:
```
idf.py -p PORT monitor
```
### 示例输出结果
以下为 CMFA103J3950HANT 驱动测试 log:
```log
I (333) app_start: Starting scheduler on CPU0
I (337) app_start: Starting scheduler on CPU1
I (337) main_task: Started on CPU0
I (347) main_task: Calling app_main()
I (347) ntc driver: IoT Ntc Driver Version: 0.1.0
I (347) ntc driver: calibration scheme version is Line Fitting
I (357) ntc driver: Calibration Success
I (367) NTC demo: NTC temperature = 23.44 ℃
I (367) NTC demo: NTC temperature = 23.47 ℃
I (377) NTC demo: NTC temperature = 23.47 ℃
I (377) NTC demo: NTC temperature = 23.47 ℃
I (387) NTC demo: NTC temperature = 23.50 ℃
I (387) NTC demo: NTC temperature = 23.50 ℃
I (397) NTC demo: NTC temperature = 23.44 ℃
I (397) NTC demo: NTC temperature = 23.44 ℃
I (407) NTC demo: NTC temperature = 23.43 ℃
I (407) NTC demo: NTC temperature = 23.43 ℃
```

View File

@@ -0,0 +1,2 @@
idf_component_register(SRCS "ntc_temperature_example_main.c"
INCLUDE_DIRS ".")

View File

@@ -0,0 +1,4 @@
dependencies:
idf: ">=5.0"
ntc_driver:
override_path: "../../../../components/sensors/ntc_driver"

View File

@@ -0,0 +1,38 @@
/*
* SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "ntc_driver.h"
const static char *TAG = "NTC demo";
void app_main(void)
{
//Select the NTC sensor and initialize the hardware parameters
ntc_config_t ntc_config = {
.b_value = 3950,
.r25_ohm = 10000,
.fixed_ohm = 10000,
.vdd_mv = 3300,
.circuit_mode = CIRCUIT_MODE_NTC_GND,
.atten = ADC_ATTEN_DB_11,
.channel = ADC_CHANNEL_3,
.unit = ADC_UNIT_1
};
//Create the NTC Driver and Init ADC
ntc_device_handle_t ntc = NULL;
adc_oneshot_unit_handle_t adc_handle = NULL;
ESP_ERROR_CHECK(ntc_dev_create(&ntc_config, &ntc, &adc_handle));
ESP_ERROR_CHECK(ntc_dev_get_adc_handle(ntc, &adc_handle));
float temp = 0.0;
for (int i = 0; i < 10; i++) {
if (ntc_dev_get_temperature(ntc, &temp) == ESP_OK) {
ESP_LOGI(TAG, "NTC temperature = %.2f ℃", temp);
}
}
ESP_ERROR_CHECK(ntc_dev_delete(ntc));
}

View File

@@ -0,0 +1,14 @@
dependencies:
cmake_utilities:
version: 0.*
idf:
version: '>=5.0'
description: ntc driver
documentation: https://docs.espressif.com/projects/esp-iot-solution/en/latest/sensors/ntc_driver.html
issues: https://github.com/espressif/esp-iot-solution/issues
repository: git://github.com/espressif/esp-iot-solution.git
repository_info:
commit_sha: be8a92bd151e3f0809ed73aef0c1a481b1c2fdc1
path: components/sensors/ntc_driver
url: https://github.com/espressif/esp-iot-solution/tree/master/components/sensors/ntc_driver
version: 0.3.0

View File

@@ -0,0 +1,94 @@
/*
* SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <stdlib.h>
#include "esp_log.h"
#include "esp_adc/adc_cali.h"
#include "esp_adc/adc_oneshot.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Supported circuit mode
*
*/
typedef enum {
CIRCUIT_MODE_NTC_VCC = 1, // Vcc --------> Rt --------> Rref --------> GND
CIRCUIT_MODE_NTC_GND = 2, // Vcc --------> Rref --------> Rt --------> GND
} ntc_circuit_mode_t;
/**
* @brief NTC config data type
*/
typedef struct {
ntc_circuit_mode_t circuit_mode; /*!< ntc circuit mode */
adc_unit_t unit; /*!< adc unit */
adc_atten_t atten; /*!< adc atten */
adc_channel_t channel; /*!< adc channel */
uint32_t b_value; /*!< beta value of NTC (K) */
uint32_t r25_ohm; /*!< 25℃ resistor value of NTC (K) */
uint32_t fixed_ohm; /*!< fixed resistor value (Ω) */
uint32_t vdd_mv; /*!< vdd voltage (mv) */
} ntc_config_t;
typedef void *ntc_device_handle_t;
/**
* @brief Initialize the NTC and ADC channel config
*
* @param config
* @param ntc_handle A ntc driver handle
* @param adc_handle A adc handle
*
* @return
* - ESP_OK Success
* - ESP_FAIL Failure
*/
esp_err_t ntc_dev_create(ntc_config_t *config, ntc_device_handle_t *ntc_handle, adc_oneshot_unit_handle_t *adc_handle);
/**
* @brief Get the adc handle
*
* @param ntc_handle A ntc driver handle
* @param adc_handle A adc handle
*
* @return
* - ESP_OK Success
* - ESP_FAIL Failure
*/
esp_err_t ntc_dev_get_adc_handle(ntc_device_handle_t ntc_handle, adc_oneshot_unit_handle_t *adc_handle);
/**
* @brief Delete ntc driver device and ntc detect device
*
* @param ntc_handle A ntc driver handle
*
* @return
* - ESP_OK Success
* - ESP_FAIL Failure
*/
esp_err_t ntc_dev_delete(ntc_device_handle_t ntc_handle);
/**
* @brief Get the ntc temperature
*
* @param ntc_handle A ntc driver handle
* @param temperature NTC temperature
*
* @return
* - ESP_OK Success
* - ESP_FAIL Failure
*
*/
esp_err_t ntc_dev_get_temperature(ntc_device_handle_t ntc_handle, float *temperature);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,206 @@
/*
* SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#include "esp_adc/adc_cali_scheme.h"
#include "ntc_driver.h"
#define NTC_DRIVER_CHECK(a, str, ret_val) \
if (!(a)) { \
ESP_LOGW(TAG, "%s:(%d): %s", __FUNCTION__, __LINE__, str);\
return (ret_val); \
}
#define NTC_DRIVER_CHECK_GOTO(a, str, label) \
if (!(a)) { \
ESP_LOGW(TAG, "%s:(%d): %s", __FUNCTION__, __LINE__, str);\
goto label; \
}
const static char *TAG = "ntc driver";
typedef struct ntc_driver {
ntc_config_t s_ntc_config;
adc_oneshot_unit_handle_t adc_handle;
adc_cali_handle_t adc_cali_handle;
} ntc_driver_dev_t;
static bool if_init_adc_unit = false;
static esp_err_t adc_calibration_init(adc_unit_t unit, adc_atten_t atten, adc_cali_handle_t *out_handle)
{
esp_err_t ret = ESP_FAIL;
#if ADC_CALI_SCHEME_CURVE_FITTING_SUPPORTED
ESP_LOGI(TAG, "calibration scheme version is %s", "Curve Fitting");
adc_cali_curve_fitting_config_t cali_config = {
.unit_id = unit,
.atten = atten,
.bitwidth = ADC_BITWIDTH_DEFAULT,
};
ret = adc_cali_create_scheme_curve_fitting(&cali_config, out_handle);
#endif
#if ADC_CALI_SCHEME_LINE_FITTING_SUPPORTED
ESP_LOGI(TAG, "calibration scheme version is %s", "Line Fitting");
adc_cali_line_fitting_config_t cali_config = {
.unit_id = unit,
.atten = atten,
.bitwidth = ADC_BITWIDTH_DEFAULT,
};
ret = adc_cali_create_scheme_line_fitting(&cali_config, out_handle);
#endif
if (ret == ESP_OK) {
ESP_LOGI(TAG, "Calibration Success");
} else if (ret == ESP_ERR_NOT_SUPPORTED) {
ESP_LOGW(TAG, "eFuse not burnt, skip software calibration");
} else {
ESP_LOGE(TAG, "Invalid arg or no memory");
}
return ret;
}
esp_err_t ntc_dev_create(ntc_config_t *config, ntc_device_handle_t *ntc_handle, adc_oneshot_unit_handle_t *adc_handle)
{
ESP_LOGI(TAG, "IoT Ntc Driver Version: %d.%d.%d", NTC_DRIVER_VER_MAJOR, NTC_DRIVER_VER_MINOR, NTC_DRIVER_VER_PATCH);
esp_err_t ret = ESP_OK;
if (ntc_handle == NULL || config == NULL) {
ESP_LOGW(TAG, "arg is invalid");
return ESP_ERR_INVALID_ARG;
}
ntc_driver_dev_t *ndd = (ntc_driver_dev_t *) calloc(1, sizeof(ntc_driver_dev_t));
if (ndd == NULL) {
ESP_LOGW(TAG, "Calloc device failed");
return ESP_ERR_NO_MEM;
}
ndd->s_ntc_config = *config;
if (adc_handle != NULL && *adc_handle != NULL) {
ndd->adc_handle = *adc_handle;
} else {
adc_oneshot_unit_init_cfg_t init_config1 = {
.unit_id = config->unit,
};
ret = adc_oneshot_new_unit(&init_config1, &ndd->adc_handle);
NTC_DRIVER_CHECK_GOTO(ret == ESP_OK, "adc oneshot new unit fail!", init_fail);
if_init_adc_unit = true;
if (adc_handle != NULL) {
*adc_handle = ndd->adc_handle;
}
}
adc_oneshot_chan_cfg_t channel_config = {
.bitwidth = ADC_BITWIDTH_DEFAULT,
.atten = config->atten,
};
ret = adc_oneshot_config_channel(ndd->adc_handle, config->channel, &channel_config);
NTC_DRIVER_CHECK_GOTO(ret == ESP_OK, "adc oneshot config channel fail!", init_fail);
ret = adc_calibration_init(config->unit, config->atten, &ndd->adc_cali_handle);
NTC_DRIVER_CHECK_GOTO(ret == ESP_OK, "adc calibration init fail!", init_fail);
*ntc_handle = (ntc_device_handle_t)ndd;
return ret;
init_fail:
if (if_init_adc_unit) {
adc_oneshot_del_unit(ndd->adc_handle);
}
free(ndd);
ndd = NULL;
return ret;
}
esp_err_t ntc_dev_get_adc_handle(ntc_device_handle_t ntc_handle, adc_oneshot_unit_handle_t *adc_handle)
{
esp_err_t ret = ESP_OK;
if (ntc_handle == NULL) {
ESP_LOGW(TAG, "Pointer of handle is invalid");
return ESP_ERR_INVALID_ARG;
}
ntc_driver_dev_t *ndd = (ntc_driver_dev_t *)ntc_handle;
*adc_handle = ndd->adc_handle;
return ret;
}
esp_err_t ntc_dev_delete(ntc_device_handle_t ntc_handle)
{
esp_err_t ret = ESP_OK;
if (ntc_handle == NULL) {
ESP_LOGW(TAG, "Pointer of handle is invalid");
return ESP_ERR_INVALID_ARG;
}
ntc_driver_dev_t *ndd = (ntc_driver_dev_t *)ntc_handle;
#if ADC_CALI_SCHEME_CURVE_FITTING_SUPPORTED
ret = adc_cali_delete_scheme_curve_fitting(ndd->adc_cali_handle);
NTC_DRIVER_CHECK(ret == ESP_OK, "adc curve calibration deinit fail", ESP_FAIL);
#endif
#if ADC_CALI_SCHEME_LINE_FITTING_SUPPORTED
ret = adc_cali_delete_scheme_line_fitting(ndd->adc_cali_handle);
NTC_DRIVER_CHECK(ret == ESP_OK, "adc line calibration deinit fail", ESP_FAIL);
#endif
if (if_init_adc_unit) {
ret = adc_oneshot_del_unit(ndd->adc_handle);
NTC_DRIVER_CHECK(ret == ESP_OK, "adc oneshot deinit fail", ESP_FAIL);
}
free(ndd);
ndd = NULL;
return ret;
}
static esp_err_t ntc_voltage_to_temperature(ntc_device_handle_t ntc_handle, uint32_t voltage_mv, float *temperature)
{
ntc_driver_dev_t *ndd = (ntc_driver_dev_t *)ntc_handle;
if (ndd->s_ntc_config.b_value && voltage_mv) {
uint32_t r_ntc_ohm = 0;
if (ndd->s_ntc_config.circuit_mode == CIRCUIT_MODE_NTC_VCC) {
r_ntc_ohm = (ndd->s_ntc_config.vdd_mv - voltage_mv) * ndd->s_ntc_config.fixed_ohm / voltage_mv;
} else if (ndd->s_ntc_config.circuit_mode == CIRCUIT_MODE_NTC_GND) {
r_ntc_ohm = voltage_mv * ndd->s_ntc_config.fixed_ohm / (ndd->s_ntc_config.vdd_mv - voltage_mv);
}
*temperature = 1.0 / (log(1.0 * r_ntc_ohm / ndd->s_ntc_config.r25_ohm) * 1.0 / ndd->s_ntc_config.b_value + 1.0 / 298.15) - 273.0;
return ESP_OK;
}
return ESP_FAIL;
}
esp_err_t ntc_dev_get_temperature(ntc_device_handle_t ntc_handle, float *temperature)
{
int voltage, adc_raw = 0;
if (ntc_handle == NULL) {
ESP_LOGW(TAG, "Pointer of handle is invalid");
return ESP_ERR_INVALID_ARG;
}
ntc_driver_dev_t *ndd = (ntc_driver_dev_t *)ntc_handle;
esp_err_t ret = adc_oneshot_read(ndd->adc_handle, ndd->s_ntc_config.channel, &adc_raw);
NTC_DRIVER_CHECK(ret == ESP_OK, "adc oneshot read fail", ESP_FAIL);
NTC_DRIVER_CHECK(adc_raw != 0, "adc raw data equal to 0", ESP_FAIL);
ret = adc_cali_raw_to_voltage(ndd->adc_cali_handle, adc_raw, &voltage);
NTC_DRIVER_CHECK(ret == ESP_OK, "adc calibration raw to voltage fail", ESP_FAIL);
NTC_DRIVER_CHECK(voltage != 0, "voltage equal to 0", ESP_FAIL);
ntc_voltage_to_temperature(ndd, voltage, temperature);
return ESP_OK;
}

View File

@@ -0,0 +1,9 @@
# The following lines of boilerplate have to be in your project's CMakeLists
# in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.5)
set(EXTRA_COMPONENT_DIRS "$ENV{IDF_PATH}/tools/unit-test-app/components"
"../../ntc_driver")
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(ntc_driver_test)

View File

@@ -0,0 +1,3 @@
idf_component_register(SRC_DIRS "."
PRIV_INCLUDE_DIRS "."
PRIV_REQUIRES unity ntc_driver)

View File

@@ -0,0 +1,73 @@
/*
* SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "soc/soc_caps.h"
#include "unity.h"
#include "ntc_driver.h"
#define TEST_MEMORY_LEAK_THRESHOLD (-460)
const static char *TAG = "NTC_DRIVER_TEST";
static size_t before_free_8bit;
static size_t before_free_32bit;
TEST_CASE("test_ntc_driver", "[ntc_driver]")
{
ntc_config_t ntc_config = {
.b_value = 3950,
.r25_ohm = 10000,
.fixed_ohm = 10000,
.vdd_mv = 3300,
.circuit_mode = CIRCUIT_MODE_NTC_GND,
.atten = ADC_ATTEN_DB_11,
.channel = ADC_CHANNEL_3,
.unit = ADC_UNIT_1
};
ntc_device_handle_t ntc = NULL;
adc_oneshot_unit_handle_t adc_handle = NULL;
ESP_ERROR_CHECK(ntc_dev_create(&ntc_config, &ntc, &adc_handle));
ESP_ERROR_CHECK(ntc_dev_get_adc_handle(ntc, &adc_handle));
float temp = 0.0;
for (int i = 0; i < 10; i++) {
if (ntc_dev_get_temperature(ntc, &temp) == ESP_OK) {
ESP_LOGI(TAG, "NTC temperature = %.2f ℃", temp);
}
}
ESP_ERROR_CHECK(ntc_dev_delete(ntc));
}
static void check_leak(size_t before_free, size_t after_free, const char *type)
{
ssize_t delta = after_free - before_free;
printf("MALLOC_CAP_%s: Before %u bytes free, After %u bytes free (delta %d)\n", type, before_free, after_free, delta);
TEST_ASSERT_MESSAGE(delta >= TEST_MEMORY_LEAK_THRESHOLD, "memory leak");
}
void setUp(void)
{
before_free_8bit = heap_caps_get_free_size(MALLOC_CAP_8BIT);
before_free_32bit = heap_caps_get_free_size(MALLOC_CAP_32BIT);
}
void tearDown(void)
{
size_t after_free_8bit = heap_caps_get_free_size(MALLOC_CAP_8BIT);
size_t after_free_32bit = heap_caps_get_free_size(MALLOC_CAP_32BIT);
check_leak(before_free_8bit, after_free_8bit, "8BIT");
check_leak(before_free_32bit, after_free_32bit, "32BIT");
}
void app_main(void)
{
printf("NTC DRIVER TEST \n");
unity_run_menu();
}

View File

@@ -0,0 +1,41 @@
# SPDX-FileCopyrightText: 2024Espressif Systems (Shanghai) CO LTD
# SPDX-License-Identifier: Apache-2.0
'''
Steps to run these cases:
- Build
- . ${IDF_PATH}/export.sh
- pip install idf_build_apps
- python tools/build_apps.py components/sensors/ntc_driver/test_apps -t esp32
- Test
- pip install -r tools/requirements/requirement.pytest.txt
- pytest components/sensors/ntc_driver/test_apps --target esp32
'''
import pytest
from pytest_embedded import Dut
@pytest.mark.target('esp32')
@pytest.mark.target('esp32c3')
@pytest.mark.target('esp32c6')
@pytest.mark.target('esp32s3')
@pytest.mark.env('generic')
@pytest.mark.parametrize(
'config',
[
'defaults',
],
)
def test_ntc_driver(dut: Dut)-> None:
dut.run_all_single_board_cases()
@pytest.mark.target('esp32c2')
@pytest.mark.env('xtal_26mhz')
@pytest.mark.parametrize(
'config , baud',
[
('c2_xtal_26mhz', '74880'),
],
)
def test_ntc_driver_esp32c2(dut: Dut)-> None:
dut.run_all_single_board_cases()