Skip to content

Instantly share code, notes, and snippets.

@bfritscher
Created December 29, 2016 21:40
Show Gist options
  • Save bfritscher/2def62489a0fdacf6b0ad15aba4aefaf to your computer and use it in GitHub Desktop.
Save bfritscher/2def62489a0fdacf6b0ad15aba4aefaf to your computer and use it in GitHub Desktop.
esp8266 micropython plant sensor and vcc
import esp
from flashbdev import bdev
import machine
# https://github.com/micropython/micropython/issues/2352
ADC_MODE_VCC = 255
ADC_MODE_ADC = 0
def set_adc_mode(mode):
sector_size = bdev.SEC_SIZE
flash_size = esp.flash_size() # device dependent
init_sector = int(flash_size / sector_size - 4)
data = bytearray(esp.flash_read(init_sector * sector_size, sector_size))
if data[107] == mode:
return # flash is already correct; nothing to do
else:
data[107] = mode # re-write flash
esp.flash_erase(init_sector)
esp.flash_write(init_sector * sector_size, data)
print("ADC mode changed in flash; restart to use it!")
return
def get_adc_mode():
sector_size = bdev.SEC_SIZE
flash_size = esp.flash_size() # device dependent
init_sector = int(flash_size / sector_size - 4)
data = bytearray(esp.flash_read(init_sector * sector_size, sector_size))
return data[107]
import urequests
import time
if get_adc_mode() == ADC_MODE_VCC:
vcc = machine.ADC(1)
val = vcc.read()
time.sleep(2)
val = vcc.read()
payload = "plant_vcc,plant=%d value=%f\n" % (0, val)
set_adc_mode(ADC_MODE_ADC)
else:
a0 = machine.ADC(0)
a0.read()
time.sleep(2)
val = a0.read()
payload = "plant_hum,plant=%d value=%d\n" % (0, val)
set_adc_mode(ADC_MODE_VCC)
url = 'host'
headers = {'authorization': "Basic ...",'cache-control': "no-cache"}
resp = urequests.post(url, data=payload, headers=headers)
time.sleep(10)
# configure RTC.ALARM0 to be able to wake the device
rtc = machine.RTC()
rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
# set RTC.ALARM0 to fire after 7 min (waking the device)
rtc.alarm(rtc.ALARM0, 420000)
# put the device to sleep
machine.deepsleep()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment