[Diaoye learns programming] MicroPython manual built-in module umount

Insert image description here

MicroPython is a lightweight version of the interpreter designed to run 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 of Python's core syntax.
2. Directly access and control the hardware, control GPIO, I2C, SPI, etc. like Arduino.
3. A powerful module system that provides functions such as file system, network, and graphical interface.
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, which 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.

The application scenarios of MicroPython include:
1. Quickly 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.

Pay attention to the following when using MicroPython:
1. The 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 built-in module os provides some basic operating system services, including file system access and management. Among them, os.umount(mount_point) is a function used to unmount the file system. Its main features, application scenarios, and matters needing attention are as follows:

Main features: os.umount(mount_point) accepts a string parameter mount_point, which indicates the mount point of the file system to be unmounted. If mount_point does not exist, or mount_point is not mounted by any file system, then os.umount(mount_point) will throw an exception 1. During the process of unmounting the file system, the umount() method of the file system object will be called.

Application scenario: os.umount(mount_point) can be used to unmount unnecessary file systems in the file system. For example, you can use os.umount(mount_point) to unmount a FAT file system on an SD card, or unmount a Littlefs file system on a custom block device.

Things to note: Before using os.umount(mount_point), you need to import this module and use the import os statement. When using os.umount(mount_point), you need to be aware that it may affect the performance and compatibility of the file system, because file systems of different types and sources may have different characteristics and limitations. In addition, os.umount(mount_point) may have different implementation and support on different platforms. Therefore, when using os.umount(mount_point), it is best to check the platform's characteristics and limitations first.

The following are several practical application examples of MicroPython's built-in module os.umount(mount_point):

Case 1: Uninstall the FAT file system mounted under the root directory (/) on the MicroPython board, and print out the uninstallation success message. code show as below:

import os

# 定义要卸载文件系统的挂载点
mount_point = '/'

# 卸载文件系统
os.umount(mount_point)

# 打印卸载成功信息
print('File system unmounted from', mount_point)

Case 2: Unmount the FAT file system on the SD card mounted in the /sd directory on the MicroPython board and capture possible exceptions. code show as below:

import os

# 定义要卸载文件系统的挂载点
mount_point = '/sd'

# 尝试卸载文件系统,并捕获异常
try:
    # 卸载文件系统
    os.umount(mount_point)
    # 打印卸载成功信息
    print('File system unmounted from', mount_point)
except OSError as e:
    # 打印异常信息
    print('Failed to unmount file system from', mount_point, ':', e)

Case 3: Define a function on the MicroPython board to enter a command on the console and execute it. If the command is 'umount', call os.umount(mount_point) to unmount the specified file system. code show as below:

import os

# 定义一个函数,用于在控制台输入一个命令并执行
def run_command():
    # 获取用户输入的命令
    cmd = input('Enter a command: ')
    # 如果命令是'umount'
    if cmd.startswith('umount'):
        # 分割命令和参数
        args = cmd.split()
        # 如果参数个数为1
        if len(args) == 1:
            # 打印缺少参数信息
            print('Missing mount point')
        # 如果参数个数为2
        elif len(args) == 2:
            # 获取要卸载文件系统的挂载点
            mount_point = args[1]
            # 尝试卸载文件系统,并捕获异常
            try:
                # 卸载文件系统
                os.umount(mount_point)
                # 打印卸载成功信息
                print('File system unmounted from', mount_point)
            except OSError as e:
                # 打印异常信息
                print('Failed to unmount file system from', mount_point, ':', e)
        # 如果参数个数大于2
        else:
            # 打印多余参数信息
            print('Too many arguments')
    # 如果命令是'exit'
    elif cmd == 'exit':
        # 退出函数
        return
    # 其他情况
    else:
        # 尝试执行命令,并捕获异常
        try:
            exec(cmd)
        except Exception as e:
            # 打印异常信息
            print(e)
    # 递归调用函数
    run_command()

Case 4: Unmount the SD card:

import machine
import uos
import sdcard
import mount

# 初始化SD卡
spi = machine.SPI(1, baudrate=10000000, polarity=0, phase=0)
sd = sdcard.SDCard(spi, machine.Pin(4))
uos.mount(sd, "/sd")

# 在SD卡上创建文件
with open("/sd/data.txt", "w") as file:
    file.write("Hello, SD card!")

# 卸载SD卡
uos.umount("/sd")

In this example, we initialize the SD card using the SPI class of the machine module and connect it with the SPI interface using the SDCard class of the sdcard module. Then, we use the mount function of the mount module to mount the SD card to the specified path in the file system ("/sd" in this example). Next, we create a file on the SD card and write some content. Finally, we use the umount function of the uos module to unmount the SD card. By using the umount function, we can safely unmount the SD card, ensuring data integrity.

Case 5: Unmount the network file system:

import uos
import network
import mount

# 连接到WiFi网络
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect("my_wifi_network", "my_wifi_password")

# 等待WiFi连接成功
while not wifi.isconnected():
    pass

# 获取网络文件系统的IP地址
ip_address = wifi.ifconfig()[0]

# 挂载网络文件系统
uos.mount("smb://" + ip_address + "/shared_folder", "/mnt")

# 在网络文件系统上读取文件
with open("/mnt/data.txt", "r") as file:
    content = file.read()

# 打印文件内容
print(content)

# 卸载网络文件系统
uos.umount("/mnt")

In this example, we use the WLAN class of the network module to connect to the WiFi network and wait for the connection to succeed. Then, we use the wifi.ifconfig() function to obtain the IP address of the network file system. Next, we use the mount function of the mount module to mount the network file system to the specified path of the file system (in this example, "/mnt"). We then read a file on the network file system and print out its contents. Finally, we use the umount function of the uos module to unmount the network file system. By using the umount function, we can safely unmount the network file system to ensure data integrity.

Case 6: Uninstall the flash memory chip:

import machine
import uos
import flashbdev
import mount

# 初始化闪存芯片
flash = machine.SPI(0, baudrate=10000000, polarity=0, phase=0)
flash_cdev = flashbdev.FlashBdev(flash)

# 挂载闪存芯片
uos.mount(flash_cdev, "/flash")

# 在闪存芯片上创建文件
with open("/flash/data.txt", "w") as file:
    file.write("Hello, Flash chip!")

# 卸载闪存芯片
uos.umount("/flash")

In this example, we initialize the flash chip using the SPI class of the machine module and connect it with the SPI interface using the FlashBdev class of the flashbdev module. Then, we use the mount function of the mount module to mount the flash chip to the specified path in the file system ("/flash" in this example). Next, we create a file on the flash chip and write some content. Finally, we use the umount function of the uos module to unmount the flash chip. By using the umount function, we can safely unmount the flash memory chip, ensuring data integrity.

Case 7: Unmount the mounted SD card

import uos

# 卸载已挂载的SD卡
uos.umount("/sd")

In this example, we use the uos.umount() function to unmount the SD card file system that has been mounted to the path "/sd". In this way, the SD card will be removed from the MicroPython device and can no longer be accessed and operated on.

Case 8: Uninstall the mounted external Flash memory

import uos

# 卸载已挂载的外部Flash存储器
uos.umount("/flash")

In this example, we use the uos.umount() function to unmount the external Flash memory file system that has been mounted to the path "/flash". In this way, the external Flash memory is removed from the MicroPython device and can no longer be accessed and manipulated.

Case 9: Remounting the file system after unmounting it

import uos

# 卸载已挂载的文件系统
uos.umount("/sd")

# 执行其他操作...

# 重新挂载文件系统到指定路径
uos.mountsd("/sd")

In this example, we first use the uos.umount() function to unmount the mounted file system, and then after performing other operations, re-mount the SD card file system to the path "/sd" through the uos.mountsd() function . This way, the file system can be unmounted and remounted when needed.

These cases demonstrate the practical application of the umount function in the uos module, including unmounting the mounted SD card, unmounting the mounted external Flash storage, and remounting the file system after unmounting it. By using the umount function, you can easily unmount a mounted file system on a MicroPython device and remount the file system when needed. Please note that when using the umount function, make sure to specify the correct path and perform appropriate operations based on actual needs.

Insert image description here

Guess you like

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