Getting started with MicroPython

Why don't we use Python more?

Python is a great language. 

It is a scripted language derived from C like the C++ we use in our Arduino IDE, but it is much more flexible and much easier to read. Python is strongly typed, and allows for complex classes and Object oriented programming. Python uses a very straight forward human readable syntax, and has tons of shortcuts and built in libraries for nearly anything you can imagine. Its only real downside as far as I am concerned is using whitespace to delimit blocks just like YAML, but if your editor is configured correctly to change tabs to spaces, it is not a problem. Did I mention that it is easy to read? Python is also one of the building blocks of Home Assistant, all of the components and lots of the core code is written in python, so if you learn it, you can contribute back to the community. Finally python is available for our favorite items like ESP8266 based Sonoff devices, NodeMCU and D1 mini's and even Node-Red functions can be written in python, so if you have to code, you can do it all (ok, most of it, so far I have not seen any lovelace programming in python yet) in 1 language, instead of C++ for arduino, Javascript for Node-Red functions, Python for components ... let's simplify our own lives

Getting started with MicroPython.

You probably have an ESP 8266 board lying around somewhere,
I am using a NodeMCU for this example but it could be almost anything with 1Mb of storage.
Attach the normal way you always would through a usb to serial adapter.
Get the name of that adapter so you can use it later, mine is /dev/cu.SLAB_USBtoUART

with this little bit of information we can get going:
First use pip or pip3 to install esptool

$ pip3 install esptool

if that went ok, we can download the latest micropython code.
http://micropython.org/download#esp8266
save the bin file somewhere you can easily reach it, I saved mine to: ~/Dev/micropython

cd to the directory you downloaded the file to:
$ cd ~/Dev/micropython/

erase the current firmware on your esp8266
$ esptool.py --port dev/cu.SLAB_USBtoUART erase_flash

You should get something like:
esptool.py v2.5.1
Serial port /dev/cu.SLAB_USBtoUART
Connecting........_
Detecting chip type... ESP8266
Chip is ESP8266EX
Features: WiFi
MAC: 84:0d:8e:86:76:f6 

Uploading stub...
Running stub...
Stub running...
Erasing flash (this may take a while)...
Chip erase completed successfully in 7.5s
Hard resetting via RTS pin...

Next we want to upload our freshly downloaded bin file. I am using 1.9.4

$ esptool.py --port /dev/cu.SLAB_USBtoUART --baud 460800 write_flash --flash_size=detect -fm dio 0 esp8266-20180511-v1.9.4.bin

and we get something like:
esptool.py v2.5.1
Serial port /dev/cu.SLAB_USBtoUART
Connecting........_
Detecting chip type... ESP8266
Chip is ESP8266EX
Features: WiFi
MAC: 84:0d:8e:86:76:f6
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 460800
Changed.
Configuring flash size...
Auto-detected Flash size: 4MB
Flash params set to 0x0240
Compressed 604872 bytes to 394893...
Wrote 604872 bytes (394893 compressed) at 0x00000000 in 9.2 seconds (effective 528.5 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...

Now you have micro python installed!!!
so what can we do with it?

First lets connect a terminal to the board and get our python interface. If you follow Dr Zzzs you probably have termite installed, on my Mac I use CoolTerm.
Just connect to the device you used to program the esp8266, at 115200 baud and you should see:
>>>
You are ready to write python!!!! This interface is called REPL which stands for Read Evan Print Loop.  You can just type commands and it will Read the command, Evaluate it, Print any feedback, and then wait to do it again. Lets try it:
>>> print('hello hass.io community!')
hello hass.io community!
BAM!!! You just wrote python code and got a printed response.
Lets do something more interesting:
>>> import machine
>>> machine.<tab> (actually use the tab button on your keyboard)

Sweet, we just saw that python has tab complete and we can see all the methods available to us on the machine object (which is our board)

Lets check out the network. By default with a fresh install our chip came up as an Access Point with the name MicroPython-###### where the numbers are the end of the mac address of your esp8266, but we really just want to connect to our network with the wifi "Station" that is also built in. Lets see how to do that: 
>>> import network
>>> sta_if = network.WLAN(network.STA_IF)
we just created an object to work with for our wifi station, lets connect it to our network (substitute your SSID and Password on the next line), and then lets see what we can do with this object:
>>> sta_if.connect("<SSID","<PASSWD>")
>>> sta_if.<tab>
hmmm what can we use to see if we really are connected
lets try active()
>>> sta_if.active()
True
WOOT we are connected! I also saw our linux best friend ifconfig?
>>> sta_if.ifconfig()
('10.0.0.42','255.255.255.0','10.0.0.1','10.0.0.1')

So freeking cool!!!!!

There is this web interface you can use to get to your MicroPython terminal in a browser. It is called webrepl but for security reasons, we need to turn it on from our serial terminal, and add a password.
>>> import webrepl_setup
just follow the prompts to (E)nable and enter a 4-8 character password.
once it is done, let it restart
open  http://micropython.org/webrepl/ in chrome or firefox
update the IP to your ip address from our ifconfig() and click the connect button:
Welcome to MicroPython!
Password:
WebREPL connected
>>>
Sweeet we have the same prompt in a browser, can write any of our above code and upload and download files to the MicroPython file system!

Lets clean up a few things

In the "Get a file" box type boot.py 
click "Get from device"
This will download your boot.py file that surprise runs every time your MicroPython board boots up.

lets add a couple of lines in your favorite editor
paste the following after your imports, and before we start webrepl (see if you can figure out where that is)

wifiSSID = 'prettyFly4awifi'
wifiPassword = '$t4y0ut!'
def do_connect(ssid,passwd):
  import network
  sta_if = network.WLAN(network.STA_IF)
  if not sta_if.isconnected():
    print('connecting to network...')
    sta_if.active(True)
    sta_if.connect(ssid, passwd)
    while not sta_if.isconnected():
      pass
  print('network config:', sta_if.ifconfig())

# now use the function we created
do_connect(wifiSSID,wifiPassword)


Of course those are not really my SSID or password, and you should update them appropriately
Note that whitespace matters, so these should be all the way to the left with no preceding whitespace until we are in the function do_connect.

Save your edited file and upload it via webrepl

Now every time your board boots up, it will connect to your network and be ready for you to play!
one more thing just for security's sake, lets turn off that automatic wifi access point.  The AP is named AP_IF (like our STA_IF) see if you can use the tab complete to figure out how to de-active-ate it.
If you get stuck, the two commands are below in the Home Work section.

That's enough for today ...

But in a future article we will play with some of your options here, but just as a teaser check out:
This 110 lines of python code (50 of which are comments or whitespace) will allow you to run your holiday lights in one of 3 animations with color choices from a web page anywhere in the world.  
Tony from adafruit does a great job walking through the code, and how he reverse engineered the webrepl page to make it work.

I can't wait to see how you change it over the coming weeks!

Home work:

First we need to get the network WLAN object that represents the Access point just like we did with the Station:
>>> ap_if = network.WLAN(network.AP_IF)

Then we use that object's active method to turn it off:
>>> ap_if.active(False)

Comments

Popular posts from this blog

HomeAssistant via docker on a Mac

Flashing my tuya switches with tasmota

How I put Tasmota on my NodeMCU board and why I love them so much.