前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >MicroPython 玩转硬件系列3:上电自动执行程序

MicroPython 玩转硬件系列3:上电自动执行程序

作者头像
用户2366192
发布2021-05-31 10:52:39
3.6K0
发布2021-05-31 10:52:39
举报
文章被收录于专栏:TopSemic嵌入式TopSemic嵌入式

1.引言

上一篇我们在ESP32上实现了LED灯的闪烁,但是有一个问题,该功能的实现需要我们在串口终端里去手动执行代码,是否可以让ESP32上电后自动执行代码呢?当然是可以的,本篇文章介绍如何实现该功能。

2.ampy安装

ampy是什么,大家直接看下方的官方介绍即可,

https://github.com/scientifichackers/ampy

Adafruit MicroPython Tool (ampy) - Utility to interact with a CircuitPython or MicroPython board over a serial connection.

Ampy is meant to be a simple command line tool to manipulate files and run code on a CircuitPython or MicroPython board over its serial connection. With ampy you can send files from your computer to the board's file system, download files from a board to your computer, and even send a Python script to a board to be executed.

安装方式:

pip install adafruit-ampy -upgrade

3.ampy工具使用

前面的2篇文章,我们都是通过直接在Putty终端里写代码或者把Windows里写好的代码复制到Putty终端里执行的。有了ampy后,我们就不需要这么做了,我们可以先在Windows写好MicroPython程序,然后通过ampy工具直接运行程序。

第1步:在Windows里,写一个hello.py文件

print("Hello World!")

第2步:直接在DOS窗口里,通过ampy在板子上运行hello.py程序,执行:

ampy --port COM3 run led.py

注意:执行ampy指令前,你得确保串口没有被占用。

如果换成下方的led.py文件

from machine import Pin

import time

led=Pin(4,Pin.OUT)

while True:

led.on()

print("LED on!")

time.sleep(1.0) # Delay for 1 second.

led.off()

print("LED off!")

time.sleep(1.0) # Delay for 1 second.

执行:

ampy --port COM3 run led.py

我们看到led在不断闪烁了,但是并没有打印信息,这是什么原因呢?

没打印的原因:By default the run command will wait for the script to finish running on the board before printing its output.

因为代码里是一个while(1)循环,所以一直不会退出,所以也就不会打印了。

针对这种情况,我们可以使用下面的指令:

ampy --port COM3 run --no-output led.py

这样就不会一直停在那里了。同时我们打开PuTTY可以看到在这里一直有打印输出。

4.上电执行代码

通过以下3个步骤就可以实现上电自动执行代码了:

1) 将led.py改名为main.py

2) ampy --port COM3 put main.py

3) 板子重新上电,就可以看到灯不停的闪烁了

如果需要删除掉main.py,只需要执行:

ampy --port COM3 rm main.py

上面的工作机理是,通过ampy把main.py导入到ESP32板子里,上电后会自动执行main.py。

5.参考资料

https://www.digikey.com/en/maker/projects/micropython-basics-load-files-run-code/fb1fcedaf11e4547943abfdd8ad825ce

http://www.cirmall.com/bbs/thread-102620-1-1.html

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-06-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 TopSemic嵌入式 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档