从ESP8266将传感器数据上传到Web服务器的文本文件

时间:2017-11-20 20:03:17

标签: php arduino iot esp8266

我使用以下代码将示例值上传到我的Web服务器:

它连接到我的路由器,只是以dir的名义上传一些示例数据。在我的服务器kecsmarthelmet.com中,我有一些Index,Upload.php等文件。

请求转到Upload.php,执行后输出文件返回空白。

#include <ESP8266WiFi.h>
// server to connect to and relative path to PHP script
char server[] = "www.kecsmarthelmet.com";
String phpScript = "/update.php";

// wifi network and password
const char* ssid = "SMARTHELMET";
const char* password = "kec123456";
int keyIndex = 0;
WiFiClient client;
int wifiStatus;

void setup() {
  // some data to send (fake wind sensor readings)
  float windDir = 380.0;
  // format datapoints as PHP arguments
  // this means easy parsing later in the PHP script
  String data = "&dir=" + String(windDir, 2);
  // required for Adafruit Feather M0 Wifi board
  // start serial connection for feedback
  Serial.begin(115200);
  delay(200);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Your are connecting to;");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  while (!Serial) {
    //
  }
  // is a wifi unit attached?
  Serial.println("Checking for wifi hardware...");
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("- none found, quitting...");
    while (true);
  }
  Serial.println("- found");
  // attempt to connect to WiFi network:
  wifiStatus = WiFi.status();
  while (wifiStatus != WL_CONNECTED) {
    Serial.print("Attempting to connect to: \"");
    Serial.print(ssid);
    Serial.println("\"");
    WiFi.begin(ssid, password);
    delay(10000); // wait 10 sec for connection
  }
  Serial.println("- connected!");
  // post data using HTTP POST
  Serial.println("Connecting to server...");
  if (client.connect(server, 80)) {
    Serial.println("- connected");
    Serial.println("Posting sensor data...");
    client.print("POST ");
    client.print(phpScript);
    client.println(" HTTP/1.1");
    client.println("Host: www.kecsmarthelmet.com");
    client.println("User-Agent: Arduino/1.0");
    client.println("Connection: close");
    client.println("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
    client.print("Content-Length: ");
    client.println(data.length());
    client.println();
    client.print(data);
    Serial.println(data);
    Serial.println("- done");
  }
  // disconnect when done
  Serial.println("Disconnecting from server...");
  client.stop();
  Serial.println("- bye!");
}

void loop() {
  // you could also move your HTTP POST code here, if you
  // wanted to post repeatedly
}

上传的PHP文件如下:

<?php
  $dir = $_POST["dir"];
  echo file_get_contents($dir);
  $file =  './current.txt';
  file_put_contents($file, $dir);
?>

在输出文件中执行。没有出现。它仍然是一片空白。

0 个答案:

没有答案