import machine
import urequests 
from machine import Pin, SoftI2C, ADC
import network, time
import random
import json
import dht
analogpin= ADC(0)
sensor = dht.DHT11(Pin(14)) #D5 
temp=0
hum=0
HTTP_HEADERS = {'Content-Type': 'application/json'} 
THINGSPEAK_WRITE_API_KEY = 'NSKVEGFEZP0ML2JY'
THINGSPEAK_READ_API_KEY = 'YUMUNXAM1H6JKITA'

UPDATE_TIME_INTERVAL = 60000  # in 1 menit - 60000 
last_update = time.ticks_ms() 
ssid='AFKA'
password='77777777'

# Configure ESP as Station using SSID-Password wifi
sta_if=network.WLAN(network.STA_IF)
sta_if.active(True)
if not sta_if.isconnected():
    print('connecting to network...')
    sta_if.connect(ssid, password)
    while not sta_if.isconnected():
     pass
print('network config:', sta_if.ifconfig()) 
while True:
  try:
    time.sleep(10)
    sensor.measure()
    temp = sensor.temperature()
    hum = sensor.humidity()
    temp_f = temp * (9/5) + 32.0
    print('Temperature: %3.1f C' %temp)
    print('Temperature: %3.1f F' %temp_f)
    print('Humidity: %3.1f %%' %hum)
  except OSError as e:
    print('Failed to read sensor.')
  reading1 = analogpin.read()
  print('ADC: %3.1f ' %reading1)
  if time.ticks_ms() - last_update >= UPDATE_TIME_INTERVAL: 
     last_update = time.ticks_ms() 
     reading1 = analogpin.read()
     print(reading1)
     reading1volt=reading1 * 5.0 / 4095
     reading2 = random.getrandbits(8)
     reading2=temp
     reading3=hum
     var_readings = {'field1':reading1, 'field2':reading2,'field3':reading3} 
     request = urequests.post( 'http://api.thingspeak.com/update?api_key=' + THINGSPEAK_WRITE_API_KEY, json = var_readings, headers = HTTP_HEADERS )  
     request.close() 
     print(var_readings)
     #time.sleep(60)