hi guys.
i want to post temperature data from nodemcu to localhost. the localhost is created with xamp on my laptop. (my ip of laptop is localhost ).
so first this is my diagram:
i get temp data from DHT22 and nodemcu send it to localhost. but when i connect nodemcu to wifi and post temp data to localhost , i get this result (-1 code that is httpcode):
what is the problem. pls help me.
nodemcu code:
#include "DHT.h"
#define DHTPIN 2 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE);
// For wifi and http connection
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
// connection to wifi
const char* ssid = "******";
const char* password = "********";
const char* post_link = "http://localhost"; // created with xamp , it is not different replacing with my ip laptop
void setup() {
Serial.begin(115200);
Serial.println(F("DHTxx test!"));
dht.begin();
WiFi.begin(ssid, password);
//Check for the connection
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
}
void loop() {
delay(2000);
// temp from DHT22
float t = dht.readTemperature();
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if ( isnan(t) || isnan(f)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
Serial.print(F("Temperature: "));
Serial.print(t);
Serial.println(F(" C "));
// convert it to string to post to localhost
String string_temp = String(t);
String postData = "tmp=" + string_temp;
// post
HTTPClient http; //Declare object of class HTTPClient
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
// Send and get Data
http.begin(post_link); //Specify request destination
http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header
int httpCode = http.POST(postData); //Send the request
Serial.println(httpCode); //Print HTTP return code
Serial.println(string_temp); //Print HTTP return code
}
}
and this is the php code for get tmp data and create a text file to localhost (htdoc) and save data in it.
php code:
<?php
$data=$_POST["tmp"];
file_put_contents("test.txt",$data);
?>