ESP8266 DHT11 传感器数据上传至OneNet并控制舵机
#include <DHT.h> #include <ESP8266WiFi.h> #include <WiFiClientSecure.h> #include <Servo.h>
#define DHTPIN 4 // 设置传感器引脚 #define DHTTYPE DHT11 // 选择传感器类型
DHT dht(DHTPIN, DHTTYPE);
const char* ssid = 'HONOR Play4T'; // 替换为您的Wi-Fi网络名称 const char* password = '12345678'; // 替换为您的Wi-Fi密码
const char* host = 'api.heclouds.com'; // 替换为您云平台的主机地址
// OneNet平台的API参数 const char* apiKey = 'IiJSs17atNND2C77wumz03w63hw='; // 替换为您的API Key const char* deviceId = '1099655073'; // 替换为您的设备ID
WiFiClientSecure client; Servo servo;
void setup() { Serial.begin(9600); dht.begin(); connectToWiFi(); servo.attach(5); // 将舵机连接到GPIO 5 }
void loop() { float humidity = dht.readHumidity(); float temperature = dht.readTemperature();
if (!isnan(humidity) && !isnan(temperature)) { uploadDataToCloud(humidity, temperature); }
delay(2000); // 延迟2秒
float lightValue = getLightValueFromCloud();
if (!isnan(lightValue)) { controlServo(lightValue); } }
void connectToWiFi() { Serial.print('Connecting to Wi-Fi...'); WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print('.'); }
Serial.println(' Connected to Wi-Fi'); }
void uploadDataToCloud(float humidity, float temperature) { String payload = '{'humidity':{'value':' + String(humidity) + '},'temperature':{'value':' + String(temperature) + '}}';
Serial.print('Connecting to cloud platform...');
if (client.connect(host, 443)) { client.println('POST /devices/' + String(deviceId) + '/datapoints HTTP/1.1'); client.println('Host: ' + String(host)); client.println('Content-Type: application/json'); client.println('Content-Length: ' + String(payload.length())); client.println(); client.println(payload); client.println();
Serial.println('Data uploaded to cloud platform');
} else { Serial.println('Failed to connect to cloud platform'); }
delay(500); }
float getLightValueFromCloud() { float lightValue;
Serial.print('Connecting to cloud platform...');
if (client.connect(host, 443)) { client.print('GET /devices/' + String(deviceId) + '/light_value/latest HTTP/1.1 ' + 'Host: ' + String(host) + ' ' + 'Api-Key: ' + String(apiKey) + ' ' + 'Connection: close
');
while (client.connected()) {
String line = client.readStringUntil('
'); if (line.startsWith(''value':')) { lightValue = line.substring(9).toFloat(); break; } }
Serial.print('Light value from cloud platform: ');
Serial.println(lightValue);
} else { Serial.println('Failed to connect to cloud platform'); }
return lightValue; }
void controlServo(float lightValue) { int angle = map(lightValue, 0, 100, 0, 180); // 将light值映射到0-180度舵机角度 servo.write(angle); // 控制舵机角度
原文地址: https://www.cveoy.top/t/topic/oNsx 著作权归作者所有。请勿转载和采集!