build wifi gadgets using esp8266
TRANSCRIPT
Build WiFi Gadgetsusing ESP8266
GeekCamp.SG 2015
Zhu Baoshi @ba0sh1
www.ba0sh1.com
2
Internet of Things (?)• Let coffee pot twitter you a message is less
productive than just a beep!•Same for turning on/off a light.•Beware of the over hype!
•But why connect things onto internet?Remote convenience
Did you forget to … ?MonitoringDiagnose / supportWhy-not ?
Data driven actuatorsWeather
www.ba0sh1.com
3
ESP8266 in IoT Device
www.ba0sh1.com
4
ESP8266 In-a-nutshell• Developed by Espressif System• LOW COST• A 32-bit Microcontroller, using Tensilica
Xtensa core• RF frontend• Runs at 80MHz or 160MHz• External Flash• ~80kB DRAM• ~35kB IRAM• ADC, GPIO, SPI, I2S, DMA• Part number is ESP8266EX• 20 million chip sold. 5000 active
developers
www.ba0sh1.com
5
Modules
ESP8266
Flash
26MHz Crystal
Chip Antenna or equivalent
www.ba0sh1.com
6
Dev Boards
Adafruit Huzzah SparkfunMOD-WIFI-ESP8266-DEV
NodeMCU v1
Mine :D
$9.95 €5.50 $8.5
www.ba0sh1.com
7
Beware of “unauthorized” NodeMCU v1
www.ba0sh1.com
8
Architect ESP8266 project
ESP8266 Arduino / other MCU
Sensors / Indicators / Actuators
The “original” pre-oct-2014 way
Hayes AT alike instructions
www.ba0sh1.com
9
Dawn of ESP8266 SDK
ESP8266Sensors /
Indicators / Actuators
I/OExpander
www.ba0sh1.com
10
Demo
www.ba0sh1.com
11
Know your Hardware• WiFi– Supports 802.11b/g/n, WPA/WPA2– AP, STA, AP+STA modes– With my ASUS router it connects at 65Mbps– With WebSocket speed test I receive 5-6KB/s– NetIO test best at 1040KB/s, reference from
http://www.esp8266.com/viewtopic.php?f=5&t=245 (doing nothing but receive TCP packets)
www.ba0sh1.com
12
Power Power Power!• ESP8266 is both low power and power hungry• Test setup:
• Idle mode: 40uA
www.ba0sh1.com
13
Power Consumption @ WiFi idle
100ms
64mA
424mA
847ns
Average for 1 second: 993ms@64mA+7ms@424mA = 66.5mA
With 22uF tantalum bypass capacitor. A bigger capacitor may help reduce the spike.
www.ba0sh1.com
14
Power Consumption @ WiFi active
Average 67.6mA
www.ba0sh1.com
15
Wakeup-Read-Send-Sleep
Startup
RF Calibration
Scan AP, Connect, DHCP
Connect to MQTT, Publish data
Active for 5.7 seconds: 70.2mA
www.ba0sh1.com
16
Will you go battery power?
Standby Always on Wake up once every minute
Wake up once every hour
2500mAh lithium battery
7 years 37 hours 15.5 days 689 days
2xAA alkaline 3000mAh
8.4 years 44 hours 18.6 days 827 days
*Your actual millage may vary
www.ba0sh1.com
17
Keep your options open• Particle Photon ($19)• Lightblue Bean ($30)
• OpenWRT routers ($7-20)LinuxUSBHigh performanceNot low powerSlow boot
www.ba0sh1.com
18
ESP8266 Development H/W• Module (+ development board) • USB-Serial adaptor (3.3V)• A GOOD power supply
www.ba0sh1.com
19
ESP8266 Programming S/W• ARDUINO IDE• https://github.com/esp8266/Arduino
(recommend the “Staging” version)
• Compatible with *many* Arduino libraries
www.ba0sh1.com
20
ESP8266 Arduino LibraryWiFi.begin(ssid, password);while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print(".");}Serial.println("");Serial.println("WiFi connected"); Serial.println("IP address: ");Serial.println(WiFi.localIP());
WiFiClient client;if (!client.connect(host, httpPort)) { Serial.println("connection failed"); return;}// This will send the request to the serverclient.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");delay(10);// Read all the lines of the reply from server and print them to Serialwhile(client.available()){ String line = client.readStringUntil('\r'); Serial.print(line);}
www.ba0sh1.com
21
NodeMCU• http://www.nodemcu.com/index_en.html(mqtt.lua)m = mqtt.Client(“client”, 120, “user”, “pass”)m:connect(“192.168.0.99”, 1831, 0, function(conn) print("Connected to MQTT:" .. BROKER .. ":" .. BRPORT .." as " .. CLIENTID) m:publish("sensors/".. CLIENTID .. "/temperature",30,0,0, function(conn) print ("temp published") node.dsleep(10*1000000) end)end)
(init.lua)tmr.alarm(1,500, 1, function() if wifi.sta.getip()==nil then print(" Wait to IP address!") else print("New IP address is "..wifi.sta.getip()) dofile("mqtt.lua") endend)
www.ba0sh1.com
22
ESP8266 SDK and Toolchain• I want to have more control / more speed / be
cool• ESP8266 SDK available at bbs.espressif.com• Espressif compiler in VM• crosstool-NG on Win/Linux/Mac github.com/
pfalcon/esp-open-sdk• Unofficial DevKit for ESP8266 (Windows) at
http://programs74.ru/udkew-en.html
www.ba0sh1.com
23
ESP8266 IoT SDK• Low-level C SDK, partially open source• Soft Timer#define DELAY 100 /* milliseconds */LOCAL os_timer_t blink_timer;
LOCAL void ICACHE_FLASH_ATTR blink_cb(void *arg){ GPIO_OUTPUT_SET(LED_GPIO, led_state); led_state ^=1;}
void user_init(void){ ...... // Set up a timer to blink the LED os_timer_disarm(&blink_timer); os_timer_setfn(&blink_timer, (os_timer_func_t *)blink_cb, (void *)0); os_timer_arm(&blink_timer, DELAY, 1);}
www.ba0sh1.com
24
• Non-OS Task#define recvTaskPrio 0#define recvTaskQueueLen 10os_event_t recvTaskQueue[recvTaskQueueLen];
void ICACHE_FLASH_ATTR uart_init(){ system_os_task(recvTask, recvTaskPrio, recvTaskQueue, recvTaskQueueLen); ....}
void uart0_rx_intr_handler(void *para){ .... system_os_post(recvTaskPrio, SIG_RX, RcvChar);}
void recvTask(os_event_t *e) { switch (e->sig) { case SIG_RX: os_printf(“sig_rx %c/n”, (char)e->par); break; }}
www.ba0sh1.com
25
• TCP/UDP APIs
void to_scan(*arg){ ... espconn_regist_connectcb(conn, connect_callback); espconn_regist_disconcb(conn, disconnect_callback); espconn_regist_reconcb(conn, error_callback); espconn_connect(conn);}void connect_callback(void * arg){ espconn_regist_recvcb(conn, receive_callback); espconn_regist_sentcb(conn, sent_callback);}
void user_init(void) { wifi_set_opmode(STATION_MODE); system_init_done_cb(to_scan);}
Chain of callbacks, soon gets very messy
www.ba0sh1.com
26
RTOS SDK• Partially open source at
https://github.com/espressif/esp_iot_rtos_sdk• Based on FreeRTOS / lwip• BSD sockets (thread-safe)• Newer, clearer code• Foundation of esp8266_iot_platform
www.ba0sh1.com
27
FreeRTOSvoid blink_thread() { while(1) { toggle_led(); vTaskDelay(1000 / portTICK_RATE_MS); }}
void receive_thread() { while(1) {
xQueueReceive(xQueueUart, (void *)&e, portMAX_DELAY); ... }}
www.ba0sh1.com
28
Examplewifi_thread
Set WiFi parameters
while (not no ip and not timeout){ vTaskDelay; }
while (have ip){ xSemaphoreGive(wifi_alive); vTaskDelay;}
wifi_disconnect();vTaskDelay;
mqtt_thread
xSemaphoreTake(wifi_alive);mqtt_connect
while (not fail){ if have message publish; mqtt_yield(timeout);}
mqtt_subscribe
www.ba0sh1.com
29
Demo
www.ba0sh1.com
30
Other resources• www.espressif.com
• www.esp8266.com
• ESPlorer http://esp8266.ru/esplorer
• My favorite serial terminal Termite http://www.compuphase.com/software_termite.htm
• Flash Download Tool http://bbs.espressif.com/
www.ba0sh1.com
31
About me• www.ba0sh1.com• [email protected]• Twitter @ba0sh1• https://www.facebook.com/baoshi