【树莓派Pico 2 RP2350开发板】 使用Python语言GPIO/UART/PWM/ADC外设操作
[复制链接]
本帖最后由 meiyao 于 2025-3-16 10:28 编辑
尝试学习Python语言,并结合Python语言,展示学习进度
GPIO外设调试、UART外设调试、定时器生成PWM、ADC调试、电机控制等。
外设代码
GPIO 调试:控制 LED 灯、读取按键状态。
-
- 实验名称:点亮板载LED灯
-
-
-
- from machine import Pin
- import time
-
-
- LED = Pin(25, Pin.OUT)
-
-
- while True:
- LED.value(1)
- time.sleep(1)
- LED.value(0)
- time.sleep(1)
UART 调试:实现串口通信,发送和接收数据,ADC 调试:读取模拟信号。
-
- from machine import ADC, UART, Pin
- import time
-
-
-
- uart = UART(0, baudrate=9600, tx=Pin(0), rx=Pin(1))
-
-
-
- adc = ADC(Pin(26))
-
-
- while True:
- adc_value = adc.read_u16()
- uart.write("ADC Value: {}\n".format(adc_value))
- time.sleep(1)
-
UART 配置:
初始化 UART 0,设置波特率为 9600,使用 GPIO 0 作为 TX 引脚,GPIO 1 作为 RX 引脚。
ADC 配置:
初始化 ADC,使用 GPIO 26 作为模拟输入引脚。
主循环:
读取 ADC 的原始值(0-65535)。
将 ADC 值通过 UART 发送。
每次发送后等待 1 秒,避免数据发送过快。
定时器生成 PWM:控制 LED 亮度或舵机角度。
- from machine import Pin, PWM, Timer
-
-
- pwm_pin = Pin(15)
- pwm = PWM(pwm_pin)
- pwm.freq(1000)
-
-
- duty = 0
- direction = 1
-
-
- def update_pwm(timer):
- global duty, direction
- duty += direction * 1000
- if duty >= 65535 or duty <= 0:
- direction *= -1
- pwm.duty_u16(duty)
-
-
- timer = Timer()
- timer.init(period=10, mode=Timer.PERIODIC, callback=update_pwm)
-
框架结构图
【MicroPython】machine.Pin类函数详解
machine.Pin(id, mode=None, pull=None, value)
Pin对象构造函数
id:GPIO编号,数值为0-29,如使用GPIO13则此处填写13,。;
mode:模式,可选None、Pin.IN(0)、Pin.OUT(1)、Pin.OPEN_DRAIN(2);
pull:使用内部上下拉电阻,仅在输入模式下有效,可选 None、Pin.PULL_UP(1)、Pin.PULL_DOWN(2);
value:输出或开漏模式下端口值,0为低(off)、1为高(on);
串口框图
UART类函数详解
machine.UART(id,baudrate=115200,bits=8,parity=None,stop=1,tx=None,rx=None):
UART对象构造函数,作用为初始化对应通道和引脚.
id:使用UART通道,可为0或者1;
baudrate: 波特率参数
bits:数据位长度
parity:奇偶校验位
stop:停止位长度
tx:TXD引脚,应为Pin对象
rx:RXD引脚,应为Pin对象
ADC框架
machine.ADC类函数详解
machine.ADC(id):
ADC对象构造函数,并初始化对应通道。
id:可为GPIO对象,也可为ADC通道;
函数返回值并不是直接返回ADC读取的数值,而是处理过的数值,其数值范围为0-65535;
故ADC电压计算公式应为:
Vin =\frac{3.3*ReadData}{65535}Vin=655353.3∗ReadData
ADC读取电压为3.3乘上返回值除以65535,单位为V
实现结果
ADC与串口输出
使用串口打印出ADC采集的值,上图显示15。
PWM:
播放器加载失败: 未检测到Flash Player,请到 安装
PWM
LED闪烁:
播放器加载失败: 未检测到Flash Player,请到 安装
led闪烁
|