I’ve been looking for a way of storing Voltage and Climate information on the internet and I have modified your example Thingspeak code which works fine (thank you) and has been uploading data reliably for 5 days.
I wanted to be sure the system is reliable and I am not sure if it would be best to put the ESP into sleep mode and wake up at regular intervals or is there a ‘watchdog’ routine I could use to ensure the device is running and traps disconnection or upload failures. Could I use the error code request.txt to trigger something ?
Thanks Peter
-------------------------- # modified project details from https://RandomNerdTutorials.com from time import sleep import network import urequests import urandom def randint(min, max): span = max - min + 1 div = 0x3fffffff // span offset = urandom.getrandbits(30) // div val = min + offset return val import esp esp.osdebug(None) import gc gc.collect() #ssid = 'REPLACE_WITH_YOUR_SSID' #password = 'REPLACE_WITH_YOUR_PASSWORD' api_key = 'xxxxx' station = network.WLAN(network.STA_IF) station.active(True) station.connect(ssid, password) while station.isconnected() == False: pass print('Connection successful') print(station.ifconfig()) temp = '12' hum = '70' volt = 28 while True: volt = randint(18,30) volt = str(volt) temp = randint(15,32) temp = str(temp) hum = randint(45,65) hum = str(hum) sensor_readings = {'field1':temp, 'field2':hum, 'field3':volt} print(sensor_readings) request_headers = {'Content-Type': 'application/json'} request = urequests.post('http://api.thingspeak.com/update?api_key=' + api_key, json=sensor_readings,headers=request_headers) print(request.text) request.close() sleep(40) ------------------
PS, I’ve just noticed your editor removes tabs from MicroPython code
Hello Peter, to make an HTTP POST request to ThinkSpeak API, you must send the api_key in the JSON parameter. Please modify your code like this:
http_request = {'api_key': api_key,'field1':temp, 'field2':hum, 'field3':volt} print(http_request) request_headers = {'Content-Type': 'application/json'} request = urequests.post('http://api.thingspeak.com/update, json=http_request ,headers=request_headers)
Can you try it? Does that work for you?
At the moment I only have examples for ThingSpeak with Arduino IDE: