[Diaoye learns programming] MicroPython manual esp8266 esp32 specific port library esp.flash_read()

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 esp.flash_read() is a function used to read data from the flash memory of ESP8266 and ESP32 chips. Flash memory is a non-volatile memory that can be used to store firmware, file systems and user data.

The main features of esp.flash_read() are:

It is a simple and convenient way to operate flash memory reading objects. You can use esp.flash_read(byte_offset, buffer) to read data from flash memory. You need to specify two parameters: byte_offset and buffer.
It is a flexible and powerful way to control flash memory reading objects. You can control the starting address and length of data read from flash memory, as well as the buffer object into which the data is placed, by passing in different byte_offset and buffer parameters.
It is a compatible and extensible interface method for flash memory reading objects. You can use other modules or functions to access or modify the properties and methods of flash memory reading objects. You can use the esp.flash_size() method to obtain the total size of flash memory.

The application scenarios of esp.flash_read() are:

Used to read firmware or file system data from flash memory. For example, before using the uos module or other modules, use esp.flash_read() to read the metadata or content of the firmware or file system from flash memory for loading and parsing. .
Used to read user data from flash memory. For example, before using esp.flash_write() or esp.flash_erase() method, use esp.flash_read() to read user data from flash memory and process or back up as needed.
Used to read custom data structures from flash memory. For example, before using a file system or data structure designed and implemented by yourself, use esp.flash_read() to read a custom data structure from flash memory and read it according to your own Requirements for analysis or operation.

Things to note about esp.flash_read() are:

Before using esp.flash_read(), you need to ensure that the ESP8266 or ESP32 development board has been correctly connected to the power supply and computer, and the MicroPython firmware has been installed.
When using esp.flash_read(), you need to pay attention to the legality and validity of the byte_offset and buffer parameters to avoid errors such as address out-of-bounds or buffer overflow.
When using esp.flash_read(), you need to pay attention to coordination and compatibility issues with other modules or functions to avoid functional conflicts or interference. For example, if you use the esp.flash_read() method, you cannot also use the machine.deepsleep() method.

The following are several practical application cases using esp.flash_read():

Case 1: Use esp.flash_read() to read and print the firmware version number from flash memory. code show as below:

import esp # 导入 esp 模块
import struct # 导入 struct 模块
offset = 0x1000 # 设置固件版本号在闪存中的偏移量
buffer = bytearray(4) # 创建一个字节数组对象,大小为 4 字节
esp.flash_read(offset, buffer) # 从闪存中读取 4 字节到缓冲区中
version = struct.unpack('I', buffer)[0] # 将缓冲区中的字节转换为无符号整数
print('Firmware version:', version) # 打印固件版本号

This program can read and print the firmware version number from flash memory. You can use other methods to handle or display this value.

Case 2: Use esp.flash_read() to read and back up user data from flash memory. code show as below:

import esp # 导入 esp 模块
user_start = esp.flash_user_start() # 获取用户可用的闪存起始地址
user_size = esp.flash_size() - user_start # 计算用户可用的闪存空间大小
buffer = bytearray(user_size) # 创建一个字节数组对象,大小为用户可用的闪存空间大小
esp.flash_read(user_start, buffer) # 从闪存中读取用户数据到缓冲区中
with open('backup.bin', 'wb') as f: # 打开一个文件对象,以二进制写入模式
    f.write(buffer) # 将缓冲区中的数据写入文件中
print('User data backup done') # 打印提示信息

This program can read and backup user data from flash memory. You can use other methods to modify or verify this operation.

Case 3: Use esp.flash_read() to read and parse a simple file system from flash memory, which can store and read strings in the flash memory space available to the user. code show as below:

import esp # 导入 esp 模块
user_start = esp.flash_user_start() # 获取用户可用的闪存起始地址
user_size = esp.flash_size() - user_start # 计算用户可用的闪存空间大小
sector_size = 4096 # 设置每个扇区的大小
sector_count = user_size // sector_size # 计算可用的扇区数量
sector_map = bytearray(sector_count) # 创建一个字节数组对象,大小为可用的扇区数量

def read_file(name):
    # 定义一个函数来读取文件,参数为文件名,返回值为文件内容或 None(如果没有找到)
    name = name.encode('utf-8') # 将文件名转换为字节串
    name_len = len(name) # 获取文件名的长度
    for i in range(sector_count): # 循环遍历每个扇区
        if sector_map[i] == 1: # 如果该扇区为占用状态
            offset = user_start + i * sector_size # 计算起始地址偏移量
            buffer = esp.flash_read(offset, sector_size) # 从闪存中读取该扇区数据到缓冲区中
            if buffer[0] == name_len & 0xff and buffer[1] == (name_len >> 8) & 0xff and buffer[2:name_len + 2] == name: # 如果找到匹配的文件名
                content_len = buffer[name_len + 3] + (buffer[name_len + 4] << 8) # 获取文件内容的长度
                content = buffer[name_len + 5:name_len + content_len + 5] # 获取文件内容
                return content.decode('utf-8') # 将文件内容转换为字符串并返回
    return None # 如果没有找到匹配的文件名,返回 None

# 测试代码
for i in range(sector_count): # 循环遍历每个扇区
    offset = user_start + i * sector_size # 计算起始地址偏移量
    buffer = esp.flash_read(offset, sector_size) # 从闪存中读取该扇区数据到缓冲区中
    if buffer[0] != 0xff: # 如果该扇区不为空白
        sector_map[i] = 1 # 标记该扇区为占用状态

print(read_file('hello.txt')) # 读取并打印第一个文件的内容
print(read_file('test.txt')) # 读取并打印第二个文件的内容
print(read_file('foo.txt')) # 尝试读取一个不存在的文件的内容

This program can read from flash memory and parse a simple file system that can store and read strings in the flash space available to the user.

Case 4: Read the entire flash content:

import esp

flash_size = esp.flash_size()
data = esp.flash_read(0, flash_size)

Case 5: Read the content of the specified address:

import esp

address = 0x1000
length = 4
data = esp.flash_read(address, length)

Case 6: Verify flash writing:

import esp

address = 0x2000
esp.flash_write(address, b'123')
data = esp.flash_read(address, 3)
print(data)

The first example reads the entire flash. The second example reads fixed-length content based on address. The third example verifies previous flash writes by reading. This function can read the contents of the ESP module flash. It is often used in scenarios such as read and write verification, content backup and recovery, etc. The above examples demonstrate the simple application of esp.flash_read() in different situations.

Case 7: Read data from the specified address of Flash

import esp

data = esp.flash_read(0x100000, 4096) 
print(data)

This example will read 4096 bytes of data from Flash starting at address 0x100000.

Case 8: Back up firmware partition

import esp

firmware_addr = 0x0
backup_file = 'firmware.bin'
with open(backup_file, 'wb') as f:
  f.write(esp.flash_read(firmware_addr, firmware_size))  

This example can read data from the firmware partition address and back it up to a file.

Case 9: Verify firmware checksum

import esp

checksum_addr = 0x100000
firmware_addr = 0x200000
checksum = esp.flash_read(checksum_addr, 32)
data = esp.flash_read(firmware_addr, firmware_size)
verify(data, checksum)

This example reads the firmware checksum and data and can then verify that the firmware is complete and correct.

Insert image description here

Guess you like

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