[Diaoye learns programming] MicroPython manual WiPy specific port library wipy.machine.ADCWiPy

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 is a streamlined implementation of the Python language for microcontrollers that allows developers to write embedded applications using Python syntax and standard libraries. WiPy is a wireless development board based on ESP32 chip, which supports running MicroPython firmware. MicroPython WiPy-specific libraries are a set of modules designed for WiPy that provide access to WiPy-specific functionality and hardware interfaces. The main features of MicroPython's WiPy-specific libraries are as follows:

1. It contains some WiPy-related modules, such as machine, network, pycom, uos, etc., which respectively provide WiPy machine-level control, network connection, lighting control, operating system interface and other functions.
2. It also contains some common MicroPython modules, such as binascii, hashlib, math, random, struct, time, etc., which provide some commonly used data processing, encryption, mathematics, random numbers, data structures, time and other functions.
3. It follows the design principles of MicroPython, which are simplicity, efficiency, portability and compatibility.

Insert image description here

MicroPython's wipy.machine.ADCWiPy is a class used to create and control analog-to-digital conversion (ADC) objects, which allows developers to use the ADC function on the WiPy development board to read the value of analog signals.

The main features of wipy.machine.ADCWiPy are as follows:

It is part of the machine module, which contains some classes and functions related to WiPy hardware.
It creates an ADC object that can use the channel() method to create an ADC channel that can be connected to an internal or external analog source on the WiPy.
It can set the resolution of the ADC object (bits parameter), the default is 12 bits, which means that the ADC can convert analog signals into digital values ​​from 0 to 4095.
It can use the init() and deinit() methods to enable or disable the ADC object to save power or release resources.

The application scenarios of wipy.machine.ADCWiPy are as follows:

There are four GPIO pins (GP2, GP3, GP4, GP5) on the WiPy development board that can be used as ADC inputs. They can be connected to external analog sensors, such as temperature sensors, photoresistors, potentiometers, etc., and then use wipy.machine. ADCWiPy to read their analog values.
The WiPy development board also has some internal analog signal sources, such as battery voltage, temperature sensor, Hall effect sensor, etc. They can use wipy.machine.ADCWiPy to read their analog values.
There is also a DAC output pin (GP25) on the WiPy development board, which can output an analog signal from 0 to 3.3V. It can be used in conjunction with wipy.machine.ADCWiPy to realize the generation and collection of analog signals.

Things to note about wipy.machine.ADCWiPy are as follows:

Before using wipy.machine.ADCWiPy, you need to import the machine module first, using the import machine statement.
When using wipy.machine.ADCWiPy, you need to be careful not to conflict with other modules or devices, and to avoid using excessive memory and power resources.
When using wipy.machine.ADCWiPy, you need to note that the ADC pin input range is 0-1.4V (1.8V is the absolute maximum it can tolerate). 1.8 V is the maximum when GP2, GP3, GP4 or GP5 is remapped to the ADC module. If these pins are used in digital mode, the maximum input voltage allowed is 3.6V.

Here are some codes for practical applications:

Case 1: Use wipy.machine.ADCWiPy and wipy.machine.Pin to read the analog value of a temperature sensor LM35 and display the temperature value on the OLED screen.

# 导入 machine 和 wipy 模块
import machine
import wipy

# 创建一个 ADC 对象并连接到 LM35 的引脚
adc = machine.ADC()
apin = adc.channel(pin='GP3')

# 创建一个 Pin 对象并连接到 OLED 的复位引脚
p_rst = machine.Pin('GP25', mode=Pin.OUT)

# 创建一个 I2C 对象并连接到 OLED 的 SDA 和 SCL 引脚
i2c = machine.I2C(0, pins=('GP26', 'GP27'))

# 导入 ssd1306 库并创建一个 OLED 对象
import ssd1306
oled = ssd1306.SSD1306_I2C(128, 64, i2c, p_rst)

# 循环读取 LM35 的模拟值并显示温度值
while True:
    # 读取模拟值,范围是 0 到 4095
    value = apin()
    # 计算温度值,单位是摄氏度
    # 假设 ADC 输入范围是 0 到 1.4V,LM35 输出电压是 10mV/℃
    temperature = value / 4095 * 1.4 / 0.01
    # 清除 OLED 屏幕
    oled.fill(0)
    # 在 OLED 屏幕上显示温度值
    oled.text("Temperature:", 0, 0)
    oled.text("{:.2f} C".format(temperature), 0, 16)
    # 更新 OLED 屏幕
    oled.show()

Case 2: Use wipy.machine.ADCWiPy and wipy.machine.PWM to implement a simple music player that can adjust the volume based on the analog value of a potentiometer.

# 导入 machine 和 wipy 模块
import machine
import wipy

# 创建一个 ADC 对象并连接到电位器的引脚
adc = machine.ADC()
apin = adc.channel(pin='GP3')

# 创建一个 PWM 对象并连接到扬声器的引脚
pwm = machine.PWM(0, freq=1000)
pwm.channel(Timer.A, pin='GP25')

# 定义一个函数来播放一段音符
def play_tone(freq, msec):
    # 设置 PWM 的频率和占空比
    pwm.freq(freq)
    pwm.duty_cycle(50)
    # 等待指定的毫秒数
    time.sleep_ms(msec)
    # 停止 PWM 输出
    pwm.duty_cycle(0)

# 定义一些音符的频率,单位是赫兹
NOTE_C4 = 262
NOTE_D4 = 294
NOTE_E4 = 330
NOTE_F4 = 349
NOTE_G4 = 392
NOTE_A4 = 440
NOTE_B4 = 494

# 定义一首简单的歌曲,每个元素是一个音符和一个时长的元组,单位是毫秒
song = [(NOTE_C4, 250), (NOTE_D4, 250), (NOTE_E4, 250), (NOTE_F4, 250),
        (NOTE_G4, 250), (NOTE_A4, 250), (NOTE_B4, 250), (NOTE_C4, 500)]

# 循环播放歌曲并根据电位器的模拟值调节音量
while True:
    # 遍历歌曲中的每个音符和时长
    for note, msec in song:
        # 读取电位器的模拟值,范围是 0 到 4095
        value = apin()
        # 计算音量值,范围是 0 到 100
        volume = value / 4095 * 100
        # 设置 PWM 的占空比为音量值的一半(因为占空比的范围是 0 到 50)
        pwm.duty_cycle(volume / 2)
        # 播放音符和时长
        play_tone(note, msec)

Case 3: Use wipy.machine.ADCWiPy and wipy.machine.Pin to implement a simple light-controlled switch, which can control the switch of an LED light based on the analog value of a photoresistor.

Follow these steps:

Import the machine and wipy modules
. Create an ADC object and connect it to the pin of the photoresistor.
Create a Pin object and connect it to the pin of the LED light.
Loop to read the analog value of the photoresistor and control the switch of the LED light
. If the analog value is less than 1000, it means If the light is dark, turn on the LED light.
If the analog value is greater than or equal to 1000, it means the light is bright, turn off the LED light.

Here is the code for the complete program:

# 导入 machine 和 wipy 模块
import machine
import wipy

# 创建一个 ADC 对象并连接到光敏电阻的引脚
adc = machine.ADC()
apin = adc.channel(pin='GP3')

# 创建一个 Pin 对象并连接到 LED 灯的引脚
p_led = machine.Pin('GP25', mode=Pin.OUT)

# 循环读取光敏电阻的模拟值并控制 LED 灯的开关
while True:
    # 读取模拟值,范围是 0 到 4095
    value = apin()
    # 如果模拟值小于 1000,表示光线较暗,就开启 LED 灯
    if value < 1000:
        p_led.value(1)
    # 如果模拟值大于等于 1000,表示光线较亮,就关闭 LED 灯
    else:
        p_led.value(0)

Case 4: Reading analog sensor values:

from machine import ADC

# 初始化ADC
adc = ADC(0)

# 读取模拟传感器值
sensor_value = adc.read()

# 打印传感器值
print("传感器值:", sensor_value)

In this example, we use machine.ADC() to initialize an ADC object. We then read the value of the simulated sensor using the read() method and store it in the variable sensor_value. Finally, we use the print() function to print out the sensor value.

Case 5: Set ADC channel and accuracy::

from machine import ADC

# 初始化ADC
adc = ADC(1)

# 设置ADC通道和精度
adc.channel(2)
adc.width(ADC.WIDTH_12BIT)

# 读取传感器值
sensor_value = adc.read()

# 打印传感器值
print("传感器值:", sensor_value)

In this example, we use machine.ADC() to initialize an ADC object and specify the channel number as 1. Then, we use the channel() method to set the ADC channel to 2, indicating that we want to read the sensor value of the second channel. Next, we use the width() method to set the ADC's accuracy to 12 bits. Finally, we read the value of the sensor using the read() method and store it in the variable sensor_value. Finally, we use the print() function to print out the sensor value.

Case 6: Continuous reading of sensor values::

from machine import ADC
import time

# 初始化ADC
adc = ADC(0)

# 连续读取传感器值
for i in range(10):
    sensor_value = adc.read()
    print("传感器值:", sensor_value)
    time.sleep(1)

In this example, we use machine.ADC() to initialize an ADC object. Then, we use the read() method to continuously read the sensor's value, and use the print() function to print out the sensor's value after each reading. We use the time.sleep(1) function to pause for 1 second between each read to simulate the process of continuous reading.

Case 7: Reading analog voltage

from machine import ADCWiPy

adc = ADCWiPy()
print(adc.read()) # 读取ADC通道电压,0-4095数值

Case 8: Temperature collection

from machine import ADCWiPy

adc = ADCWiPy()  
factor = 3.3 / (4095 * 10) 

while True:
  voltage = adc.read() * factor 
  temp = 27 - (voltage - 0.706)/0.001721
  print(temp)

Case 9: Light intensity detection

from machine import ADCWiPy  

def check_light():
  adc = ADCWiPy()
  if adc.read() < 500:
    print('Too dark, turn on the light!')
 
check_light()

These examples show how to use ADCWiPy to read analog inputs and implement functions such as temperature sensors and light sensing.

Insert image description here

Guess you like

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