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

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.hall_sensor() is a function used to read the raw value of the ESP32's built-in Hall effect sensor. This function returns an integer representing the output voltage of the Hall effect sensor in millivolts. This function does not require any parameters.

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

ESP32 can detect changes in the magnetic field around it without the need for an external Hall effect sensor, thereby realizing the magnetic field sensing function.
The original value can be converted into magnetic flux density or magnetic induction intensity according to different application scenarios, and the magnetic field can be controlled or displayed.
Can be used in combination with other modules or functions to implement a variety of magnetic field-related applications.

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

Case 1: Magnetic field display: Use ESP32 development board, OLED display and other components, and use MicroPython's esp32.hall_sensor() function to implement a magnetic field display. The magnetic field intensity around ESP32 can be displayed on the OLED display and based on the user's selection to switch between different magnetic field 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("Magnetic Field Display", 0 ,0)
oled.show()

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

# 定义一个全局变量,用于存储当前的磁场单位,初始值为特斯拉(T)
unit = "T"

# 定义一个函数,用于读取 ESP32 内置霍尔效应传感器的原始值,并转换为不同的磁场单位
def read_mf():
    global unit
    # 调用 esp32.hall_sensor() 函数,获取原始值(单位为毫伏)
    raw = esp32.hall_sensor()
    # 根据当前的磁场单位,将原始值转换为对应的磁通量密度或磁感应强度(单位为特斯拉、高斯或奥斯特)
    if unit == "T":
        # 原始值乘以 1.4e-6 得到特斯拉(单位为 T)
        mf = raw * 1.4e-6
    elif unit == "G":
        # 原始值乘以 1.4e-2 得到高斯(单位为 G)
        mf = raw * 1.4e-2
    elif unit == "O":
        # 原始值乘以 1.75e-5 得到奥斯特(单位为 O)
        mf = raw * 1.75e-5
    else:
        return None
    # 返回转换后的磁场值和单位字符串
    return "{:.2f} {}".format(mf, unit)

# 定义一个函数,用于在 OLED 上显示 ESP32 周围的磁场强度,并根据用户的选择来切换不同的磁场单位
def show_mf():
    # 调用 read_mf 函数,获取磁场值和单位字符串
    mf_str = read_mf()
    # 在 OLED 上显示磁场字符串
    oled.fill(0)
    oled.text("Magnetic Field Display", 0 ,0)
    oled.text(mf_str, 32 ,16)
    oled.show()

# 定义一个函数,用于切换磁场单位,并重新显示磁场
def change_unit():
    global unit
    # 根据当前的磁场单位,切换到下一个磁场单位(T -> G -> O -> T)
    if unit == "T":
        unit = "G"
    elif unit == "G":
        unit = "O"
    elif unit == "O":
        unit = "T"
    else:
        return
    # 调用 show_mf 函数,重新显示磁场
    show_mf()

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

Case 2: Magnetic field control: Use the ESP32 development board, electromagnets, LED lights and other components, and use MicroPython's esp32.hall_sensor() function to implement a magnetic field control. The electromagnet switch can be controlled according to the magnetic field strength around the ESP32, thus achieving Magnetic adsorption function. Here are some code examples:

# 导入 esp32 模块
import esp32
# 导入电磁铁模块
from machine import Pin
# 导入 LED 灯模块
from machine import PWM

# 定义霍尔效应传感器引脚号和阈值
HALL_PIN = 36
HALL_THRESHOLD = 500

# 定义电磁铁引脚号和状态
MAGNET_PIN = 4
MAGNET_ON = 1
MAGNET_OFF = 0

# 定义 LED 灯引脚号和频率
LED_PIN = 2
LED_FREQ = 1000

# 创建 ADC 对象并初始化,设置为输入模式,并设置分辨率和衰减
adc = ADC(Pin(HALL_PIN))
adc.atten(ADC.ATTN_11DB)
adc.width(ADC.WIDTH_12BIT)

# 创建电磁铁对象并初始化,设置为输出模式,并设置初始状态为关闭
magnet = Pin(MAGNET_PIN, Pin.OUT)
magnet.value(MAGNET_OFF)

# 创建 LED 灯对象并初始化,设置为 PWM(脉冲宽度调制)输出模式,并设置频率和占空比
led = PWM(Pin(LED_PIN))
led.freq(LED_FREQ)
led.duty(0)

# 定义一个函数,用于根据 ESP32 周围的磁场强度来控制电磁铁的开关,并显示 LED 灯的状态
def magnet_control():
    # 读取 ADC 的值,并将其映射到 0-1023 的范围
    value = adc.read()
    value = int(value * 1023 / 4095)
    # 如果值小于阈值,则表示周围的磁场强度低于设定值,打开电磁铁,吸附金属物体
    if value < HALL_THRESHOLD:
        magnet.value(MAGNET_ON)
        # 设置 LED 灯的占空比为最大(1023),亮起 LED 灯
        led.duty(1023)
    # 如果值大于等于阈值,则表示周围的磁场强度高于或等于设定值,关闭电磁铁,释放金属物体
    else:
        magnet.value(MAGNET_OFF)
        # 设置 LED 灯的占空比为零(0),熄灭 LED 灯
        led.duty(0)

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

This program uses the Hall effect sensor 1 built into the ESP32, which can detect changes in the magnetic field around it and control the switch of the electromagnet according to the set threshold. At the same time, LED lights are used to display the status of the electromagnet.

Case 3: Magnetic field detection: Use ESP32 development board, buzzer and other components, and use MicroPython's esp32.hall_sensor() function to implement a magnetic field detection. The tone of the buzzer can be controlled according to the magnetic field strength around the ESP32, thereby realizing the magnetic field. sound prompt. Here are some code examples:

# 导入 esp32 模块
import esp32
# 导入蜂鸣器模块
from machine import Pin
from machine import PWM

# 定义蜂鸣器引脚号和频率
BUZZER_PIN = 5
BUZZER_FREQ = 1000

# 创建蜂鸣器对象并初始化,设置为 PWM(脉冲宽度调制)输出模式,并设置频率和占空比
buzzer = PWM(Pin(BUZZER_PIN))
buzzer.freq(BUZZER_FREQ)
buzzer.duty(0)

# 定义一个函数,用于根据 ESP32 周围的磁场强度来控制蜂鸣器的音调
def buzzer_control():
    # 调用 esp32.hall_sensor() 函数,获取原始值(单位为毫伏)
    raw = esp32.hall_sensor()
    # 将原始值映射到 100-2000 的范围,作为蜂鸣器的频率(单位为赫兹)
    freq = int(raw * 1900 / 1023 + 100)
    # 设置蜂鸣器的频率和占空比(50%)
    buzzer.freq(freq)
    buzzer.duty(512)

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

This program makes use of the Hall effect sensor built into the ESP32, which can detect changes in the magnetic field around it and control the frequency of the buzzer based on the original value.

Case 4: Detecting magnetic field changes

import esp32

while True:
  print(esp32.hall_sensor()) 
  # 输出磁场读数

Continuously reading the magnetic field sensor value can detect changes in the magnetic field.

Case 5: Door magnetic sensor:

import esp32

THRESHOLD = 10

def check_door_state():
  value = esp32.hall_sensor()
  if value > THRESHOLD:
    print('Door opened!')
  else:
    print('Door closed!')
      
check_door_state()

Determine whether the door is open through the reading of the door sensor.

Case 6: Speaker control

import esp32

def beep(duration):
  # 打开喇叭 
  esp32.hall_sensor() # 重置计数器
  while esp32.hall_sensor() < 40 * duration:
    pass
  # 关闭喇叭
    
beep(1) # 蜂鸣1秒  

Use magnetic field counting to implement simple buzzer control. These examples show the use of hall sensors in magnetic field detection, sensor input, etc.

Case 7: Monitoring magnetic field strength:

import esp32
import time

while True:
    hall_value = esp32.hall_sensor()
    print("Hall Sensor Value:", hall_value)
    time.sleep(1)

In this example, we use an infinite loop to continuously monitor the value of the Hall sensor. By calling the esp32.hall_sensor() function, we can get the current Hall sensor value. Print it out and use the time.sleep(1) function to delay reading the sensor value again after one second.

Case 8: Magnetic field trigger operation::

import esp32
import machine

# 配置外部引脚触发
trigger_pin = machine.Pin(4, machine.Pin.IN, machine.Pin.PULL_DOWN)

while True:
    if trigger_pin.value() == 1:
        hall_value = esp32.hall_sensor()
        print("Hall Sensor Value:", hall_value)

In this example, we configured an external pin (Pin 4) as a trigger pin and connected it to a trigger (such as a button). In an infinite loop, we check the status of the trigger pin. When the value of the trigger pin is 1 (high level), we call the esp32.hall_sensor() function to get the current Hall sensor value and print it out.

Case 9: Magnetic field trigger task::

import esp32
import machine

# 配置外部引脚触发
trigger_pin = machine.Pin(4, machine.Pin.IN, machine.Pin.PULL_DOWN)

while True:
    if trigger_pin.value() == 1:
        hall_value = esp32.hall_sensor()
        if hall_value > 1000:
            print("Magnetic field detected!")
            # 执行其他任务...

In this example, we configured an external pin (Pin 4) as a trigger pin and connected it to a trigger (such as a button). In an infinite loop, we check the status of the trigger pin. When the value of the trigger pin is 1 (high level), we call the esp32.hall_sensor() function to get the current Hall sensor value. If the value of the Hall sensor is greater than 1000, it means that a magnetic field is detected, and we can perform other tasks, such as printing out the message "Magnetic field detected!" or performing other related operations.

These examples show how to use the esp32.hall_sensor() function in MicroPython to read the value of a Hall sensor and perform the corresponding tasks as needed. Please make appropriate settings and parameter adjustments based on your specific needs and hardware connections.

Insert image description here

Guess you like

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