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

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 Pinhtml

import timepython

 

led=Pin(4,Pin.OUT)git

 

while True:github

    led.on()微信

    print("LED on!")app

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

    led.off()ui

    print("LED off!")spa

    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
若是你喜欢这篇文章就点击 在看 或者 分享 给你的朋友吧!
扫码关注公众号:

加入微信交流群:.net

本文分享自微信公众号 - TopSemic嵌入式(TopSemic)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。

相关文章
相关标签/搜索