020 - ESP32 MicroPython: RESTful APIs | Demo READ and WRITE

Introduction

In this article, we will learn a more complete usage of RESTful APIs which is bidirectional communication with the server that is both sending and requesting of data.

In article 018, I demonstrate sending of data to Thingspeak server using the HTTP POST method while in article 019, I demonstrate requesting of data from OpenWeather server using HTTP GET method.

This time, I would like to demonstrate both data writing and data reading to Thingspeak IoT platform using RESTful APIs.

Bill Of Materials

  1. ESP32 DOIT board with DHT sensor and an LED with limiting resistor.
  2. ESP32 Heltec boad.

Hardware Instruction

  1. Connect the ESP32 DOIT board 3.3V pin to DHT22 VCC pin.
  2. Connect the ESP32 DOIT board D23 pin to DHT22 DOUT pin.
  3. Connect the ESP32 DOIT board GND pin to DHT22 GND pin.
  4. Connect the LED anode pin through a limiting resistor to ESP32 DOIT board D22 pin.
  5. Connect the LED cathode pin to ESP32 DOIT board GND pin.
  6. Leave the Heltec ESP32 development without any connection. The OLED uses the ESP32 pin 15 for SCL and pin 4 for the SDA. The OLED RST pin should be tied to VCC. It was connected to ESP32 pin 16.

Video Demonstration

Call To Action

For any concern, write your message in the comment section.

You might also like to support my journey on Youtube by Subscribing. Click this to Subscribe to TechToTinker.

Thank you and have a good days ahead.

See you,

– George Bantique | tech.to.tinker@gmail.com

Source Code

1. ESP32 DOIT board with DHT22 sensor and LED:

 1# **************************************#
 2# Description:                          #
 3#   Contains MicroPython code for       #
 4# sending DHT sensor readings to        #
 5# Thingspeak server using RESTful APIs  #
 6# with urequests HTTP POST method.      #
 7# It also contains an LED that is       #
 8# dependent to the signal control from  #
 9# another client. This demonstrates the #
10# use of HTTP GET method.               #
11# --------------------------------------#
12# Author: George Bantique               #  
13#         TechToTinker Youtube Channel  # 
14#         TechToTinker.blogspot.com     # 
15#         tech.to.tinker@gmail.com      # 
16# Date: Nov.20, 2020                    #
17# --------------------------------------#
18# Please feel free to modify the code   # 
19# according to your needs.              # 
20# **************************************# 
21
22# ************************************** 
23# Load necessary libraries 
24import machine 
25import dht
26import network  
27import urequests
28import ujson as json
29import time 
30
31# ************************************** 
32# Create objects: 
33led = machine.Pin(2,machine.Pin.OUT)
34ext_led = machine.Pin(22, machine.Pin.OUT)
35d = dht.DHT22(machine.Pin(23)) 
36
37# ************************************** 
38# Configure the ESP32 wifi as STAtion 
39sta = network.WLAN(network.STA_IF) 
40if not sta.isconnected():  
41  print('connecting to network...')  
42  sta.active(True)  
43  sta.connect('your wifi ssid', 'your wifi password')  
44  while not sta.isconnected():  
45    pass  
46print('network config:', sta.ifconfig()) 
47
48# **************************************
49# Constants and variables:
50HTTP_HEADERS = {'Content-Type': 'application/json'} 
51UPDATE_TIME_INTERVAL = 3000  # in ms 
52last_update = time.ticks_ms() 
53
54# **************************************
55# Main loop:
56while True: 
57    if time.ticks_ms() - last_update >= UPDATE_TIME_INTERVAL:
58        # HTTP GET
59        response = urequests.get('https://api.thingspeak.com/channels/1242207/fields/1.json?api_key=CLDDS1LS1Y6A1LHD&results=1')
60        # check status code of the request 
61        if response.status_code == 200: 
62            # get the json format of data
63            data = response.json() 
64            field1 = str(data['feeds'][0]['field1'])
65            print(field1)
66            if field1=='1':
67                ext_led.value(1)
68            else:
69                ext_led.value(0)
70            
71        # HTTP POST
72        d.measure() 
73        t = d.temperature() 
74        h = d.humidity() 
75        dht_readings = {'field1':t, 'field2':h} 
76        request = urequests.post( 
77                  'http://api.thingspeak.com/update?api_key=V365HW2M3NZES7EW', 
78                  json = dht_readings, 
79                  headers = HTTP_HEADERS ) 
80        request.close() 
81        print(dht_readings)
82         
83        led.value(not led.value()) 
84        last_update = time.ticks_ms()

2: ESP32 Heltec board:

  1# **************************************#
  2# Description:                          #
  3#   Contains MicroPython code for       #
  4# requesting DHT sensor readings from   #
  5# Thingspeak server using RESTful APIs  #
  6# with urequests HTTP GET method.       #
  7# It also contains a button switch that #
  8# sent to the server to control the LED #
  9# of another client. This demonstrates  #
 10# the use of HTTP POST method.          #
 11# --------------------------------------#
 12# Author: George Bantique               #  
 13#         TechToTinker Youtube Channel  # 
 14#         TechToTinker.blogspot.com     # 
 15#         tech.to.tinker@gmail.com      # 
 16# Date: Nov.20, 2020                    #
 17# --------------------------------------#
 18# Please feel free to modify the code   # 
 19# according to your needs.              # 
 20# **************************************#
 21
 22# ************************************** 
 23# Load necessary libraries 
 24import machine 
 25import ssd1306
 26import network  
 27import urequests
 28import ujson as json
 29import time 
 30
 31# ************************************** 
 32# Create objects:
 33
 34# 1. oled object
 35rst = machine.Pin(16, machine.Pin.OUT)
 36rst.value(1)
 37i2c = machine.I2C(scl=machine.Pin(15), sda=machine.Pin(4), freq=400000)
 38oled = ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
 39
 40# 2. button switch object
 41press = False
 42def sw_press(pin):
 43    global press
 44    press = True
 45but = machine.Pin(21, machine.Pin.IN, machine.Pin.PULL_UP)
 46but.irq(trigger=machine.Pin.IRQ_FALLING, handler=sw_press)
 47
 48# 3. led switch
 49led = machine.Pin(25, machine.Pin.OUT)
 50
 51# # ************************************** 
 52# # Configure the ESP32 wifi as STAtion 
 53sta = network.WLAN(network.STA_IF) 
 54if not sta.isconnected():  
 55  print('connecting to network...')  
 56  sta.active(True)  
 57  sta.connect('your wifi ssid', 'your wifi password')   
 58  while not sta.isconnected():  
 59    pass  
 60print('network config:', sta.ifconfig()) 
 61
 62# # **************************************
 63# # Constants and variables:
 64HTTP_HEADERS = {'Content-Type': 'application/json'} 
 65UPDATE_TIME_INTERVAL = 3000  # in ms 
 66last_update = time.ticks_ms()
 67led_state = '0'
 68
 69# **************************************
 70# Main loop:
 71while True: 
 72    if time.ticks_ms() - last_update >= UPDATE_TIME_INTERVAL:
 73        
 74        # HTTP POST
 75        if press:
 76            press = False
 77            if led_state == '0':
 78                led_state = '1'
 79            else:
 80                led_state = '0'
 81                
 82        sw_press = {'field1':led_state} 
 83        request = urequests.post('http://api.thingspeak.com/update?api_key=F8OG056AW2SEQBW6', 
 84                  json = sw_press, 
 85                  headers = HTTP_HEADERS ) 
 86        request.close() 
 87        print(sw_press)
 88
 89        # HTTP GET
 90        response = urequests.get('https://api.thingspeak.com/channels/1242204/feeds.json?api_key=CM2XQ37C1PWGHCJ9&results=1')
 91        
 92        if response.status_code == 200:
 93            data = response.json()
 94            # first is store the json response to data variable
 95            # then parse the fields from feeds list
 96            # [0] -> converts list to dictionary
 97            field1 = str(data['feeds'][0]['field1'])
 98            field2 = str(data['feeds'][0]['field2'])
 99            oled.fill(0)
100            oled.text('RESTful API Demo', 0, 5)
101            oled.text('Temp:{} oC' .format(field1), 20, 25)
102            oled.text('Humi:{} %' .format(field2), 20, 35)
103            oled.show()
104            #print('response OK')
105        else:
106            print('Error in HTTP request')
107            oled.fill(0)
108            oled.text('Error in HTTP', 10, 5)
109            oled.text('request!', 10, 15)
110            oled.show()
111            #print('response ERR')
112        led.value(not led.value()) 
113        last_update = time.ticks_ms()


Posts in this series



No comments yet!

GitHub-flavored Markdown & a sane subset of HTML is supported.