[Diao Ye Learns Programming] MicroPython Manual ESP32 Specific Port Library esp32.raw_temperature()

Insert image description here

MicroPython is a lightweight version of the interpreter designed for running the Python 3 programming language in embedded systems. Compared with regular Python, the MicroPython interpreter is small (only about 100KB) and is compiled into a binary Executable file to run, resulting in higher execution efficiency. It uses a lightweight garbage collection mechanism and removes most of the Python standard library to accommodate resource-constrained microcontrollers.

The main features of MicroPython include:
1. The syntax and functions are compatible with standard Python, making it easy to learn and use. Supports most core syntax of Python.
2. Directly access and control hardware, control GPIO, I2C, SPI, etc. like Arduino.
3. Powerful module system, providing file system, network, graphical interface and other functions.
4. Support cross-compilation to generate efficient native code, which is 10-100 times faster than the interpreter.
5. The amount of code is small and the memory usage is small. It is suitable for running on MCU and development boards with small memory.
6. Open source license, free to use. The Shell interactive environment provides convenience for development and testing.
7. The built-in I/O driver supports a large number of microcontroller platforms, such as ESP8266, ESP32, STM32, micro:bit, control board and PyBoard, etc. There is an active community.

MicroPython application scenarios include:
1. Rapidly build prototypes and user interactions for embedded products.
2. Make some small programmable hardware projects.
3. As an educational tool, it helps beginners learn Python and IoT programming.
4. Build smart device firmware to achieve advanced control and cloud connectivity.
5. Various microcontroller applications such as Internet of Things, embedded intelligence, robots, etc.

Things to note when using MicroPython:
1. Memory and Flash space are limited.
2. The explanation and execution efficiency is not as good as C language.
3. Some library functions are different from the standard version.
4. Optimize the syntax for the platform and correct the differences with standard Python.
5. Use memory resources rationally and avoid frequently allocating large memory blocks.
6. Use native code to improve the performance of speed-critical parts.
7. Use abstraction appropriately to encapsulate underlying hardware operations.

Generally speaking, MicroPython brings Python into the field of microcontrollers, which is an important innovation that not only lowers the programming threshold but also provides good hardware control capabilities. It is very suitable for the development of various types of Internet of Things and intelligent hardware.
Insert image description here

MicroPython's esp refers to the MicroPython firmware and related software libraries for ESP8266 and ESP32 chips. ESP8266 and ESP32 are a class of low-cost, low-power Wi-Fi and Bluetooth modules widely used in IoT and embedded systems. MicroPython's esp provides an advanced scripting environment for both chips, allowing developers to use the Python language for rapid prototyping and development.

ESP8266: It is a low-cost, low-power Wi-Fi module/chip developed by Espressif Systems. It has a built-in TCP/IP protocol stack, can be used to connect to the Internet, and has strong processing capabilities. MicroPython's esp provides firmware and related software libraries for ESP8266, allowing developers to use MicroPython language to develop ESP8266 applications.

ESP32: It is a highly integrated Wi-Fi and Bluetooth module/chip launched by Espressif Systems. Compared with ESP8266, it has more powerful processing power, more peripheral interfaces and more memory. MicroPython's esp also provides firmware and related software libraries for ESP32, allowing developers to use MicroPython language to develop ESP32 applications.

MicroPython's esp firmware: It is a MicroPython firmware version specifically for ESP8266 and ESP32 chips. These firmwares have been specifically optimized to run on ESP8266 and ESP32, and provide APIs for hardware interaction, network communication, and peripheral control.

Software libraries: MicroPython's esp also provides a series of software libraries related to ESP8266 and ESP32 hardware to simplify and accelerate the development process. These software libraries provide a rich set of functional interfaces, covering commonly used hardware and communication protocols such as Wi-Fi, Bluetooth, GPIO (General Purpose Input and Output), I2C, SPI, and PWM, allowing developers to easily access and control hardware resources.
Insert image description here
MicroPython's esp32.raw_temperature() is a function used to read the raw value of the ESP32's internal temperature sensor. This function returns an integer representing the output voltage of the temperature sensor in millivolts. This function does not require any parameters.

The main features of MicroPython's esp32.raw_temperature() are:

ESP32 can measure its own chip temperature without an external temperature sensor to monitor the chip's working status and heat dissipation.
The original value can be converted into Kelvin, Celsius or Fahrenheit and temperature controlled or displayed according to different application scenarios.
Can be used in combination with other modules or functions to implement a variety of temperature-related applications.

The application scenarios of MicroPython's esp32.raw_temperature() include:

Case 1: Temperature display: Using ESP32 development board, OLED display and other components, MicroPython's esp32.raw_temperature() function is used to implement a temperature display. The temperature of the ESP32 chip can be displayed on the OLED display and based on the user's selection. Switch between different temperature units. Here are some code examples::

# 导入 esp32 模块
import esp32
# 导入 OLED 模块
import ssd1306
# 导入按键模块
from machine import Pin

# 定义 OLED 引脚号和尺寸
OLED_SCL_PIN = 22
OLED_SDA_PIN = 21
OLED_WIDTH = 128
OLED_HEIGHT = 64

# 定义按键引脚号和状态
KEY_PIN = 4
KEY_ON = 0
KEY_OFF = 1

# 创建 OLED 对象并初始化
oled = ssd1306.SSD1306_I2C(OLED_WIDTH, OLED_HEIGHT, machine.I2C(scl=machine.Pin(OLED_SCL_PIN), sda=machine.Pin(OLED_SDA_PIN)))
oled.fill(0)
oled.text("Temperature Display", 0 ,0)
oled.show()

# 创建按键对象并初始化,设置为上拉输入模式,并注册中断回调函数,触发方式为下降沿(按下)
key = Pin(KEY_PIN, Pin.IN, Pin.PULL_UP)
key.irq(lambda pin: change_unit(), trigger=Pin.IRQ_FALLING)

# 定义一个全局变量,用于存储当前的温度单位,初始值为摄氏度(C)
unit = "C"

# 定义一个函数,用于读取 ESP32 内部温度传感器的原始值,并转换为不同的温度单位
def read_temp():
    global unit
    # 调用 esp32.raw_temperature() 函数,获取原始值(单位为毫伏)
    raw = esp32.raw_temperature()
    # 根据当前的温度单位,将原始值转换为对应的温度值(单位为开尔文、摄氏或华氏)
    if unit == "K":
        # 原始值除以 10 得到开尔文温度(单位为 K)
        temp = raw / 10
    elif unit == "C":
        # 原始值除以 10 减去 273.15 得到摄氏温度(单位为 C)
        temp = raw / 10 - 273.15
    elif unit == "F":
        # 原始值除以 10 减去 273.15 再乘以 1.8 加上 32 得到华氏温度(单位为 F)
        temp = (raw / 10 - 273.15) * 1.8 + 32
    else:
        return None
    # 返回转换后的温度值和单位字符串
    return "{:.2f} {}".format(temp, unit)

# 定义一个函数,用于在 OLED 上显示 ESP32 芯片的温度,并根据用户的选择来切换不同的温度单位
def show_temp():
    # 调用 read_temp 函数,获取温度值和单位字符串
    temp_str = read_temp()
    # 在 OLED 上显示温度字符串
    oled.fill(0)
    oled.text("Temperature Display", 0 ,0)
    oled.text(temp_str, 32 ,16)
    oled.show()

# 定义一个函数,用于切换温度单位,并重新显示温度
def change_unit():
    global unit
    # 根据当前的温度单位,切换到下一个温度单位(K -> C -> F -> K)
    if unit == "K":
        unit = "C"
    elif unit == "C":
        unit = "F"
    elif unit == "F":
        unit = "K"
    else:
        return
    # 调用 show_temp 函数,重新显示温度
    show_temp()

# 定义一个循环,用于调用 show_temp 函数,并延迟一秒钟
while True:
    show_temp()
    time.sleep(1)

Case 2: Temperature control: Using the ESP32 development board, fans and other components, MicroPython's esp32.raw_temperature() function is used to implement a temperature control. The fan speed can be controlled based on the temperature of the ESP32 chip to achieve heat dissipation of the chip. Here are some code examples::

# 导入 esp32 模块
import esp32
# 导入风扇模块
from machine import PWM

# 定义风扇引脚号和频率
FAN_PIN = 5
FAN_FREQ = 1000

# 创建风扇对象并初始化,设置为 PWM(脉冲宽度调制)输出模式,并设置频率和占空比
fan = PWM(Pin(FAN_PIN))
fan.freq(FAN_FREQ)
fan.duty(0)

# 定义一个函数,用于根据 ESP32 芯片的温度来控制风扇的转速
def fan_control():
    # 调用 esp32.raw_temperature() 函数,获取原始值(单位为毫伏)
    raw = esp32.raw_temperature()
    # 将原始值除以 10 得到开尔文温度(单位为 K)
    temp = raw / 10
    # 根据开尔文温度的大小,设置不同的风扇占空比(越高越快)
    if temp < 300:
        # 如果温度低于 300 K,则设置占空比为零(关闭风扇)
        fan.duty(0)
    elif temp < 310:
        # 如果温度在 300-310 K 之间,则设置占空比为 256(低速)
        fan.duty(256)
    elif temp < 320:
        # 如果温度在 310-320 K 之间,则设置占空比为 512(中速)
        fan.duty(512)
    else:
        # 如果温度高于 320 K,则设置占空比为 1023(高速)
        fan.duty(1023)

# 定义一个循环,用于调用 fan_control 函数,并延迟一秒钟
while True:
    fan_control()
    time.sleep(1)

Case 3: Temperature recording: Use ESP32 development board, SD card and other components, and use MicroPython's esp32.raw_temperature() function to implement a temperature record. The temperature of the ESP32 chip can be read regularly and saved to text in the SD card. file to achieve the temperature history record of the chip. Here are some code examples:

# 导入 esp32 模块
import esp32
# 导入 SD 卡模块
import sdcard
# 导入 os 模块
import os

# 定义 SD 卡引脚号和文件名
SD_CS_PIN = 15 # 片选引脚号
SD_SCK_PIN = 14 # 时钟引脚号
SD_MOSI_PIN = 13 # 主机输出从机输入引脚号
SD_MISO_PIN = 12 # 主机输入从机输出引脚号
FILE_NAME = "temp.txt" # 文件名

# 创建 SD 卡对象并初始化,设置为 SPI 模式,并挂载到 /sd 目录下
sd = sdcard.SDCard(machine.SPI(1, sck=machine.Pin(SD_SCK_PIN), mosi=machine.Pin(SD_MOSI_PIN), miso=machine.Pin(SD_MISO_PIN)), machine.Pin(SD_CS_PIN))
os.mount(sd, "/sd")

# 定义一个函数,用于读取 ESP32 内部温度传感器的原始值,并转换为摄氏温度
def read_temp():
    # 调用 esp32.raw_temperature() 函数,获取原始值(单位为毫伏)
    raw = esp32.raw_temperature()
    # 将原始值除以 10 减去 273.15 得到摄氏温度(单位为 C)
    temp = raw / 10 - 273.15
    # 返回摄氏温度值
    return temp

# 定义一个函数,用于将 ESP32 芯片的温度保存到 SD 卡中的文本文件中,并附加时间戳
def save_temp():
    # 调用 read_temp 函数,获取摄氏温度值
    temp = read_temp()
    # 调用 time.localtime 函数,获取当前的时间元组(年,月,日,时,分,秒)
    t = time.localtime()
    # 将时间元组转换为字符串格式(年-月-日 时:分:秒)
    t_str = "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(*t)
    # 将温度值和时间字符串拼接成一行数据,并在末尾加上换行符(\n)
    data = "{:.2f} C, {}\n".format(temp, t_str)
    # 打开 SD 卡中的文本文件,以追加模式(a)写入数据,并关闭文件
    f = open("/sd/" + FILE_NAME, "a")
    f.write(data)
    f.close()

# 定义一个循环,用于每隔一分钟调用 save_temp 函数,并进入浅睡眠模式,等待下一次唤醒
while True:
    save_temp()
    machine.sleep(60000) # 睡眠一分钟(60000 毫秒)

Case 4: Get temperature value

import esp32

temp = esp32.raw_temperature() 
print(temp)

Print out temperature readings directly.

Case 5: Temperature monitoring

import esp32, time

while True:
  temp = esp32.raw_temperature()
  if temp > 30:
    print('Temperature too high!')
  time.sleep(60)

Check the temperature periodically and alarm when the temperature is too high.

Case 6: Temperature compensation:

import esp32

def compensate(raw):
  return raw / 0.01 + 25 

temp = compensate(esp32.raw_temperature())
print(temp)

The raw temperature reading obtained by radiation is converted to obtain the compensated temperature.

These examples show how to obtain the raw temperature value of the ESP32's built-in temperature sensor and process it.

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_41659040/article/details/132917191