欢迎光临散文网 会员登陆 & 注册

ESP8266连接服务器实现数据传输(http协议)

2023-01-18 19:54 作者:悲匠  | 我要投稿

前言:

本次试验我所用的硬件:esp8266,云服务器(宝塔),超声波传感器。通过esp8266发送get请求与服务器交互并保存数据到数据库

1.服务端代码

服务器用php写了一个接口接收GET请求数据存入数据库并返回json,代码如下:


<?php
    //设置json格式头部
    header('Content-type: application/json');
	$conn=mysql_connect("数据库地址","数据库用户名","数据库密码"); //连接数据库地址、用户名、密码
	mysql_query("set names 'utf8'"); //数据库编码
	mysql_select_db("数据库名称"); //数据库名称
    $time = time();//获取当前时间戳
    //获取GET请求参数
    $code = $_GET['code'];
    $hight = $_GET['hight'];

    if($hight != null){
            $sql = "INSERT INTO text (idd,time)VALUES ('$hight','$time')";
            $rs=mysql_query($sql);
            $sql1="select * from text order by rand( ) limit 1";
            $row1=mysql_fetch_assoc(mysql_query($sql1));
            //输出json
            echo json_encode(array('code'=>200,'data'=>$row1['hight']));
    }
  //输出json
	if($code = null){
  echo json_encode(array('code'=>400,'data'=>"code is null"));
    }else($hight){
  echo json_encode(array('code'=>401,'data'=>"hight is null"));
    }
?>		

2.esp8266代码

esp8266主要通过get请求将数据作为参数提交到服务器

#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>

const char *ssid = "wifi名称";
const char *password = "wifi密码";
const int trigPin = 15;//超声波引脚
const int echoPin = 13;//超声波引脚

float duration;//超声波数据
float distance;//超声波数据

void setup()
{
  //初始化代码
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(dian, OUTPUT);
  digitalWrite(dian, LOW);
  Serial.begin(9600);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
//wifi连接
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("网络连接成功 IP:");
  Serial.print(WiFi.localIP());
}

void loop()
{
  //超声波启动
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);//获取超声波原始数据
  distance = duration * 0.034 / 2.0;//处理原始数据转换为cm
  post(distance);//将超声波数据上传到服务器
  Serial.println("水位:");
  Serial.println(distance,"200");
  
}
//post函数,用于上传数据到服务器并且接收返回的json
void post(float hight,String code) {
  WiFiClient client;
  HTTPClient hc;
  String a = String(hight);//将获取的超声波数据(float)转换为String类型
  String url = "http://127.0.0.1/api.php?hight=" + a;//拼接请求
  hc.begin(client, url);

  int httpCode = hc.GET();
  if (httpCode == HTTP_CODE_OK)
  {
    //请求成功
    String responsePayload = hc.getString();
    Serial.println("数据上传成功:");
    Serial.println(responsePayload);//获取服务器返回的响应有效负载json数据
  }
  else
  {
    Serial.println("数据上传失败:");
    Serial.print(httpCode);//获取错误状态码
  }

  hc.end();
}

3.测试

3.1使用arduino烧录esp8266

打开串口监视器

打开数据库查看数据是否写入

最后:通过上面的方法可以实现远程数据采集,通过获取服务器响应有效负载可以实现远程开关等等

ESP8266连接服务器实现数据传输(http协议)的评论 (共 条)

分享到微博请遵守国家法律