Close
0%
0%

ESP cookbook

Collecting snippets that can quickly be copied to assemble a program for different sensors etc. Mostly about ESP8266/32 with Arduino IDE.

Public Chat
Similar projects worth following
**Sorry, I again found myself being the R&D department of our company, not much extra time outside work and family..**
**Another challenge, HackADay's editing/formatting system tends to lose stuff when editing, very annoying to notice older parts are crippled, when adding new**
Mostly, when starting a new project, I go through sample programs for each sensor/display needed for the job, and copy snippets from them. Testing, if it would be beneficial to collect this kind of ready-made snippets on a single page, from where they could be quickly copied to whatever project under work.

See "Instructions" for the recipes, "Details" for the table of contents.

Note that this cookbook is targeted to aid with quick prototyping and not writing production quality code - there are methods that are convenient for hacking but not recommended or to be used in production. I try to warn about such practices but feel free to notify about those I have missed so far.

Note: If code pasted from the "instructions" complains about strange characters, copy first to some plain text editor, remove those strange characters, which are hopefully visible there, and then copy&paste from there. Hackaday has the automatic feature to add random invisible characters to keep the reader awake. To keep the writer awake, sections of text or pictures might automatically disappear when saving edits.

List of current "instructions"

Page 1 - General

1. ESP 8266 pin uses and restrictions

2. Serial communication

3. Network connectivity - TCP/IP and HTTP

4. Thingspeak

5. Writing float to character buffer

6. GPIO & timer interrupts, deep sleep

7. Persistent variable storage - EEPROM, RTC, SPIFFS

8. 74HC4051 Multiplexer

9. MCP4725 I²C DAC

10. Analog to Digital Converter (ADC)

Page 2 - Temperature etc sensors

11. TMP36 analog temperature sensor

12. DS18B20 one-wire temperature sensor

13. DHTxx temperature / humidity sensor (AKA AM23xx)

14. BMP280 / BME280 I²C air pressure, temperature and humidity (BME) sensor.

15. MLX90614 I²C infrared temperature sensor

16. Dew point calculation

17. BH1750FVI I²C light intensity sensor

18. HC-SR04 ultrasonic distance sensor

19. VL53L0x I²C laser Time of Flight distance sensor

Page 3 - Displays

21. 0.96" / 1,3" I²C OLED displays

22. 0.96 / 1.3" SPI OLED displays

23. SPI LCD displays

24. WaveShare SPI 2.9" e-Paper

25. WS2811, WS2812, WS2812B, WS2813 individually addressable LEDs (no snippets so far)

  • 1
    ESP 8266 pin uses and restrictions

    Not all ESP 8266's GPIOs are born equal, something I have now and then been banging my head at (and burned some ESPs). Some are hard wired for some use, like SPI clock and data, some wired to functionality like flashing and booting. For now Wemos D1 mini's pins, others to be added. Some limitations/features might be missing, to be added when bumped into.

    Dev board Dx, Arduino IDE aliasGPIO #Notes
    D016- Wire to RST for timed wake from deep sleep
    - Doesn't support interrupts, PWM, I²C, one-wire
    D15Default I²C SCL, but others except D0 fine for that too.
    D24Default I²C SDA, but others except D0 fine for that too.
    D30- Needs to be pulled up for booting, down for flashing. Wemos has 10k pull-up, convenient for I²C.
    - Used for booting/flashing, don't hard wire to GND/Vcc. Wemos has hard pull-down for flashing by serial RTS.
    - Otherwise after boot works as a generic digital I/O
    D42- Built in LED
    - Wemos has 10k pull-up, convenient for I²C.
    - Used for booting, doesn't boot up if pulled down while starting. ESP-12 doesn't seem to require a pull-up but recommended to have one.
    - Otherwise after boot works as a generic digital I/O
    D514Hardware SPI clock, but others can be used for software SPI. Fine for other uses.
    D612Hardware SPI MISO, but others can be used for software SPI. Fine for other uses.
    D713Hardware SPI MOSI, but others can be used for software SPI. Fine for other uses.
    D815- Need to be pulled down for booting up, Wemos for example has 10k pull-down. Not good for I²C, which would require pull-up.
    - Otherwise after boot works as a generic digital I/O
    A0A0ADC input, 0-1 V for generic ESP8266, 0-3.3 V for Wemos D1 mini (which has a 220k/100k resistor voltage divider)
    TX1Serial TX, other GPIO use possible
    RX3Serial RX, I²S DMA output, other GPIO use possible
    -10In ESP-12 modules and boards using them GPIO10 is connected to the internal flash, but in a pinch might be usable for own applications, if quad SPI modes not used. GPIO9 usually doesn't work but might, if you know what you're doing.


    When running on batteries, I use ESP-12E/F (12S would be convenient as it has the required pull-up/downs internally, but I've had bad experience waking them from deep sleep due to too high resistance behind RST). This template I print on paper (six fit nicely on an A4) for planning/marking connections:

    Explanation: 

    • RST & EN pulled up (by a ~2.2-12k resistor)
    • For wake-up from deep sleep, add a diode from RST to IO16 - this allows pulling RST low without interfering IO16
    • Pull IO0 up (by a resistor)
    • Recommended to pull IO2 up (by a resistor)
    • Pull IO15 down (by a resistor)
    • The LED is controlled by IO2, inverted
    • IO3 / RX0 is also the I²S out pin, used for WS281x addressable LEDs etc
    • IO4 & 5 are the default I²C SDA & SCL pins, others can be used as well but the defaults often allow running example code etc without modifications.
    • The round pins 1-8 & 9-16 beside the ESP-12 image represent 1/10" / 2.54mm headers, can be used to plan wiring to a SOT-16 adapter, as below, or whatever PCB.
  • 2
    Serial communication

    After soon 60 years the RS-232 standard is doing strong, as that's what we're talking with to our most modern IoT thingys (yep I know about TTL vs positive/negative levels, pretty close anyway I'd say). Pretty much any MCU board talks RS-232 to the computer, nowadays generally through a UART inside the MCU board or cable, thus the Serial library is probably the most common denominator that's always available for I/O.

    Initialization

    None needed

    Setup()

      Serial.begin(115200); //9600 would be more common, albeit slow, 74880 would print boot loader info as clear text instead of garbage
      while (!Serial) {} //Wait for OK 

    Use

    //Output
        Serial.println("hello"); //With line feed 
        Serial.println((String)"Temperature: " + temp + " humidity: " + humidity); //See Note
        Serial.printf("Temperature: %f humidity: %f\n", temp, humidity);
    //Input
        if (Serial.available() > 0)
          if (Serial.peek() > 42) { //Ignore LF,CR etc
            int userInput1 = Serial.parseInt(); //Adjust number of these as needed. See Note2
            int userInput2 = Serial.parseInt();
          } else {
            Serial.readString(); //Ditch useless data
          }
    

    Note1: The String concatenation method is something you should never do. Unless if lazy. just prototyping and have excess memory. Not that unlikely, if you are reading this.

    Note2: parseInt is a dirty way to do input, quick for testing some parameters but for production you will write a proper input function.

  • 3
    Network connectivity - TCP/IP and HTTP

    For pretty much any ESP project I'd want the data to be sent to somewhere, thus networking would be like garlic in cooking - first chop it and then start wondering what are you actually going to cook.


    Initialization

    #include <ESP8266WiFi.h>
    #include <ESP8266HTTPClient.h>
    const char *WLAN_SSID = "My-network-SID-address";
    const char *WLAN_PASSWORD = "My-network-pw";
    HTTPClient http;
    

    Setup()

    WiFi.mode(WIFI_STA);
    WiFi.begin(WLAN_SSID, WLAN_PASSWORD);
    while (WiFi.status() != WL_CONNECTED) { 
        delay(200);
        Serial.print(".");
    }
    Serial.println((String)"\nConnected: " + WiFi.localIP() + " RSSI: " + WiFi.RSSI());

    Use (HTTP GET call)

    // Helper function
    int doHttpGet(char *url) {
        int httpCode = -1;
        for(int i = 0; i < 20; i++) {
        http.begin(url);
        int httpCode = http.GET();
        http.end();
        Serial.print("URL: ");
        Serial.println(url);
        Serial.print("HTTP return code: ");
        Serial.print(httpCode);
        Serial.print(" ");
        Serial.println(
        http.errorToString(httpCode));
        if(httpCode > 0) //Other retry codes can be added
            break;
            delay(5000);
        }
        return httpCode;
    }
    // Do the request:
    doHttpGet("http://my.url?val1=42&val2=4");3");

View all 28 instructions

Enjoy this project?

Share

Discussions

Elliot Williams wrote 05/02/2019 at 20:50 point

This is an _amazing_ resource for anyone working with the ESP8266! 

I've been watching this grow for (months?) now.  I know we've written it up once before, but maybe it's time to do it again.  

Big Kudos!

  Are you sure? yes | no

Tillo wrote 05/01/2019 at 14:35 point

could you put that onto some repository? 

  Are you sure? yes | no

Turo Heikkinen wrote 05/02/2019 at 05:29 point

Will clean up and publish the URL.

  Are you sure? yes | no

Similar Projects

Does this project spark your interest?

Become a member to follow this project and never miss any updates