我目前在将从温度传感器收集的数据发送到我的Raspberry Pi时遇到问题。 Pi说它还没有收到任何数据。我也不确定GET和POST是如何工作的。我对这些东西比较陌生,所以任何帮助都会非常感激。
NodeMCU代码:
#include <ESP8266WiFi.h>
#include <OneWire.h>
#include <DallasTemperature.h>
//#include <WiFiEspClient.h>
/********************************************************************/
// Data wire is plugged into pin 2 on the Arduino
#define ONE_WIRE_BUS D4
/********************************************************************/
// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
/********************************************************************/
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
// Init library
WiFiClient client;
//dht DHT;
// Wifi config, ssid = wifi name & password = wifi password
const char* ssid = "ATkudnisdb0TAbEdfhrsdhg7i2";
const char* password = "2pkpmp3niagfdhgsdfhg%";
// Get data host
const char* host = "172.168.2.143";
// Your domain remember don't add slash at the end or http it will not work
const char* streamId = "collectdata.php";
// Sensor values
//int humidityValue = 0;
int tempValue = 0;
void sendRequest(){
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
}
// We now create a URI for the request
String url = "/php/";
url += streamId;
url += "?temp=";
url += tempValue;
Serial.print("Requesting URL: ");
Serial.println(url);
// This will send the request to the server
client.print("POST " + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
delay(1000);
Serial.println();
Serial.println("closing connection");
delay(2500);
}
void setup() {
sensors.begin();
Serial.begin(9600);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
//digitalWrite(blue, HIGH);
}
void loop() {
Serial.print(" Requesting temperatures...");
sensors.requestTemperatures();
tempValue = sensors.getTempCByIndex(0);
Serial.print(tempValue);
// Send the command to get temperature readings
sendRequest();
}
PHP代码:
<?php
$servername = “localhost”;
$username = “esp8266”;
$password = “Tutorial”;
$dbname = “esp8266”;
$mood = $_GET[‘mood’];
$conn = mysql_connect(“localhost”,”esp8266”,”Tutorial”);
if(!$conn) {
die(‘Could not connect: ’ . mysql_error());
}
$datenow = date(‘Y-m-d’);
$sql = “INSERT INTO `JSDataTable`(`logdate`,`mood`) VALUES (\”$datenow\”,\”$mood\”)”;
$result = mysql_query($sql);
if(!result) {
die(‘Invalid query: ‘ . mysql_error());
}
echo “<h1>The data has been sent!</h1>”;
mysql_close($conn);
?>