ESP8266: Difference between revisions

From Noisebridge
Jump to navigation Jump to search
(wipe then swipe fix)
 
(33 intermediate revisions by 14 users not shown)
Line 1: Line 1:
= ESP8266 =
[[File:CyanBread bb.png|800px]]
<pre>
▄▄▄▄▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄▄▄▄▄
▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌
▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀█░▌ ▀▀▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀▀▀
▐░▌          ▐░▌          ▐░▌      ▐░▌▐░▌      ▐░▌          ▐░▌▐░▌          ▐░▌         
▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄█░▌          ▐░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄▄▄
▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▐░░░░░░░░░▌  ▄▄▄▄▄▄▄▄▄█░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌
▐░█▀▀▀▀▀▀▀▀▀  ▀▀▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀█░▌▐░░░░░░░░░░░▌▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀█░▌
▐░▌                    ▐░▌▐░▌          ▐░▌      ▐░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░▌      ▐░▌▐░▌      ▐░▌
▐░█▄▄▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄▄▄█░▌▐░▌          ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄█░▌
▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░▌          ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌
▀▀▀▀▀▀▀▀▀▀▀  ▀▀▀▀▀▀▀▀▀▀▀  ▀            ▀▀▀▀▀▀▀▀▀▀▀  ▀▀▀▀▀▀▀▀▀▀▀  ▀▀▀▀▀▀▀▀▀▀▀  ▀▀▀▀▀▀▀▀▀▀▀                                                                                         
</pre>
 
See also:
* [[ESP8266/OTA]]
* [[ESP8266/Blink]]
* [[ESP8266/WS2812]]
* [[ESP8266/PIR]]
* [[ESP8266/Temp]]
* [[ESP8266/Matrix]]
 
 
'''Servo Demo'''
<pre>
from time import sleep
 
servo = machine.PWM(machine.Pin(13), freq=50)
 
def wipe():
d = 30
while d < 120:
  servo.duty(d)
  d = d + 1
 
def swipe():
d = 120
while d > 30:
  servo.duty(d)
  d = d - 1
 
def loop():
while 1:
  wipe()
  sleep(0.5)
  swipe()
  sleep(0.5)
 
loop()
</pre>
 
* https://nurdspace.nl/ESP8266
* https://github.com/espressif/ESP8266_AT/wiki
* http://www.esp8266.com/wiki/doku.php?id=esp8266-module-family
 


The ESP8266 is a small, low-cost wifi-talking board. It's the new center of the Internet of Things. Originally intended as a "wifi modem", it exposes the WiFi interface over AT-style commands.
The ESP8266 is a small, low-cost wifi-talking board. It's the new center of the Internet of Things. Originally intended as a "wifi modem", it exposes the WiFi interface over AT-style commands.


Some hackers immediately noticed there is a general-purpose microcontroller on the box, and made a firmware for it that takes Lua programs. Now you don't need another microcontroller. Sweet!
Some hackers immediately noticed there is a general-purpose microcontroller on the box, and made a firmware for it that takes Lua programs. Now you don't need another microcontroller. Sweet!
Several additional community efforts have also been initiated and are generally discussed at http://esp8266.com one of the newer developmentss is the addition of integrated support in the Arduino IDE, further details follow in the ''Software'' section below.
== Boot Modes ==
To load new firmware, connect GPIO0 to ground, and momentarily connect RESET to ground, or cycle the power. You can then disconnect GPIO0 and program the chip over Serial with 115,200 baud. Then reset or power cycle after the firmware upload completes.
<pre>
reset causes:
        0:
        1: normal boot
        2: reset pin
        3: software reset
        4: watchdog reset
    boot device:
        0:
        1: ram
        3: flash
</pre>


== Hardware ==
== Hardware ==
<pre>
  -15cm-
  ESP-01 Module Pinout and Wiring:
+---------+
| |-| |---|     Vcc to 3.3v power
| | |-|  |     EN/CH_PD & Rst each to Vcc w/10k Resistor
| |---- ..|  |     GPIO0 to Ground & Reset for firmware update
|        | 25cm    RxD to Serial TxD & TxD to Serial RxD
| G I I R |  |       74,480 bps for bootloader output
| n O O x |          115,200 bps for upload and debug
| d 2 0 D |
| * * * * |
| * * * * |
+---------+
  T E R V
  x N s c
  D  t c
</pre>


For full specs, see [https://nurdspace.nl/ESP8266]. Important facts:
For full specs, see [https://nurdspace.nl/ESP8266]. Important facts:
* 3.3v *only* - 5v will let out the majikul smoke
* 3.3v *only* - 5v will let out the majikul smoke
* Some reports say 1A current draw, others say 250 mA
* Power draw < 250 mA
* Talks 802.1n, supports most major auth types.
* Talks 802.1n, supports most major auth types.


There are a number of ESP8266 hardware versions. The ones of interest are:
There are a number of ESP8266 hardware versions. The ones of interest are:


* ESP1: 8 pins (basically one I/O plus power, etc.). Breadboard friendly (2.54mm), but not useful standalone
* ESP-01: 8 pins (basically one I/O plus power, etc.). Breadboard friendly 2x4 header (2.54mm), but not useful standalone
* ESP12: 16 pins (I/O, power, 9 GPIO). Non-breadboard friendly: 2mm pin spacing
* ESP-12: 16 pins (I/O, power, 9 GPIO). Non-breadboard friendly: 2mm pin spacing
* ESP-12e: 22 pins, same as ESP-12, with an additional 6 pins on the back edge adding 1 I/O and SPI connections
 
=== Sources ===
 
Most modules are available from this ebay store http://stores.ebay.com/tomyuen007/ for $3 and up, ships from US, generally less than a week for delivery.


== Software ==
== Software ==
Folks seem to use [http://nodemcu.com/index_en.html NodeMCU], a Lua based firmware, when using the ESP alone.


= Group order 01/2015 =
=== espressif SDK ===
 
https://github.com/espressif/ESP8266_RTOS_SDK
 
Toolchain setup on VM: http://www.esp8266.com/wiki/doku.php?id=toolchain
 
Loading Firmware: http://www.esp8266.com/wiki/doku.php?id=loading_firmware
 
=== Arduino IDE ===
 
Enhancements to the Arduino IDE in versions 1.6.4 and later have enabled support for the esp8266 and the ability to upload new firmware. Version 1.6.5 r5 or later is recommended.
 
The current version of the IDE can be downloaded from https://www.arduino.cc/en/Main/Software
 
Two additional steps are required to add esp8266 support to the Arduino IDE
# Open the preferences menu in the Arduino IDE and add <code>http://arduino.esp8266.com/stable/package_esp8266com_index.json</code> into "Additional Board Manager URLs" field
# Open Boards Manager from "Tools > Board: ______ > Boards Manager..." menu, scroll down to esp8266, click to select it and then click the install button.
 
Details about esp8266 support can be found at https://github.com/esp8266/Arduino
 
Once it downloads you'll see "ESP8266 Modules" section added to the list of target boards under "Tools > Board: ______>". You can use the "Generic ESP8266 Module" option for programming ESP-## modules using a 3.3v USB-Serial connector.
 
You'll need a USB to Serial cable/dongle for programming the board, connecting Ground/Rx/Tx. If you're using the cheap USB dongles, like the AI branded ones using a CH340G chip, you may also need to install the drivers.
 
* http://www.wch.cn/download/CH341SER_ZIP.html (Windows)
* http://www.wch.cn/download/CH341SER_MAC_ZIP.html (Mac)
* http://www.wch.cn/download/CH341SER_LINUX_ZIP.html (Linux)
 
In order to enable the ESP8266 to accept new firmware, temporarily connect GPIO0 to ground, and cycle the power.
 
=== LUA ===
There are a wide variety of firmware builds available for the chip. Of interest is the software [http://nodemcu.com/index_en.html NodeMCU], which turns the serial port in to a Lua REPL. [[User:Yesac|Yesac]] is working on an [https://github.com/squeed/nodemcu-env environment] within NodeMCU for doing TFTP and some other junk.
 
Uploading firmware is easy with [https://github.com/themadinventor/esptool esptool]
 
= Projects =
 
== NUB plug ==
 
[[File:NUBplug.png|366px]]
 
 
== IoT X'ample ==
 
'''Breadboarded multi-function device using ESP-12 module, PIR sensor, buzzer, indicator LEDs and light sensor.'''
 
See additional PIR info [[ESP8266/PIR]]
 
[[File:BoardRoom_bb.png|800px]]
 
The following code can be used on the above diagrammed hardware. Using a web browser the ESP8266 will respond the following url requests
* http://xxx.xxx.xxx.xxx/ (Displays current status, motion and light level)
* http://xxx.xxx.xxx.xxx/buzz (Triggers the buzzer to make a noise)
* http://xxx.xxx.xxx.xxx/hello (Returns a simple hello message)
 
<pre>
/*
 
  AS IS NO GUARANTEE NO WARRANTY
 
*/
 
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
 
const char *ssid = "YourWiFi";
const char *password = "WiFiPassword";
 
ESP8266WebServer server ( 80 );
 
const int pir = 4;
const int led = 14;
const int buzzer = 12;
 
void handleRoot() {
char temp[400];
int sec = millis() / 1000;
int min = sec / 60;
int hr = min / 60;
 
snprintf ( temp, 400,
 
"<html>\
  <head>\
    <title>PIR Demo</title>\
    <style>\
      body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }\
    </style>\
  </head>\
  <body>\
    <h1>Hello from ESP8266 PIR!</h1>\
    <p>Uptime: %02d:%02d:%02d</p>\
    <p>Motion: %s</p>\
    <p>Ambient: %d%</p>\
  </body>\
</html>",
 
hr, min % 60, sec % 60, digitalRead(pir)?"true":"false", round(analogRead(A0)/10.24)
);
server.send ( 200, "text/html", temp );
}
 
void handleBuzz() {
 
char temp[400];
int sec = millis() / 1000;
int min = sec / 60;
int hr = min / 60;
 
snprintf ( temp, 400,
 
"<html>\
  <head>\
    <title>BUZZ!!!</title>\
    <style>\
      body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #ff0000; }\
    </style>\
  </head>\
  <body>\
    <h1>BUZZ!!!</h1>\
    <p>Uptime: %02d:%02d:%02d</p>\
    <p>Motion: %s</p>\
  </body>\
</html>",
 
hr, min % 60, sec % 60, digitalRead(pir)?"true":"false"
);
server.send ( 200, "text/html", temp );
 
        digitalWrite(buzzer, HIGH);
        delay(300);
        digitalWrite(buzzer, LOW);
}
 
 
void handleNotFound() {
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
 
for ( uint8_t i = 0; i < server.args(); i++ ) {
message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
}
 
server.send ( 404, "text/plain", message );
}
 
void setup ( void ) {
pinMode ( led, OUTPUT );
digitalWrite ( led, 0 );
       
        pinMode(buzzer, OUTPUT);
        digitalWrite(buzzer, 0);
       
        pinMode(pir, INPUT);
 
Serial.begin ( 115200 );
WiFi.begin ( ssid, password );
Serial.println ( "" );


// Wait for connection
while ( WiFi.status() != WL_CONNECTED ) {
delay ( 500 );
Serial.print ( "." );
}


Prices are from the same store, and are competitive within a few cents.
Serial.println ( "" );
Serial.print ( "Connected to " );
Serial.println ( ssid );
Serial.print ( "IP address: " );
Serial.println ( WiFi.localIP() );


* ESP-12, Without breakout (Option A): $2.60 [http://www.aliexpress.com/store/product/Free-Shipping-10pcs-lot-ESP8266-remote-serial-Port-WIFI-wireless-module-through-walls-Wang-ESP-12/413752_32243298445.html aliex]
server.on ( "/", handleRoot );
* ESP-12, with breakout board, battery socket, resistors, and power regulator (2.54mm pitch): $4.50 [http://www.aliexpress.com/item/Free-shipping-10pcs-lot-ESP8266-ESP-12-serial-WIFI-Industrial-stable-version-A-full-test-board/32260087529.html aliex]
        server.on("/buzz", handleBuzz);
server.on ( "/hello", []() {
server.send ( 200, "text/plain", "hi, how ya doin?" );
} );
server.onNotFound ( handleNotFound );
server.begin();
Serial.println ( "HTTP server started" );
}


void loop ( void ) {
       
        if (digitalRead(pir)) {
          // Do something interesting on motion
        } else {
          // Nothing new here
        }


=== Order Participants ===
        // LED on if motion == true
Put your name, email, and quantity of With and Without breakout desired.
        digitalWrite(led, digitalRead(pir));


{| border="1" cellspacing="0" cellpadding="5" align="center"
server.handleClient();
|-
}
! Name
</pre>
! Email
! No Breakout
! Breakout
|-
| Casey
| c1@caseyc.net
| 0
| 3
|-
| Adrian
| adrian@freebsd
| 0
| 5
|-
| Naomi
| naomi at nthmost
| 0
| 4
|-
| Dana
| dsniezko at sonic net
| 0
| 3
|-
| Patrick
| p@trickod.com
| 0
| 4
|-
| Les Jones
|
| 0
| 2
|-
| Brad
| brad.schwagler at gmail
| 0
| 2
|-
| Torrie
| tdfischer at hackerbots
| 10
| 0
|-
| Jake
| jake at spaz odt org
| 0
| 2
|-
| Henner
| h.zeller at acm.org
| 10
| 0
|-
| John E.
| neurofog@gmail.com
| 2
| 0
|-
| Yer name
| Yer email
| -1
| -1
|}

Latest revision as of 20:44, 7 April 2021

CyanBread bb.png

 ▄▄▄▄▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄▄▄▄▄ 
▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌
▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀█░▌ ▀▀▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀▀▀ 
▐░▌          ▐░▌          ▐░▌       ▐░▌▐░▌       ▐░▌          ▐░▌▐░▌          ▐░▌          
▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄█░▌          ▐░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄▄▄ 
▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▐░░░░░░░░░▌  ▄▄▄▄▄▄▄▄▄█░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌
▐░█▀▀▀▀▀▀▀▀▀  ▀▀▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀█░▌▐░░░░░░░░░░░▌▐░█▀▀▀▀▀▀▀█░▌▐░█▀▀▀▀▀▀▀█░▌
▐░▌                    ▐░▌▐░▌          ▐░▌       ▐░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░▌       ▐░▌▐░▌       ▐░▌
▐░█▄▄▄▄▄▄▄▄▄  ▄▄▄▄▄▄▄▄▄█░▌▐░▌          ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄█░▌▐░█▄▄▄▄▄▄▄█░▌
▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░▌          ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌
 ▀▀▀▀▀▀▀▀▀▀▀  ▀▀▀▀▀▀▀▀▀▀▀  ▀            ▀▀▀▀▀▀▀▀▀▀▀  ▀▀▀▀▀▀▀▀▀▀▀  ▀▀▀▀▀▀▀▀▀▀▀  ▀▀▀▀▀▀▀▀▀▀▀                                                                                           

See also:


Servo Demo

from time import sleep

servo = machine.PWM(machine.Pin(13), freq=50)

def wipe():
 d = 30
 while d < 120:
  servo.duty(d)
  d = d + 1

def swipe():
 d = 120
 while d > 30:
  servo.duty(d)
  d = d - 1

def loop():
 while 1:
  wipe()
  sleep(0.5)
  swipe()
  sleep(0.5)

loop()


The ESP8266 is a small, low-cost wifi-talking board. It's the new center of the Internet of Things. Originally intended as a "wifi modem", it exposes the WiFi interface over AT-style commands.

Some hackers immediately noticed there is a general-purpose microcontroller on the box, and made a firmware for it that takes Lua programs. Now you don't need another microcontroller. Sweet!

Several additional community efforts have also been initiated and are generally discussed at http://esp8266.com one of the newer developmentss is the addition of integrated support in the Arduino IDE, further details follow in the Software section below.

Boot Modes[edit]

To load new firmware, connect GPIO0 to ground, and momentarily connect RESET to ground, or cycle the power. You can then disconnect GPIO0 and program the chip over Serial with 115,200 baud. Then reset or power cycle after the firmware upload completes.

reset causes:
        0: 
        1: normal boot
        2: reset pin
        3: software reset
        4: watchdog reset

    boot device:
        0:
        1: ram
        3: flash

Hardware[edit]


  -15cm-
		  ESP-01 Module Pinout and Wiring:
+---------+
| |-| |---|	    Vcc to 3.3v power
| | |-|   |	    EN/CH_PD & Rst each to Vcc w/10k Resistor
| |---- ..|  |	    GPIO0 to Ground & Reset for firmware update
|         | 25cm    RxD to Serial TxD & TxD to Serial RxD
| G I I R |  |	      74,480 bps for bootloader output
| n O O x |           115,200 bps for upload and debug
| d 2 0 D |
| * * * * |
| * * * * |
+---------+
  T E R V
  x N s c
  D   t c

For full specs, see [1]. Important facts:

  • 3.3v *only* - 5v will let out the majikul smoke
  • Power draw < 250 mA
  • Talks 802.1n, supports most major auth types.

There are a number of ESP8266 hardware versions. The ones of interest are:

  • ESP-01: 8 pins (basically one I/O plus power, etc.). Breadboard friendly 2x4 header (2.54mm), but not useful standalone
  • ESP-12: 16 pins (I/O, power, 9 GPIO). Non-breadboard friendly: 2mm pin spacing
  • ESP-12e: 22 pins, same as ESP-12, with an additional 6 pins on the back edge adding 1 I/O and SPI connections

Sources[edit]

Most modules are available from this ebay store http://stores.ebay.com/tomyuen007/ for $3 and up, ships from US, generally less than a week for delivery.

Software[edit]

espressif SDK[edit]

https://github.com/espressif/ESP8266_RTOS_SDK

Toolchain setup on VM: http://www.esp8266.com/wiki/doku.php?id=toolchain

Loading Firmware: http://www.esp8266.com/wiki/doku.php?id=loading_firmware

Arduino IDE[edit]

Enhancements to the Arduino IDE in versions 1.6.4 and later have enabled support for the esp8266 and the ability to upload new firmware. Version 1.6.5 r5 or later is recommended.

The current version of the IDE can be downloaded from https://www.arduino.cc/en/Main/Software

Two additional steps are required to add esp8266 support to the Arduino IDE

  1. Open the preferences menu in the Arduino IDE and add http://arduino.esp8266.com/stable/package_esp8266com_index.json into "Additional Board Manager URLs" field
  2. Open Boards Manager from "Tools > Board: ______ > Boards Manager..." menu, scroll down to esp8266, click to select it and then click the install button.

Details about esp8266 support can be found at https://github.com/esp8266/Arduino

Once it downloads you'll see "ESP8266 Modules" section added to the list of target boards under "Tools > Board: ______>". You can use the "Generic ESP8266 Module" option for programming ESP-## modules using a 3.3v USB-Serial connector.

You'll need a USB to Serial cable/dongle for programming the board, connecting Ground/Rx/Tx. If you're using the cheap USB dongles, like the AI branded ones using a CH340G chip, you may also need to install the drivers.

In order to enable the ESP8266 to accept new firmware, temporarily connect GPIO0 to ground, and cycle the power.

LUA[edit]

There are a wide variety of firmware builds available for the chip. Of interest is the software NodeMCU, which turns the serial port in to a Lua REPL. Yesac is working on an environment within NodeMCU for doing TFTP and some other junk.

Uploading firmware is easy with esptool

Projects[edit]

NUB plug[edit]

NUBplug.png


IoT X'ample[edit]

Breadboarded multi-function device using ESP-12 module, PIR sensor, buzzer, indicator LEDs and light sensor.

See additional PIR info ESP8266/PIR

BoardRoom bb.png

The following code can be used on the above diagrammed hardware. Using a web browser the ESP8266 will respond the following url requests

/*

   AS IS NO GUARANTEE NO WARRANTY

*/

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char *ssid = "YourWiFi";
const char *password = "WiFiPassword";

ESP8266WebServer server ( 80 );

const int pir = 4;
const int led = 14;
const int buzzer = 12;

void handleRoot() {
	
	char temp[400];
	int sec = millis() / 1000;
	int min = sec / 60;
	int hr = min / 60;

	snprintf ( temp, 400,

"<html>\
  <head>\
    <title>PIR Demo</title>\
    <style>\
      body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }\
    </style>\
  </head>\
  <body>\
    <h1>Hello from ESP8266 PIR!</h1>\
    <p>Uptime: %02d:%02d:%02d</p>\
    <p>Motion: %s</p>\
    <p>Ambient: %d%</p>\
  </body>\
</html>",

		hr, min % 60, sec % 60, digitalRead(pir)?"true":"false", round(analogRead(A0)/10.24)
	);
	server.send ( 200, "text/html", temp );
}

void handleBuzz() {
  	
	char temp[400];
	int sec = millis() / 1000;
	int min = sec / 60;
	int hr = min / 60;

	snprintf ( temp, 400,

"<html>\
  <head>\
    <title>BUZZ!!!</title>\
    <style>\
      body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #ff0000; }\
    </style>\
  </head>\
  <body>\
    <h1>BUZZ!!!</h1>\
    <p>Uptime: %02d:%02d:%02d</p>\
    <p>Motion: %s</p>\
  </body>\
</html>",

		hr, min % 60, sec % 60, digitalRead(pir)?"true":"false"
	);
	server.send ( 200, "text/html", temp );

        digitalWrite(buzzer, HIGH);
        delay(300);
        digitalWrite(buzzer, LOW);
}
  

void handleNotFound() {
	String message = "File Not Found\n\n";
	message += "URI: ";
	message += server.uri();
	message += "\nMethod: ";
	message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
	message += "\nArguments: ";
	message += server.args();
	message += "\n";

	for ( uint8_t i = 0; i < server.args(); i++ ) {
		message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
	}

	server.send ( 404, "text/plain", message );
}

void setup ( void ) {
	pinMode ( led, OUTPUT );
	digitalWrite ( led, 0 );
         
        pinMode(buzzer, OUTPUT);
        digitalWrite(buzzer, 0);
        
        pinMode(pir, INPUT);

	Serial.begin ( 115200 );
	WiFi.begin ( ssid, password );
	Serial.println ( "" );

	// Wait for connection
	while ( WiFi.status() != WL_CONNECTED ) {
		delay ( 500 );
		Serial.print ( "." );
	}

	Serial.println ( "" );
	Serial.print ( "Connected to " );
	Serial.println ( ssid );
	Serial.print ( "IP address: " );
	Serial.println ( WiFi.localIP() );

	server.on ( "/", handleRoot );
        server.on("/buzz", handleBuzz);
	server.on ( "/hello", []() {
		server.send ( 200, "text/plain", "hi, how ya doin?" );
	} );
	server.onNotFound ( handleNotFound );
	server.begin();
	Serial.println ( "HTTP server started" );
}

void loop ( void ) {
        
        if (digitalRead(pir)) {
          // Do something interesting on motion
        } else {
          // Nothing new here
        }

        // LED on if motion == true
        digitalWrite(led, digitalRead(pir));

	server.handleClient();
}