Running Python on the ESP8266/NodeMCU from the Command Line

in #programming6 years ago

Screenshot from 2018-06-12 16-30-51.png

I was looking at the projects being done with Blinkit and I noticed the use of shell scripts.

Hmm, I thought, what about executing commands on an ESP8266 via the shell?

Executing Micro Python commands on the ESP8266 with mpfs

It turns out, using AMPY, or my favourite, MPFS, you can execute Python commands on your Micro Mython microcontroller board.

In MPFS you have ...

  • -c = Execute the command(s) in the shell and stay in the shell
  • -n = Execute but return
  • -s = Execute the commands in the supplied script

Executing whole Python Scripts from the shell

Now, this simply allows you to do things like list the existing files, upload/download, or run an arbitrary Python command, such as print().

But, Python can execute Python code :)

In Python there is the built in function exec. For example in repl:

exec("print('hello world')")

would be translated to mpfs on the command line as:

mpfshell -c "open ttyUSB0; exec exec( \"print('hello world')\")"

Exec just needs a string, but doesn't have to be a string literal, so we can load a file and execute it!

Putting it all together

Create a file called script.mpf then add the following

open ttyUSB0
cd /
ls
exec exec(open("blink.py").read())
exit

(you will need the blink.py from previous articles, or make one)

Then execute it with mpfshell -s script.mpf from your terminal.

That's it!

Now you can use it in your shell scripts, macros. or other applications :)


makerhacks.png

Sort:  

This is interesting! Last day I was trying to program an ESP-01 board with arduino but it quite didn't work out well.

Blinkit inspires everyone 🤣 Nice project buddy! Keep it up!

Coin Marketplace

STEEM 0.16
TRX 0.16
JST 0.029
BTC 68245.80
ETH 2509.65
USDT 1.00
SBD 2.52