【物联网】ESP32 + onenet + 按钮or模拟信号传感器,使用HTTP协议上传数据

最近在学习物联网的知识,之前总是在本地做一些传感器使用,感觉很无聊,后期想利用传感器和微信小程序进行数据实时观看,所以最近学习一下物联网知识。

本次物联网平台使用的是中国移动的onenet平台,使用的是新版本(旧版本的多协议接入新用户关闭了),刚刚学会怎么使用HTTP协议传输数据,现在将代码展示出来。

#include <Arduino.h>
#include<WiFi.h>
#include<HTTPClient.h>

const int button = 34;

const char* ssid = "xxxxxx";  //wifi名称
const char* passwd = "xxxxxxx";  //wifi密码
const char* token = "xxxx"; //token是onenet新平台的鉴权协议,需要使用token计算机生成。



HTTPClient http;


void setup() {

  pinMode(34, INPUT);

  Serial.begin(115200);
  WiFi.begin(ssid, passwd);
  while(WiFi.status() != WL_CONNECTED){
    delay(2000);
    Serial.println("Connecting to WiFi");
  }
  Serial.println("Connected to WiFi");
  http.begin("https://open.iot.10086.cn/fuse/http/device/thing/property/post?topic=$sys/w3j5oq7Z7c/123123/thing/property/post&protocol=HTTP");
  http.addHeader("token", token);
  http.addHeader("Content-Type", "application/json");

  //int httpResponseCode = http.POST(data);

}
void loop() {



  int button_res = digitalRead(34);

  if (button_res == HIGH){
    Serial.println("button down");

    String data= "{\"id\":\"123\",\"version\":\"1.0\",\"params\":{\"abc\":{\"value\":1},\"light\":{\"value\":1}}}";

    int httpResponseCode = http.POST(data);
    Serial.println("done");
    if (httpResponseCode > 0){
      Serial.print("HTTP Response code:");
      Serial.println(httpResponseCode);
      } 
    else {
      Serial.print("Error code:");
      Serial.println(httpResponseCode);
      }

    http.end();
    delay(1000);
  }
}

程序运行结果是当按下按钮时,向onenet平台传输数据,数据内容是value后面的值,如果想要实时的传输传感器数据,需要读取接口的模拟值,并格式化字符串结构,把上传值改掉。

注意,使用http协议的post请求上传数据,onenet平台是5s刷新一次,不能达到实时刷新。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值