[Diao Ye Learns Programming] MicroPython Manual Zephyr 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
Zephyr is an open source real-time operating system (RTOS) designed for embedded systems. The technical parameters of Zephyr will be explained in detail below, including its basic concepts and definitions.

1. Supported processor architectures: Zephyr supports a variety of processor architectures, including ARM, x86, RISC-V, etc. This allows Zephyr to run on a wide range of embedded systems, from low-power microcontrollers to high-performance processors.
2. Memory requirements: Zephyr's memory requirements are relatively low and can be adapted to resource-constrained embedded systems. It provides a variety of memory management solutions, including static memory allocation and dynamic memory allocation, which can be flexibly configured according to application requirements.
3. Multi-task support: Zephyr supports concurrent execution of multiple tasks. It uses a lightweight thread (Thread) mechanism to achieve task creation, scheduling and synchronization. Zephyr also provides a wealth of synchronization primitives, such as semaphores, mutexes, and message queues, to facilitate developers to communicate and synchronize between tasks.
4. Real-time performance: As a real-time operating system, Zephyr has good real-time performance. It provides configurable priority scheduling policies to ensure timely response to critical tasks. In addition, Zephyr also provides two scheduling modes, hard real-time and soft real-time, to meet application scenarios with different real-time requirements.
5. Hardware Abstraction Layer (HAL): Zephyr provides a Hardware Abstraction Layer (HAL) to shield the differences between different hardware platforms. Through HAL, developers can use a unified API interface to access hardware resources without paying attention to the details of the underlying hardware, thus improving the portability and reusability of the code.
6. Device driver support: Zephyr provides rich device driver support, including drivers for serial ports, SPI, I2C, GPIO and other common peripherals. These device drivers can easily interact with hardware and simplify control and access to peripherals.
7. Network protocol support: Zephyr supports a variety of network protocols, such as TCP/IP protocol stack, Bluetooth, Wi-Fi, etc. This makes Zephyr suitable for application scenarios such as the Internet of Things and wireless communications, and can communicate and connect with other devices.
8. Development tool chain: Zephyr provides a rich development tool chain, including command line tools, integrated development environment (IDE) plug-ins and debugger support. These tools can help developers compile, debug and deploy applications and improve development efficiency.

Insert image description here
MicroPython's Zephyr Sensor is a relevant feature when used with MicroPython and the Zephyr operating system. The following will explain MicroPython's Zephyr sensor in detail from a professional perspective and a teacher's perspective, including its main features, application scenarios, and matters needing attention.

main feature:

Sensor interface support: Zephyr operating system provides support for a variety of sensor interfaces, including I2C, SPI and GPIO. Through MicroPython's Zephyr sensor function, developers can easily communicate and interact with various sensors.

Sensor driver support: Zephyr operating system provides a wealth of sensor drivers, covering common sensor types, such as accelerometers, gyroscopes, temperature sensors, etc. These drivers implement low-level communication and data analysis with sensors, and developers can directly use these drivers to acquire and process sensor data.

Data acquisition and processing: MicroPython’s Zephyr sensor functionality allows developers to obtain sensor data through simple API calls. Developers can use this data for various applications, such as real-time monitoring, data analysis and control, etc.

Application scenarios:

IoT applications: With MicroPython’s Zephyr sensor capabilities, developers can easily build IoT applications. For example, temperature sensors are used to monitor ambient temperature, accelerometers are used to detect the movement of objects, etc., to realize applications such as smart home, smart agriculture, and smart health.

Data collection and monitoring: Sensor functions enable embedded devices to collect various data in the environment and perform real-time monitoring. Developers can use MicroPython's Zephyr sensor function to obtain sensor data and make decisions, alarms or records based on the data.

Control and feedback: The acquisition of sensor data can be used for real-time control and feedback. Developers can adjust the behavior and status of the device based on changes in sensor data, and implement automatic control and feedback mechanisms.

Things to note:

Sensor driver compatibility: Before using a specific sensor, you need to ensure that the corresponding sensor driver is available in Zephyr OS. Developers should consult relevant documentation and driver support lists to ensure compatibility of required sensors.

Data processing and noise filtering: Sensor data is usually accompanied by a certain amount of noise, and developers need to perform data processing and noise filtering to obtain accurate and reliable data. Common data processing methods include average filtering, sliding window filtering, etc.

Power management: Sensors usually require a power supply. When using sensors, the power supply needs to be properly managed to ensure that the sensor can work properly and avoid excessive power consumption.

In short, MicroPython's Zephyr sensor function provides developers with convenient sensor interface and driver support, allowing embedded devices to easily obtain and process sensor data. It has the characteristics of sensor interface support, sensor driver support and data acquisition and processing, and is suitable for IoT applications, data collection and monitoring, control and feedback and other scenarios. When using this feature, developers need to pay attention to sensor driver compatibility, data processing and noise filtering, and power management to ensure the accuracy and reliability of sensor data.

Case 1: Using GPIO to read temperature sensor data

from machine import Pin, ADC
import time

# 初始化GPIO和ADC模块
adc = ADC(Pin(32))

# 设置ADC通道和增益
channel = 0
gain = 1

# 启动ADC转换
adc.atten(gain)

while True:
    # 读取ADC值并转换为温度值
    temperature = adc.read() * 3.3 / 4096 * 100
    print("Temperature: ", temperature)
    time.sleep(1)

Interpretation of key points: This program demonstrates how to use the GPIO and ADC modules to read data from a temperature sensor. First, you need to initialize the GPIO and ADC modules, and set the ADC channel and gain. Then, start the ADC conversion through the atten method. Then, in an infinite loop, the ADC value is continuously read and converted into a temperature value, and printed. It should be noted that when using GPIO and ADC modules to communicate, the correctness and integrity of data transmission need to be ensured. Therefore, you need to wait for the receiver to be ready before sending data, and you need to pay attention to the integrity and correctness of the data when reading the data.

Case 2: Use GPIO to read the number of photosensitive sensors

from machine import Pin, ADC
import time

# 初始化GPIO和ADC模块
adc = ADC(Pin(32))

# 设置ADC通道和增益
channel = 1
gain = 1

# 启动ADC转换
adc.atten(gain)

while True:
    # 读取ADC值并转换为光照强度值
    light_intensity = adc.read() * 3.3 / 4096 * 100
    print("Light intensity: ", light_intensity)
    time.sleep(1)

Interpretation of key points: This program demonstrates how to use GPIO and ADC modules to read data from a photosensitive sensor. First, you need to initialize the GPIO and ADC modules, and set the ADC channel and gain. Then, start the ADC conversion through the atten method. Then, in an infinite loop, the ADC value is continuously read and converted into a light intensity value, and printed. It should be noted that when using GPIO and ADC modules to communicate, the correctness and integrity of data transmission need to be ensured. Therefore, you need to wait for the receiver to be ready before sending data, and you need to pay attention to the integrity and correctness of the data when reading the data.

Case 3: Use GPIO to read the status of the button

from machine import Pin, Timer
import time

# 初始化GPIO和定时器模块
pin = Pin(17, Pin.IN, Pin.PULL_UP)
timer = Timer(-1)

# 设置定时器回调函数
def callback(event):
    if event.state == 0:
        print("Button pressed")
    else:
        print("Button released")

# 启动定时器,每隔1秒触发一次回调函数
timer.init(period=1000, mode=Timer.PERIODIC, callback=callback)

while True:
    time.sleep(1)

Interpretation of key points: This program demonstrates how to use GPIO and timer modules to read the status of the buttons. First, you need to initialize the GPIO and timer modules, and set the key pins and interrupt types. Then, define a callback function to handle changes in the key state. Next, start the timer through the init method and set the parameters of the callback function. Finally, in an infinite loop, it sleeps for 1 second and waits for the key state to change. It should be noted that when using GPIO and timer modules to communicate, the correctness and integrity of data transmission need to be ensured. Therefore, you need to wait for the receiver to be ready before sending data, and you need to pay attention to the integrity and correctness of the data when reading the data.

Case 4: Reading temperature sensor data:

import machine

# 配置温度传感器
sensor = machine.ADC(0)

# 读取传感器数据
raw_value = sensor.read()

# 转换为温度值
voltage = raw_value * 3.3 / 4095
temperature = (voltage - 0.5) * 100

# 打印温度值
print("温度:", temperature, "℃")

Interpretation of key points:
Use the machine.ADC() function to configure the ADC (analog-to-digital converter) pin, and the parameter is the pin number.
Use the read() method to read raw data from the temperature sensor.
The raw data is converted into a temperature value based on the sensor's voltage-temperature relationship.
Print the temperature value.

Case 5: Reading light sensor data:

import machine

# 配置光照传感器
sensor = machine.ADC(1)

# 读取传感器数据
raw_value = sensor.read()

# 转换为光照强度值
light_intensity = raw_value * 100 / 4095

# 打印光照强度值
print("光照强度:", light_intensity, "%")

Interpretation of key points:
Use the machine.ADC() function to configure the ADC (analog-to-digital converter) pin, and the parameter is the pin number.
Use the read() method to read raw data from the light sensor.
The raw data is converted into a light intensity value based on the sensor's voltage-light intensity relationship.
Print the light intensity value.

Case 6: Reading acceleration sensor data:

import machine

# 配置加速度传感器
sensor = machine.I2C(0)

# 设置传感器地址和配置
sensor.writeto(0x68, b'\x6B\x00')

# 读取传感器数据
data = sensor.readfrom_mem(0x68, 0x3B, 6)

# 解析加速度值
accel_x = int.from_bytes(data[0:2], 'big', signed=True) / 16384
accel_y = int.from_bytes(data[2:4], 'big', signed=True) / 16384
accel_z = int.from_bytes(data[4:6], 'big', signed=True) / 16384

# 打印加速度值
print("X轴加速度:", accel_x)
print("Y轴加速度:", accel_y)
print("Z轴加速度:", accel_z)

Interpretation of key points:
Use the machine.I2C() function to configure the I2C bus, and the parameter is the bus number.
Use the writeto() method to send configuration commands to the acceleration sensor to set the sensor address and configuration.
Use the readfrom_mem() method to read data starting from the specified address from the acceleration sensor.
The read data is analyzed and scaled according to the sensor's range coefficient to obtain the acceleration value.
Print the acceleration values ​​of the X, Y, and Z axes.

Case 7: Using temperature and humidity sensor DHT11

import machine  
import dht  
  
def main():  
    # 初始化DHT11传感器  
    pin = machine.Pin(4, machine.Pin.OUT)  
    dht = dht.DHT11(pin)  
    # 读取温度和湿度数据  
    temperature, humidity = dht.read()  
    # 打印温度和湿度数据  
    print('Temperature: %d.%02d C' % (temperature // 100, temperature % 100))  
    print('Humidity: %d.%02d %%' % (humidity // 100, humidity % 100))  
  
main()

Interpretation of key points: This code uses Zephyr's MicroPython runtime to access the DHT11 temperature and humidity sensor and read the temperature and humidity data therein. In the code, we first use the machine.Pin() function to initialize the pin connected to the DHT11 sensor, then use the dht.DHT11() function to create the DHT11 sensor object, and finally use the dht.read() method to read the temperature and humidity data. It should be noted that in Zephyr, the pin numbering may be different from common development boards such as Arduino.

Case 8: Using acceleration sensor ADXL345

import machine  
import adxl345  
  
def main():  
    # 初始化ADXL345传感器  
    i2c = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(23), freq=100000)  
    adxl = adxl345.ADXL345(i2c)  
    # 读取加速度数据(单位为g)  
    x, y, z = adxl.read()  
    # 打印加速度数据  
    print('Acceleration: x=%.2fg, y=%.2fg, z=%.2fg' % (x, y, z))  
  
main()

Interpretation of key points: This code uses Zephyr's MicroPython runtime to access the ADXL345 acceleration sensor and read the acceleration data therein. In the code, we first use the machine.I2C() function to initialize the I2C bus connected to the ADXL345 sensor, then use the adxl345.ADXL345() function to create the ADXL345 sensor object, and finally use the adxl.read() method to read the acceleration data. It should be noted that in Zephyr, the pin numbers of the I2C bus may be different from common development boards such as Arduino.

Case 9: Using light sensor TSL2561

import machine  
import tsl2561  
  
def main():  
    # 初始化TSL2561传感器  
    i2c = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(23), freq=100000)  
    tsl = tsl2561.TSL2561(i2c)  
    # 读取光照强度数据(单位为lux)  
    lux = tsl.read_lux()  
    # 打印光照强度数据  
    print('Illuminance: %d lux' % lux)  
  
main()

Key points: This code uses Zephyr's MicroPython runtime to access the TSL2561 light sensor and read the light intensity data therein. In the code, we first use the machine.I2C() function to initialize the I2C bus connected to the TSL2561 sensor, then use the tsl2561.TSL2561() function to create the TSL2561 sensor object, and finally use the tsl.read_lux() method to read the light intensity data. It should be noted that in Zephyr, the pin numbers of the I2C bus may be different from common development boards such as Arduino.

These sample codes demonstrate common uses of MicroPython to operate sensors on Zephyr. Depending on your specific hardware platform and sensor type, you can make further modifications and adjustments to these examples. Please note that specific sensor operations may vary depending on Zephyr's specific configuration and hardware platform. The above example provides a basic framework that you can adjust and implement appropriately according to your actual situation.

Please note that the above cases are only for expanding ideas and may contain errors or inapplicability. Different hardware platforms, usage scenarios and MicroPython versions may lead to different usage methods. In actual programming, you need to adjust it according to your hardware configuration and specific needs, and conduct multiple actual tests. It is important to ensure that the hardware is connected correctly and to understand the specifications and characteristics of the sensors and devices used.

Insert image description here

Guess you like

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