main.py
Код: Выделить всё
from machine import ADC, Pin
import umqtt.robust as mqtt
import json
import utime
import urequests
import network, time
import os
# Soil moisture sensor reading setup
soil = ADC(Pin(26))
min_moisture = 29799
max_moisture = 46059
# Data sending interval in seconds
delay_seconds = 5
# Configure WiFi connection details
ssid = "WIFI_NAME"
password = "WIFI_PASS"
# Function to read sensor data
def read_moisture():
while True:
moisture = (max_moisture-soil.read_u16())*100/(max_moisture-min_moisture)
print("moisture: " + "%.2f" % moisture +"% (adc: "+str(soil.read_u16())+")")
return moisture
# Function to connect to WiFi
def connect_wlan():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
while not wlan.isconnected():
print("Connecting to WiFi...")
wlan.connect(ssid, password)
utime.sleep(2)
print("Connected to WiFi")
return wlan
def send_data_to_thingsboard(moisture_value):
try:
client = mqtt.MQTTClient(client_id='CLIENT_ID', server='thingsboard.cloud', port=1883, user='ACCESS_TOKEN')
client.connect()
data = {"moisture": moisture_value}
client.publish("v1/devices/me/telemetry", json.dumps(data))
client.disconnect()
print(f"Data sent to ThingsBoard: {moisture_value}")
except Exception as e:
print(f"Error sending data: {e}")
def main():
wlan = connect_wlan()
data_queue = []
while True:
try:
moisture = read_moisture()
data_queue.append(moisture)
if wlan.isconnected() and data_queue:
while data_queue:
moisture_value = data_queue.pop(0)
send_data_to_thingsboard(moisture_value)
except OSError as e:
print(f"WiFi connection lost: {e}")
wlan = connect_wlan() # Attempt to reconnect
time.sleep(1)
if __name__ == "__main__":
main()
`
Отображение оболочки в Thonny:
Код: Выделить всё
Connected to WiFi moisture: -1.97% (adc: 46411) Error sending data: object of type 'NoneType' has no len() Подробнее здесь: https://stackoverflow.com/questions/787 ... -len-error