|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: "ESP8266 and MicroPython - Part 1" |
| 4 | +description: "Using MicroPython on ESP8266 based devices and Home Assistant." |
| 5 | +date: 2016-07-21 06:00:00 +0200 |
| 6 | +date_formatted: "July 21, 2016" |
| 7 | +author: Fabian Affolter |
| 8 | +comments: true |
| 9 | +categories: How-To |
| 10 | +og_image: /images/blog/2016-07-micropython/social.png |
| 11 | +--- |
| 12 | + |
| 13 | +<img src='/images/blog/2016-07-micropython/micropython.png' style='clear: right; border:none; box-shadow: none; float: right; margin-bottom: 12px;' width='200' /> |
| 14 | +The first release of Micropython for ESP8266 was delivered a couple of weeks ago. The [documentation](http://docs.micropython.org/en/latest/esp8266/esp8266_contents.html) covers a lot of ground. This post is providing only a little summary which should get you started. |
| 15 | + |
| 16 | +If you don't participated in the KickStarter campaign only the source code was available. This meant that you needed to build the firmware on your own. As of now the [pre-built firmware](https://micropython.org/download/#esp8266) is available for the public. |
| 17 | + |
| 18 | +<!--more--> |
| 19 | + |
| 20 | +The easiest way is to use [esptool.py](https://github.com/themadinventor/esptool) for firmware handling tasks. First erase the flash: |
| 21 | + |
| 22 | +```bash |
| 23 | +$ sudo python esptool.py --port /dev/ttyUSB0 erase_flash |
| 24 | +esptool.py v1.0.2-dev |
| 25 | +Connecting... |
| 26 | +Erasing flash (this may take a while)... |
| 27 | +``` |
| 28 | + |
| 29 | +and then load the firmware. You may adjust the file name of the firmware binary. |
| 30 | + |
| 31 | +```bash |
| 32 | +$ sudo python esptool.py --port /dev/ttyUSB0 --baud 460800 write_flash --flash_size=8m 0 esp8266-2016-07-10-v1.8.2.bin |
| 33 | +esptool.py v1.2-dev |
| 34 | +Connecting... |
| 35 | +Running Cesanta flasher stub... |
| 36 | +Flash params set to 0x0020 |
| 37 | +Writing 540672 @ 0x0... 540672 (100 %) |
| 38 | +Wrote 540672 bytes at 0x0 in 13.1 seconds (330.8 kbit/s)... |
| 39 | +Leaving... |
| 40 | +``` |
| 41 | + |
| 42 | +Now reset the device. You should then be able to use a terminal program like `minicom` or `picocom` to connect and get the [REPL (Read Evaluate Print Loop)](http://docs.micropython.org/en/latest/esp8266/esp8266/tutorial/repl.html#getting-a-micropython-repl-prompt) prompt. |
| 43 | + |
| 44 | +```bash |
| 45 | +$ sudo minicom -D /dev/ttyUSB0 |
| 46 | +#4 ets_task(4020e374, 29, 3fff70e8, 10) |
| 47 | +WebREPL daemon started on ws://192.168.4.1:8266 |
| 48 | +Started webrepl in setup mode |
| 49 | +could not open file 'main.py' for reading |
| 50 | + |
| 51 | +#5 ets_task(4010035c, 3, 3fff6360, 4) |
| 52 | +MicroPython v1.8.2-9-g805c2b9 on 2016-07-10; ESP module with ESP8266 |
| 53 | +Type "help()" for more information. |
| 54 | +>>> |
| 55 | +``` |
| 56 | + |
| 57 | +<p class='note'> |
| 58 | +The public build of the firmware may be different than the firmware distributed to the backers of the campaign. Especially in regard of the [available modules](http://docs.micropython.org/en/latest/esp8266/py-modindex.html), turned on debug messages, and alike. Also, the WebREPL may not be started by default. |
| 59 | +</p> |
| 60 | + |
| 61 | +Connect a LED to pin 5 (or another pin of your choosing) to check if the ESP8266 is working as expected. |
| 62 | + |
| 63 | +```python |
| 64 | +>>> import machine |
| 65 | +>>> pin = machine.Pin(5, machine.Pin.OUT) |
| 66 | +>>> pin.high() |
| 67 | +``` |
| 68 | + |
| 69 | +You can toogle the LED by changing its state with `pin.high()` and `pin.low()`. |
| 70 | + |
| 71 | +Various ESP8266 development board are shipped with an onboard photocell or a light dependent resistors (LDR) connected to the analog pin of your ESP8266 check if you are able to obtain a value. |
| 72 | + |
| 73 | +```python |
| 74 | +>>> import machine |
| 75 | +>>> brightness = machine.ADC(0) |
| 76 | +>>> brightness.read() |
| 77 | +``` |
| 78 | + |
| 79 | +The REPL can also be accessed through with a browser. For your convinience, is an instance of the WebREPL client hosted at [http://micropython.org/webrepl](http://micropython.org/webrepl). Alternatively, you can create a local clone of their [GitHub repository](https://github.com/micropython/webrepl). This is neccessary if your want to use the command-line tool `webrepl_cli.py`. |
| 80 | + |
| 81 | +Make sure that you are familiar with REPL and WebREPL because this will be needed soon. Keep in mind the password for the WebREPL access. |
| 82 | + |
| 83 | +Read the [instructions](http://docs.micropython.org/en/latest/esp8266/esp8266/tutorial/network_basics.html) about how to setup your wireless connection. Basically you need to upload a `boot.py` file to the microcontroller and this file is taking care of the connection setup. Below you find a sample which is more or less the same as shown in the [documentation](http://docs.micropython.org/en/latest/esp8266/esp8266/tutorial/network_basics.html#configuration-of-the-wifi). |
| 84 | + |
| 85 | +```python |
| 86 | +def do_connect(): |
| 87 | + import network |
| 88 | + |
| 89 | + SSID = 'SSID' |
| 90 | + PASSWORD = 'PASSWORD' |
| 91 | + |
| 92 | + sta_if = network.WLAN(network.STA_IF) |
| 93 | + ap_if = network.WLAN(network.AP_IF) |
| 94 | + if ap_if.active(): |
| 95 | + ap_if.active(False) |
| 96 | + if not sta_if.isconnected(): |
| 97 | + print('connecting to network...') |
| 98 | + sta_if.active(True) |
| 99 | + sta_if.connect(SSID, PASSWORD) |
| 100 | + while not sta_if.isconnected(): |
| 101 | + pass |
| 102 | + print('Network configuration:', sta_if.ifconfig()) |
| 103 | +``` |
| 104 | + |
| 105 | +Upload this file: |
| 106 | + |
| 107 | +```bash |
| 108 | +$ python webrepl_cli.py boot.py 192.168.4.1:/boot.py |
| 109 | +``` |
| 110 | + |
| 111 | +If you reboot, you should see your current IP address in the terminal. |
| 112 | + |
| 113 | +```bash |
| 114 | +>>> Network configuration: ('192.168.0.10', '255.255.255.0', '192.168.0.1', '192.168.0.1') |
| 115 | +``` |
| 116 | + |
| 117 | +First let's create a little consumer for Home Assistant sensor's state. The code to place in `main.py` is a mixture of code from above and the [RESTful API](/developers/rest_api/) of Home Assistant. If the temperature in the kitchen is higher than 20 °C then the LED connected to pin 5 is switched on. |
| 118 | + |
| 119 | +<p class='note'> |
| 120 | +If a module is missing then you need to download is it from [MicroPython Library overview](https://github.com/micropython/micropython-lib) and upload it to the ESP8266 with `webrepl_cli.py` manually. |
| 121 | +</p> |
| 122 | + |
| 123 | +```python |
| 124 | +# Sample code to request the state of a Home Assistant entity. |
| 125 | + |
| 126 | +API_PASSWORD = 'YOUR_PASSWORD' |
| 127 | +URL = 'http://10.100.0.197:8123/api/states/' |
| 128 | +ENTITY = 'sensor.kitchen_temperature' |
| 129 | +TIMEOUT = 30 |
| 130 | +PIN = 5 |
| 131 | + |
| 132 | +def get_data(): |
| 133 | + import urequests |
| 134 | + url = '{}{}'.format(URL, ENTITY) |
| 135 | + headers = {'x-ha-access': API_PASSWORD, |
| 136 | + 'content-type': 'application/json'} |
| 137 | + resp = urequests.get(URL, headers=headers) |
| 138 | + return resp.json()['state'] |
| 139 | + |
| 140 | +def main(): |
| 141 | + import machine |
| 142 | + import time |
| 143 | + |
| 144 | + pin = machine.Pin(PIN, machine.Pin.OUT) |
| 145 | + while True: |
| 146 | + try: |
| 147 | + if int(get_data()) >= 20: |
| 148 | + pin.high() |
| 149 | + else: |
| 150 | + pin.low() |
| 151 | + except TypeError: |
| 152 | + pass |
| 153 | + time.sleep(TIMEOUT) |
| 154 | + |
| 155 | +if __name__ == '__main__': |
| 156 | + print('Get the state of {}'.format(ENTITY)) |
| 157 | + main() |
| 158 | +``` |
| 159 | + |
| 160 | +Upload `main.py` the same way as `boot.py`. After a reboot (`>>> import machine` and `>>> machine.reboot()`) or power-cycling your physical notifier is ready. |
| 161 | + |
| 162 | +If you run into trouble, press "Ctrl+c" in the REPL to stop the execution of the code, enter `>>> import webrepl` and `>>> webrepl.start()`, and upload your fixed file. |
| 163 | + |
0 commit comments