#include <ESP8266.h> #include <dht11.h> #include <SoftwareSerial.h> #include <WiFi.h> #include <Servo.h> #include <ArduinoJson.h> // 引入 ArduinoJson 库

// 配置 ESP8266 WIFI 设置 #define SSID 'HONOR Play4T' // 填写 2.4GHz 的 WIFI 名称,不要使用校园网 #define PASSWORD '12345678' // 填写自己的 WIFI 密码 #define HOST_NAME 'api.heclouds.com' // API 主机名称,连接到 OneNET 平台,无需修改 #define DEVICE_ID '1099655073' // 填写自己的 OneNET 设备 ID #define HOST_PORT (80) // API 端口,连接到 OneNET 平台,无需修改 String APIKey = 'IiJSs17atNND2C77wumz03w63hw='; // 与设备绑定的 APIKey String lightDatastreamId = 'light'; // 光线数据流 ID #define INTERVAL_SENSOR 5000 // 定义传感器采样及发送时间间隔

// 创建 dht11 示例 dht11 DHT11; // 创建舵机 Servo myservo; int servoPin = 7; int light = 0; int servoPos = 0; // 定义 DHT11 接入 Arduino 的管脚 #define DHT11PIN 4

// 定义 ESP8266 所连接的软串口 /*********************

  • 该实验需要使用软串口
  • Arduino 上的软串口 RX 定义为 D3,
  • 接 ESP8266 上的 TX 口,
  • Arduino 上的软串口 TX 定义为 D2,
  • 接 ESP8266 上的 RX 口.
  • D3 和 D2 可以自定义,
  • 但接 ESP8266 时必须恰好相反 *********************/ SoftwareSerial mySerial(3, 2); ESP8266 wifi(mySerial);

void handleCommand(String command) { Serial.print('Command received: '); Serial.println(command);

if (command == '0') { // 控制舵机转到 0 度位置 myservo.write(0); servoPos = 0; light = 0; Serial.println('Servo position: 0'); myservo.write(servoPos); } else if (command == '1') { // 控制舵机转到 180 度位置 myservo.write(180); servoPos = 180; light = 1; Serial.println('Servo position: 180'); myservo.write(servoPos); } else { Serial.println('Invalid command'); } }

void setup() { mySerial.begin(115200); // 初始化软串口 Serial.begin(9600); // 初始化串口 Serial.print('setup begin\r\n');

myservo.attach(servoPin); myservo.write(0);

// 以下为 ESP8266 初始化的代码 Serial.print('FW Version: '); Serial.println(wifi.getVersion().c_str());

if (wifi.setOprToStation()) { Serial.print('to station ok\r\n'); } else { Serial.print('to station err\r\n'); }

// ESP8266 接入 WIFI if (wifi.joinAP(SSID, PASSWORD)) { Serial.print('Join AP success\r\n'); Serial.print('IP: '); Serial.println(wifi.getLocalIP().c_str()); } else { Serial.print('Join AP failure\r\n'); } Serial.println(''); Serial.print('DHT11 LIBRARY VERSION: '); Serial.println(DHT11LIB_VERSION);

mySerial.println('AT+UART_CUR=9600,8,1,0,0'); mySerial.begin(9600); Serial.println('setup end\r\n'); }

unsigned long net_time1 = millis(); // 数据上传服务器时间

void loop() { if (net_time1 > millis()) net_time1 = millis();

if (millis() - net_time1 > INTERVAL_SENSOR) { // 发送数据时间间隔 int chk = DHT11.read(DHT11PIN);

Serial.print('Read sensor: ');
switch (chk) {
  case DHTLIB_OK:
    Serial.println('OK');
    break;
  case DHTLIB_ERROR_CHECKSUM:
    Serial.println('Checksum error');
    break;
  case DHTLIB_ERROR_TIMEOUT:
    Serial.println('Time out error');
    break;
  default:
    Serial.println('Unknown error');
    break;
}

float sensor_hum = (float)DHT11.humidity;
float sensor_tem = (float)DHT11.temperature;
Serial.print('Humidity (%): ');
Serial.println(sensor_hum, 2);

Serial.print('Temperature (oC): ');
Serial.println(sensor_tem, 2);
Serial.println('');

if (wifi.createTCP(HOST_NAME, HOST_PORT)) { // 建立 TCP 连接,如果失败,不能发送该数据
  Serial.print('create tcp ok\r\n');
  char buf[10];

  // 拼接发送 data 字段字符串
  String jsonToSend = '{\'Temperature\':';
  dtostrf(sensor_tem, 1, 2, buf);
  jsonToSend += '\'' + String(buf) + '\'';
  jsonToSend += ',\'Humidity\':';
  dtostrf(sensor_hum, 1, 2, buf);
  jsonToSend += '\'' + String(buf) + '\'';

  // 从 OneNET 获取 light 数据流
  String getDatastream = '/devices/';
  getDatastream += DEVICE_ID;
  getDatastream += '/datastreams/';
  getDatastream += lightDatastreamId;
  getDatastream += '?';
  getDatastream += 'datastream_id=';
  getDatastream += lightDatastreamId;
  getDatastream += '\r\n';
  getDatastream += 'api-key:';
  getDatastream += APIKey;
  getDatastream += '\r\n';
  getDatastream += 'Host:api.heclouds.com\r\n';
  getDatastream += 'Connection:close\r\n';
  getDatastream += '\r\n';
  String getArray = getDatastream.c_str();
  wifi.send((const uint8_t *)getArray, strlen(getArray)); // 发送 GET 请求
  Serial.println('send success');

  // 等待服务器响应
  delay(1000);
  while (wifi.available()) {
    String message = wifi.recvString();
    Serial.println(message);

    // 解析响应数据流中的 light 值
    DynamicJsonDocument doc(1024);
    deserializeJson(doc, message);
    light = doc['data']['current_value'];
  }

  // 判断光线强度,控制舵机
  if (light == 0) {
    myservo.write(0);
    servoPos = 0;
    Serial.println('Servo position: 0');
    myservo.write(servoPos);
  } else if (light == 1) {
    myservo.write(180);
    servoPos = 180;
    Serial.println('Servo position: 180');
    myservo.write(servoPos);
  }

  // 拼接 POST 请求字符串
  jsonToSend += ',\'Light\':';
  jsonToSend += light;
  jsonToSend += '}';
  String postString = 'POST /devices/';
  postString += DEVICE_ID;
  postString += '/datapoints?type=3 HTTP/1.1';
  postString += '\r\n';
  postString += 'api-key:';
  postString += APIKey;
  postString += '\r\n';
  postString += 'Host:api.heclouds.com\r\n';
  postString += 'Connection:close\r\n';
  postString += 'Content-Length:';
  postString += jsonToSend.length();
  postString += '\r\n';
  postString += '\r\n';
  postString += jsonToSend;
  postString += '\r\n';
  postString += '\r\n';
  postString += '\r\n';

  const char *postArray = postString.c_str(); // 将 str 转化为 char 数组

  Serial.println(postArray);
  wifi.send((const uint8_t *)postArray, strlen(postArray)); // send 发送命令,参数必须是这两种格式,尤其是 (const uint8_t*)
  Serial.println('send success');

  if (wifi.releaseTCP()) { // 释放 TCP 连接
    Serial.print('release tcp ok\r\n');
  } else {
    Serial.print('release tcp err\r\n');
  }
  postArray = NULL; // 清空数组,等待下次传输数据
} else (Serial.print('create tcp err\r\n'));
Serial.println('');
net_time1 = millis();

} }

ESP8266 + DHT11 温湿度传感器 + OneNET + 舵机控制 - 从 OneNET 获取光线数据控制舵机

原文地址: https://www.cveoy.top/t/topic/oM2P 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录