ESP32通过uPycraft将py程序设置成Default Run后连接不上板子,提示重新烧录固件(BurnFirmware ),已解决。

原因:ESP32未响应upycraft的连接,其实这时候你的程序已经在运行了,只不过没在一定的时间内响应upycraft。

所以建议程序写好了再设置成自动运行,使用putty等串口工具查看打印信息。

分析:自动运行的程序无法在三秒钟之内运行完!(三秒只是个大概)

1.设置了while 1......,无法跳出

2.delay时间过长

3.自启动默认运行连接WiFi等子程序,消耗时间过长。

4.使用putty或者其他串口类工具,给板子发命令(   uos.remove("main.py")   )删除自动运行的main.py文件即可成功连接

 

解决办法:

通过定时器,检测某个IO是否为高电平,再将要执行的操作封装成一个子函数。

注意一定要通过定时器来检测,不要通过循环+延时来检测按键。

例程:

1.I/O检测:
check_pin()函数里面为你封装的子函数。

pin = Pin(4,Pin.IN)
def check_pin(pin):
  if pin.value() == 1:
    ...
    ...
    ...

2.定时器:

def check_pin(pin):
  if pin.value() == 1:
    ...
    ...
    ...

def Timer_func(timer, pin):
    timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:check_pin(pin))
timer = Timer(1)    # 创建定时器对象
Timer_func(timer,pin)

3.结合:

from umqtt.simple import MQTTClient
from machine import Pin,Timer
import motor
import time
import utime
import sta
import simple
import switch


global speed
#sta.do_connect()
SERVER = '121.196.58.68'
CLIENT_ID = 'sub'
TOPIC = b'h9'
speed = 1

def mqtt_callback(topic, msg):
    global speed
    print('topic: {}'.format(topic),end= '/    ')
    print('msg: {}'.format(msg),end = ' ')
    speed = int (  int( str(msg, "utf-8") ) *1.65 )
    #print (speed)
    #speed = int (int( format(msg) ) *1023/650) )
 
def check_pin(pin):
  if pin.value() == 1:
    sta.do_connect()
    client = MQTTClient(CLIENT_ID, SERVER)
    client.set_callback(mqtt_callback)
    client.connect()
    client.subscribe(TOPIC)
    timer.deinit()
    i = 0
    while 1:
        # 查看是否有数据传入
        # 有的话就执行 mqtt_callback
        i = i+1
        client.check_msg()
        print("\nsublishing[%d]:...speed: %d "%(i,speed),end= ' ')
        motor.pulse(speed)
        utime.sleep_ms(100)
  else :
    print ("waiting pin4 High......")

def Timer_func(timer, pin):
    timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:check_pin(pin))

pin = Pin(4,Pin.IN)
timer = Timer(1)    # 创建定时器对象
Timer_func(timer,pin)

定时器更多操作见API文档:https://www.1zlab.com/wiki/micropython-esp32/timer/

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值