我正在尝试获取一个 PHP 网页,以通过 Apache Web 服务器从带有以太网屏蔽的Arduino Uno获取温度读数。我正在将温度读数写入一个文本文件,然后使用两个 PHP 文件将其从那里带到PHP网页上。
但是,我无法将温度读数写入文本文件。我不确定 Arduino 代码是否不正确并且没有发送温度读数,或者 PHP 代码是否不正确并且没有接收温度读数。当我从网页读回串行监视器时,我知道 Arduino 和网页正在通信。
Arduino代码
#include <Ethernet.h> //Library for Ethernet functions
#include <SPI.h>
#include <Client.h> //Library for client functions
byte MACaddress[] = {0x90, 0xA2, 0xDA, 0x0D, 0x8B, 0xB3}; //Replace with your Ethernet shield MAC address
byte IPaddress[] = { 192,168,1,102}; //The Arduino device IP address
byte subnet[] = { 255,255,255,0};
byte gateway[] = { 192,168,0,1};
IPAddress server(192,168,1,100); // IP address of server the Arduino sends data to
EthernetClient client;
bool connected = false;
int sensorInPin = 0;
float temperature = 0;
void setup(void)
{
Serial.begin(9600);
Serial.println("Initializing Ethernet.");
delay(1000);
Ethernet.begin(MACaddress);
Serial.println("LM35 Sensor ");
analogReference(INTERNAL);
}
void printTenths(int value)
{
// Prints a value of 123 as 12.3
Serial.print(value / 100);
Serial.print(".");
Serial.println(value % 10);
}
void loop(void)
{
int span = 20;
int aRead = 0;
for (int i = 0; i < span; i++)
{
aRead = aRead + analogRead(sensorInPin);
}
aRead = aRead / 20;
temperature = ((100 * 1.1 * aRead)/99) * 10;
if (!connected)
{
Serial.println("Not connected");
if (client.connect(server,80))
{
connected = true;
//int temp = analogRead(A1);
Serial.print("Temp is ");
Serial.println(temperature);
Serial.println();
Serial.println("Sending to Server: ");
client.print("GET /arduino.php?t0=\n");
Serial.print("GET /arduino.php?t0=\n");
client.print(temperature);
Serial.print(temperature);
Serial.println();
client.println();
client.println("HTTP/1.1\r\n");
Serial.println();
Serial.println("HTTP/1.1\r\n");
client.println("Host: localhost\r\n");
Serial.println("Host: localhost\r\n");
client.println();
client.println("User-Agent: Arduino\r\n");
Serial.println("User-Agent: Arduino\r\n");
client.println("Accept: text/html\r\n");
Serial.println("Accept: text/html\r\n");
client.println();
Serial.println();
delay(1000);
}
else
{
Serial.println("Cannot connect to Server");
}
}
else
{
delay(1000);
while (client.connected() && client.available())
{
char c = client.read();
Serial.print(c);
}
Serial.println();
client.stop();
connected = false;
}
}
Arduino.php 代码
<?php
echo date("d.m.Y-H:i:s");
file_put_contents("C:\Folder\Mechatronics Application\Semester 2\Project \Hello.txt",$_GET['t0']);
?>
index.php 代码
<?php
echo date("d.m.Y-H:i:s");
$string1 = file_get_contents("C:\Folder\Mechatronics Application\Semester 2\Project\Hello.txt");
echo $string1;
?>