I can usually figure out most Arduino issues but this has me beat. I am new to websites, HTML/PHP etc. My project (for now) is simply a test bed to send data from the Arduino to the localhost server on my PC,so no circuitry is involved. A lot of my code is working fine:
- Arduino connects to my WiFi network and stays connected.
- Arduino connects to my localhost server
- my PHP code runs and successfully writes a variable composed of a time marker and the received data from the Arduino to an html file which displays the variable.
The problem is than no data passes from the Arduino to $_POST[] in the PHP script, so no value gets written to the html file. The time marker successfully updates when I refresh the PHP scrip and html, so I know that is running OK. I suspect that something is wrong in this section of code:
void loop() {
postData = "Here are the data";
if (client.connect(server, 80)) {
Serial.println("Connected to Server");
client.println("POST /http://localhost/Firstphp/first.php HTTP/1.1");
client.println("Host: 192.168.1.4");
client.println("Content-Type: text/php");
client.print("Content-Length: ");
client.println(postData.length());
client.println();
client.print(postData);
Serial.println ("Still connected");
delay(3000);
}
}
When this code runs the if loop executes continuously, but just does not send anything to the PHP script.
Other relevant info:
- my PHP scrip is in a file called first.php which is in htdocs/Firstphp.
- I checked that the IP of my localhost is indeed 192.168.1.4
- I copied this code from elsewhere, but the original was designed to POST to a website on the internet, so some of the code was different. Probably the changes I made to address localhost instead are not valid? Any help GREATLY appreciated. Full code below:
Arduino Code:
//#include <SPI.h>
#include <WiFiNINA.h>
char ssid[] = "abcdef";
char pass[] = "ghijkl";
int count=0;
int status = WL_IDLE_STATUS;
char server[] ="192.168.1.4";
String postData;
WiFiClient client;
void setup() {
Serial.begin(9600);
while (status !=WL_CONNECTED){
Serial.print("Status: ");
Serial.println (WiFi.status());
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
delay(1000);
}
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
IPAddress ip = WiFi.localIP();
IPAddress gateway = WiFi.gatewayIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
void loop() {
postData = "Here are the data";
if (client.connect(server, 80)) {
Serial.println("Connected to Server");
client.println("POST /http://localhost/Firstphp/first.php HTTP/1.1");
client.println("Host: 192.168.1.4");
client.println("Content-Type: text/php");
client.print("Content-Length: ");
client.println(postData.length());
client.println();
client.print(postData);
Serial.println ("Still connected");
delay(3000);
}
}
PHP Script:
<?php $time = time(); echo $time; $temp = $_POST['temp']; $file = 'temp.html'; $data = $temp." . ".$time; file_put_contents($file, $data); ?>