1.2 ESP32-MicroPython基础操作

本文介绍了ESP32使用MicroPython进行开发的基础操作,包括通过Thonny软件或命令行连接,安装rshell,浏览教程,使用WiFi模块,控制LED,实现串口通讯,PWM调制,按键检测,ADC读取,内存查看及文件操作等,为ESP32的MicroPython编程提供全面指导。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

1.下载固件到ESP32

2.安装rshell

3.打开自带教程

4.支持的模块

5.WiFi模块

6.点灯

7.串口通讯

8.PWM

9.按键

10.ADC

11.查看剩余内存

12.文件操作


       

1.可以使用上文提到的Thonny软件,也可以命令行

esptool.py --chip esp32 --port /dev/ttyUSB0 erase_flash #擦除 
esptool.py --chip esp32 --port /dev/ttyUSB1 --baud 460800 write_flash -z 0x1000 esp32-20220618-v1.19.1.bin #下载固件

2.安装rshell

pip3 install rshell

连接rshell

rshell --buffer-size 512 --port /dev/ttyUSB0

进入ESP32的命令行:

repl

3.打开自带教程

Welcome to MicroPython on the ESP32!
For generic online docs please visit http://docs.micropython.org/
For access to the hardware use the 'machine' module:
import machine
pin12 = machine.Pin(12, machine.Pin.OUT)
pin12.value(1)
pin13 = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_UP)
print(pin13.value())
i2c = machine.I2C(scl=machine.Pin(21), sda=machine.Pin(22))
i2c.scan()
i2c.writeto(addr, b'1234')
i2c.readfrom(addr, 4)
Basic WiFi configuration:
import network
sta_if = network.WLAN(network.STA_IF); sta_if.active(True)
sta_if.scan()                             # Scan for available access points
sta_if.connect("<AP_name>", "<password>") # Connect to an AP
sta_if.isconnected()                      # Check for successful connection
Control commands:
CTRL-A        -- on a blank line, enter raw REPL mode
CTRL-B        -- on a blank line, enter normal REPL mode
CTRL-C        -- interrupt a running program
CTRL-D        -- on a blank line, do a soft reset of the board
CTRL-E        -- on a blank line, enter paste mode
For further help on a specific object, type help(obj)
For a list of available modules, type help('modules')   

4.支持的模块

>>> help('modules')
__main__          gc                ubluetooth        upysh
_boot             inisetup          ucollections      urandom
_onewire          math              ucryptolib        ure
_thread           micropython       uctypes           urequests
_uasyncio         neopixel          uerrno            uselect
_webrepl          network           uhashlib          usocket
apa106            ntptime           uheapq            ussl
btree             onewire           uio               ustruct
builtins          uarray            ujson             usys
cmath             uasyncio/__init__ umachine          utime
dht               uasyncio/core     umqtt/robust      utimeq
ds18x20           uasyncio/event    umqtt/simple      uwebsocket
esp               uasyncio/funcs    uos               uzlib
esp32             uasyncio/lock     upip              webrepl
flashbdev         uasyncio/stream   upip_utarfile     webrepl_setup
framebuf          ubinascii         uplatform         websocket_helper

5.WiFi模块

5.1 STA连接网络

import network
sta_if = network.WLAN(network.STA_IF); sta_if.active(True)
sta_if.scan()                             # Scan for available access points
sta_if.connect("612", "88888888") # Connect to an AP
sta_if.isconnected()                      # Check for successful connection

5.2 自身成为AP

import network                       #导入相应的库
ap_if=network.WLAN(network.AP_IF)    #创建对象
ap_if.active(True)                   #激活接口,开启网络
ap_if.config(essid='向往生')          #设置AP地点,你的名字

6.点灯

from machine import Pin
import time                   #导入相关的库
led=Pin(2,Pin.OUT)            #初始化
while True:
    led.on()                  #灯泡打开
    time.sleep(1)             #延时一秒
    led.off()                 #灯泡关闭
    time.sleep(1)             #延时一秒

7.串口通讯

from machine import UART,Pin
import utime                     #导入库
 
uart=UART(1,115200)  #一个普通的函数
led=Pin(25,Pin.OUT)                                                      #灯泡的初始化
uart.write("正在进行串口测试\r\n")
uart.write("请输入字符1或者0决定灯泡的开和关\r\n")
while True:
    if uart.any()==True:
        buf=uart.read(1)
        if buf=='1':
            led.on()
            print("\r\n")
            uart.write("\r\n")
        elif buf=='0':
            led.off()
            print("\r\n")
            uart.write("\r\n")
        else:
            print("\r\n")
            uart.write("\r\n")
    utime.sleep_ms(1)

8.PWM

from machine import Pin,PWM   #这里是是2号引脚,也就是那个小灯泡,亮度逐渐增加,再减少,循环
import utime
 
LED=PWM(Pin(2))
 
LED.freq(1000)       #设置他的频率为1000HZ
 
LED_duty=0
LED_direction=1
 
while True:
    LED_duty+=LED_direction
    if LED_duty>=100:
        LED_duty=100
        LED_direction=-1
    elif LED_duty<=0:
        LED_duty=0
        LED_direction=1
    LED.duty_u16(int(LED_duty*655.35))   #改变占空比
    if LED_duty%5==0:
        print(LED_duty)       #打印LED_duty的值
    utime.sleep(0.01)     #休息100ms

9.按键

from machine import Pin
import time
button=Pin(0,Pin.IN,Pin.PULL_UP)   #0号引脚按键,输入,上拉
 
led=Pin(2,Pin.OUT)    #2号引脚就是板子上的灯
 
while True:
    led.off()           #小灯亮起来
    if(button.value()==0):       #判断按键是否按下
        time.sleep_us(10)
        if(button.value()==0):
            led.on()
            print("button is pressed")
            while(button.value()==0):
                time.sleep_ms(10)

10.ADC

from machine import ADC,Pin                    #导入相应的库
adc=ADC(Pin(32),atten=ADC.ATTN_11DB)           #ADC是16位的可测电压0-3.6v,但电压不要过高,防止烧毁芯片
while True:
    adc_value=adc.read_u16()*3.55/65535
    print("{}".format(adc_value))               #打印电压

11.查看剩余内存

>>> import gc
>>> gc.mem_free() #查询空闲内存字节数
108944
>>> gc.collect() #内存垃圾回收

12.文件操作

先进入rshell模式

rshell --buffer-size 512 --port /dev/ttyUSB0

显示目录下的文件

ls /pyboard/.

就会看到里面的文件,使用cp和rm来复制和删除文件

/home/paul/下载/ESP32> ls /pyboard/.
boot.py
/home/paul/下载/ESP32> cp /pyboard/boot.py ./
Copying '/pyboard/boot.py' to '/home/paul/下载/ESP32/boot.py' ...
/home/paul/下载/ESP32> rm main.py /pyboard/

打开boot.py可以看见

# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
#import webrepl
#webrepl.start()

### ESP32-C3与BH1750传感器的集成 #### 硬件连接 ESP32-C3是一款基于RISC-V架构的微控制器,支持多种通信协议。BH1750是一种数字光强度传感器,通过I&sup2;C接口进行数据传输。为了实现两者的集成,需按照以下方式连接硬件: | **信号名称** | **ESP32-C3引脚** | **BH1750引脚** | |--------------|-------------------|------------------| | SDA | GPIO9 | SDA | | SCL | GPIO8 | SCL | | VCC | 3.3V | VCC | | GND | GND | GND | SDA 和 SCL 是 I&sup2;C 协议的数据线和时钟线,分别对应于 ESP32-C3 的 GPIO9 和 GPIO8[^2]。 --- #### 软件配置 在软件层面,需要初始化 I&sup2;C 接口并读取 BH1750 提供的光照强度数据。以下是具体步骤: 1. 初始化 I&sup2;C 总线。 2. 设置 BH1750 的测量模式(连续或一次性)以及分辨率。 3. 定期从 BH1750 获取光照强度值。 --- #### 示例代码 以下是一个完整的 Arduino IDE 示例程序,用于演示如何将 ESP32-C3 与 BH1750 进行集成: ```cpp #include <Wire.h> #define BH1750_I2C_ADDR 0x23 // 默认地址 #define CONTINUOUS_HIGH_RES_MODE_1 0x10 // 测量模式:高精度模式1 void setup() { Serial.begin(115200); Wire.begin(9, 8); // 初始化 I&sup2;C,指定 SDA (GPIO9) 和 SCL (GPIO8) configureBH1750(); } void loop() { float lux = readLux(); // 读取光照强度 Serial.print("Light Intensity: "); Serial.print(lux); Serial.println(" lx"); delay(1000); // 延迟一秒再重复读取 } // 配置 BH1750 void configureBH1750() { Wire.beginTransmission(BH1750_I2C_ADDR); Wire.write(CONTINUOUS_HIGH_RES_MODE_1); // 设置为高精度模式1 Wire.endTransmission(); } // 读取光照强度 float readLux() { uint16_t data; Wire.requestFrom(BH1750_I2C_ADDR, 2); // 请求两个字节的数据 if (Wire.available() >= 2) { uint8_t highByte = Wire.read(); // 高字节 uint8_t lowByte = Wire.read(); // 低字节 data = ((highByte << 8) | lowByte); // 合并高低字节 } return data / 1.2; // 将原始数据转换为照度单位 (lux) } ``` 此代码实现了以下几个功能: - 初始化 I&sup2;C 并设置 BH1750 工作模式为高精度模式[^3]。 - 按固定时间间隔获取当前环境中的光照强度,并将其打印到串口监视器中。 --- ### 注意事项 1. 确保供电电压稳定,BH1750 只能接受最大 3.6V 输入电压。 2. 如果使用其他开发框架(如 IDF 或 Micropython),可能需要调整 API 函数调用形式。 3. 在实际应用中,建议加入错误处理机制以应对潜在的总线异常情况。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员熊子峰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值