[Diaoye learns programming] MicroPython manual’s built-in module dupterm

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.dupterm(stream_object, index=0, /) is a function for duplicating or switching the MicroPython terminal (ie REPL). Its main features, application scenarios, and precautions are as follows:

Main features: os.dupterm(stream_object, index=0, /) accepts two parameters: stream_object is a stream-like object used to receive and send terminal input and output 1; index is an optional integer representing The index of the terminal to be copied or switched. Currently only 0 and 1 are supported. If stream_object is None, cancel the previously set redirection. os.dupterm(stream_object, index=0, /) returns the previously set stream object, or None.

Application scenario: os.dupterm(stream_object, index=0, /) can be used to duplicate or switch MicroPython terminals on different devices or channels. For example, you can use os.dupterm(stream_object, index=0, /) to redirect the terminal from the serial port to the network, or copy the terminal from the network to the display, etc.

Things to note: Before using os.dupterm(stream_object, index=0, /), you need to import this module and use the import os statement. When using os.dupterm(stream_object, index=0, /), you need to note that the given stream object must implement the readinto() and write() methods. In addition, os.dupterm(stream_object, index=0, /) may have different implementation and support on different platforms. Therefore, when using os.dupterm(stream_object, index=0, /), it is best to first check the platform's features and limitations.

The following are three practical application cases of MicroPython's built-in module os.dupterm(stream_object, index=0, /):

Case 1: Redirect the terminal from the serial port to the network on the MicroPython board and use WebREPL for interaction. code show as below:

import os
import network
import webrepl

# 连接到无线网络(假设SSID为'MyNet',密码为'12345678')
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('MyNet', '12345678')

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

# 启动WebREPL服务(假设密码为'micropythoN')
webrepl.start(password='micropythoN')

# 获取WebREPL的流对象
webrepl_stream = webrepl.websocket

# 将终端从串口重定向到网络
os.dupterm(webrepl_stream)

Case 2: Copy the terminal from the network to the monitor on the MicroPython board, and use the LCD monitor to display input and output. code show as below:

import os
import network
import webrepl
import lcd160cr

# 连接到无线网络(假设SSID为'MyNet',密码为'12345678')
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('MyNet', '12345678')

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

# 启动WebREPL服务(假设密码为'micropythoN')
webrepl.start(password='micropythoN')

# 获取WebREPL的流对象
webrepl_stream = webrepl.websocket

# 创建一个LCD显示器对象(假设SPI总线为1,片选引脚为15)
lcd = lcd160cr.LCD160CR('X', spi=1, cs=15)

# 创建一个类似于流的对象,用于将数据写入到LCD显示器上
class LCDStream:

    # 定义初始化方法
    def __init__(self, lcd):
        # 保存LCD显示器对象
        self.lcd = lcd
        # 设置LCD显示器的字体和颜色
        self.lcd.set_font(1)
        self.lcd.set_text_color(lcd.rgb(255, 255, 255), lcd.rgb(0, 0, 0))
        # 初始化LCD显示器的光标位置
        self.x = 0
        self.y = 0

    # 定义写入方法
    def write(self, data):
        # 遍历数据中的每个字节
        for b in data:
            # 如果字节是换行符
            if b == 10:
                # 更新光标的y坐标
                self.y += 16
                # 如果y坐标超出LCD显示器的高度
                if self.y >= self.lcd.h:
                    # 将LCD显示器的内容向上滚动16像素
                    self.lcd.scroll(0, -16)
                    # 将y坐标减去16
                    self.y -= 16
                # 将光标的x坐标重置为0
                self.x = 0
            # 如果字节是回车符
            elif b == 13:
                # 忽略该字节
                pass
            # 其他情况
            else:
                # 在LCD显示器上显示该字节对应的字符
                self.lcd.write(chr(b), self.x, self.y)
                # 更新光标的x坐标
                self.x += 8
                # 如果x坐标超出LCD显示器的宽度
                if self.x >= self.lcd.w:
                    # 将x坐标重置为0,并换行
                    self.x = 0
                    self.y += 16

# 创建一个LCD流对象
lcd_stream = LCDStream(lcd)

# 将终端从网络复制到显示器(使用索引1)
os.dupterm(lcd_stream, 1)

Case 3: Define a function on the MicroPython board to input and execute a command on the console. If the command is 'dupterm', call os.dupterm(stream_object, index=0, /) to copy or switch terminals. code show as below:

import os

# 定义一个函数,用于在控制台输入一个命令并执行
def run_command():
    # 获取用户输入的命令
    cmd = input('Enter a command: ')
    # 如果命令是'dupterm'
    if cmd.startswith('dupterm'):
        # 分割命令和参数
        args = cmd.split()
        # 如果参数个数为1或2
        if len(args) in (1, 2):
            # 获取要复制或切换终端的流对象(假设已经定义了一个名为'stream_object'的变量)
            stream_object = stream_object
            # 获取要复制或切换终端的索引(默认为0)
            index = int(args[1]) if len(args) == 2 else 0
            # 尝试复制或切换终端,并捕获异常
            try:
                # 复制或切换终端,并获取之前设置的流对象
                old_stream_object = os.dupterm(stream_object, index)
                # 打印复制或切换成功信息,以及之前设置的流对象(如果有)
                print('Terminal duplicated or switched on', stream_object, 'with index', index)
                if old_stream_object is not None:
                    print('Previous stream object was', old_stream_object)
            except OSError as e:
                # 打印异常信息
                print('Failed to duplicate or switch terminal on', stream_object, 'with index', index, ':', e)
        # 如果参数个数为3,并且第二个参数是'None'
        elif len(args) == 3 and args[1] == 'None':
            # 获取要取消重定向的终端的索引(默认为0)
            index = int(args[2]) if len(args) == 2 else 0
            # 尝试取消重定向,并捕获异常
            try:
                # 取消重定向,并获取之前设置的流对象(如果有)
                old_stream_object = os.dupterm(None, index)
                # 打印取消重定向成功信息,以及之前设置的流对象(如果有)
                print('Terminal redirection cancelled on index', index)
                if old_stream_object is not None:
                    print('Previous stream object was', old_stream_object)
            except OSError as e:
                # 打印异常信息
                print('Failed to cancel terminal redirection on index', index, ':', e)
        # 如果参数个数大于3
        else:
            # 打印多余参数信息
            print('Too many arguments')
    # 如果命令是'exit'
    elif cmd == 'exit':
        # 退出函数
        return
    # 其他情况
    else:
        # 尝试执行命令,并捕获异常
        try:
            exec(cmd)
        except Exception as e:
            # 打印异常信息
            print(e)
    # 递归调用函数
    run_command()

Case 4: Redirect output to serial port:

import machine
import uos
import dupterm

# 初始化串口
uart = machine.UART(0, baudrate=115200)

# 将输出重定向到串口
dupterm.setdupterm(uart)

# 打印一些信息
print("Hello, MicroPython!")

# 恢复原始输出
dupterm.setdupterm(uos.dupterm(None))

In this example, we use the UART class of the machine module to initialize the serial port, and then use the setdupterm function of the dupterm module to redirect the output to the serial port. Next, we use the print function to print some information to the serial port. Finally, we use the dupterm function of the uos module to restore the output to its original state. By using the dupterm module, we can redirect the output from the default terminal to other devices such as serial ports.

Case 5: Redirect output to file:

import uos
import dupterm

# 打开文件进行写入
file = open("output.txt", "w")

# 将输出重定向到文件
dupterm.setdupterm(file)

# 打印一些信息
print("Hello, MicroPython!")

# 恢复原始输出
dupterm.setdupterm(uos.dupterm(None))

# 关闭文件
file.close()

In this example, we use the open function to open a file for writing, and then use the dupterm module's setdupterm function to redirect output to that file. Next, we use the print function to print some information to a file. Finally, we use the uos module's dupterm function to restore the output to its original state and close the file. By using the dupterm module, we can redirect the output to a file to facilitate saving and recording the output information of the program.

Case 6: Redirect input to serial port:

import machine
import uos
import dupterm

# 初始化串口
uart = machine.UART(0, baudrate=115200)

# 将输入重定向到串口
dupterm.setdupterm(uart)

# 接收用户输入
user_input = input("Enter your name: ")

# 恢复原始输入
dupterm.setdupterm(uos.dupterm(None))

# 处理用户输入
print("Hello, " + user_input + "!")

In this example, we use the UART class of the machine module to initialize the serial port, and then use the setdupterm function of the dupterm module to redirect the input to the serial port. Next, we use the input function to receive user input. The user can enter his or her name in the serial port input box. We then use the dupterm function of the uos module to restore the input to its original state. Finally, we process the user input and print out the corresponding greeting. By using the dupterm module we can redirect input from the default terminal to other devices such as a serial port.

Case 7: Redirect REPL output to a file

import uos

# 打开文件 "output.txt" 并将其作为 REPL 输出的重定向
with open("output.txt", "w") as file:
    uos.dupterm(file)

# 在 REPL 中执行代码,输出将会写入文件 "output.txt"

In this example, we use the open function to open the file "output.txt" and then use the dupterm function to redirect that file as output from the REPL. When executing code in the REPL, the output will be written to the file "output.txt" instead of being displayed on the terminal.

Case 8: Redirect REPL output to the serial port

import uos
from machine import UART

# 初始化串口对象
uart = UART(0, 115200)

# 将串口对象作为 REPL 输出的重定向
uos.dupterm(uart)

# 在 REPL 中执行代码,输出将会通过串口发送

In this example, we initialize a serial port object uart through the machine module, and then use the dupterm function to redirect the serial port object as the output of REPL. This way, when code is executed in the REPL, the output will be sent over the serial port instead of being displayed on the terminal.

Case 9: Restore default REPL output

import uos

# 恢复默认的 REPL 输出
uos.dupterm(None)

# 在 REPL 中执行代码,输出将会在终端上显示

In this example, we use the dupterm function to set the REPL's output redirection to None, which restores the default output. This way, when code is executed in the REPL, the output will be displayed on the terminal and not redirected elsewhere.

These examples show the dupterm function in the uos module in action, including redirecting REPL output to a file, redirecting REPL output to a serial port, and restoring the default REPL output. By using the dupterm function, you can flexibly configure the REPL's output redirection on MicroPython devices to adapt to different needs and scenarios. Note that when using the dupterm function, be sure to provide the correct output target and restore the default output if needed.

Insert image description here

Guess you like

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