在前面的MicroPython的開發方式中,我們使用PuTTY以REPL的方式在NodeMCU上直接編寫程式,這樣的好處是所有的指令都是在按下Enter之後直接執行,可以馬上看到結果,但問題是,如果不小心打錯字了,就要再重來一次。此外,所有的程式在重新開機就都不見了,要再重新輸入一次,這對於要編寫稍微大一點的程式的我們來說,使用上會非常不方便,所幸,有另外一個作法可以克服這個問題。
在MicroPython中,系統下有兩個程式是NodeMCU在一接上電源的時候就會馬上被執行的程式,依序是boot.py以及main.py。所以,有一個簡單的方式就是,如果我們在NodeMCU的板子上上傳一個main.py的程式,那麼每次NodeMCU一被啟動的時候,就會在執行完boot.py之後,立即前往執行main.py,就可以達到讓NodeMCU脫離電腦,只要接上電源就可以運作的模式了。
那麼我們應該如何把main.py上傳,寫在NodeMCU的板子上呢?回想一下,之前我們使用的REPL連線方式,都是透過Shell一步一步執行程式,該程式並不會被寫在板子上,所以,如果想要使用上傳程式檔案的功能,需要再安裝另外一個套件才行,這個套件就叫做ampy,請使用以下的方式安裝:
pip install adafruit-ampy
順利安裝完畢之後,就可以執行ampy,看看能夠得到什麼訊息:
(base) C:\Users\USER>ampy Usage: ampy [OPTIONS] COMMAND [ARGS]... ampy - Adafruit MicroPython Tool Ampy is a tool to control MicroPython boards over a serial connection. Using ampy you can manipulate files on the board's internal filesystem and even run scripts. Options: -p, --port PORT Name of serial port for connected board. Can optionally specify with AMPY_PORT environment variable. [required] -b, --baud BAUD Baud rate for the serial connection (default 115200). Can optionally specify with AMPY_BAUD environment variable. -d, --delay DELAY Delay in seconds before entering RAW MODE (default 0). Can optionally specify with AMPY_DELAY environment variable. --version Show the version and exit. --help Show this message and exit. Commands: get Retrieve a file from the board. ls List contents of a directory on the board. mkdir Create a directory on the board. put Put a file or folder and its contents on the... reset Perform soft reset/reboot of the board. rm Remove a file from the board. rmdir Forcefully remove a folder and all its... run Run a script and print its output.
從上面的教學訊息可以看出,命令put就是上傳檔案的意思。所以,接下來的步驟就是在自己的電腦中透過程式碼編輯器編輯main.py這個檔案,存檔之後,使用ampy –port COM3 put main.py就可以把檔案上傳了。程式內容如下:
from machine import Pin import time led = Pin(2, Pin.OUT) while True: led.on() time.sleep(0.5) led.off() time.sleep(0.5)
執行的過程如下所示:
ampy --port COM3 put main.py
上傳完畢如果沒有出現任何錯誤訊息的話,把NodeMCU重新啟動,就可以看到板子上的LED在閃爍囉!
(2142)
近期留言