使用Arduino和Ethernet Shield执行PHP脚本

时间:2015-04-10 18:13:45

标签: get ethernet arduino-uno

我正在使用Arduino和以太网盾进行项目。

我想在循环中执行一个php脚本(驻留在我的服务器上)。

#include <SPI.h>
#include <Ethernet.h>

// MAC address from Ethernet shield sticker under board
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,77); // IP address, may need to change depending on network
EthernetServer server(80);  // create a server at port 80

String HTTP_req;            // stores the HTTP request

void setup()
{
    Ethernet.begin(mac, ip);  // initialize Ethernet device
    server.begin();           // start to listen for clients
    Serial.begin(9600);       // for diagnostics
}

void loop()
{
    EthernetClient client = server.available();  // try to get client

    if (client) {  // got client?
        boolean currentLineIsBlank = true;
        while (client.connected()) {
            if (client.available()) {   // client data available to read
                char c = client.read(); // read 1 byte (character) from client
                HTTP_req += c;  // save the HTTP request 1 char at a time
                Serial.print("connected");
                client.println("GET http://domain.com/arduino/scripts/script_motion_detection_driveway.php HTTP/1.0");
                client.println();
            } // end if (client.available())
        } // end while (client.connected())
        delay(1);      // give the web browser time to receive the data
        client.stop(); // close the connection
    } // end if (client)
}

当我运行代码并加载页面时,它不是执行脚本而是打印行:

GET http://domain.com/arduino/scripts/script_motion_detection_driveway.php HTTP/1.0

一遍又一遍......

它在循环中而不是设置的原因是因为最终GET请求将放在if语句中以测试条件。

执行脚本需要更改什么?

1 个答案:

答案 0 :(得分:0)

您应该查看此示例:http://www.arduino.cc/en/Tutorial/WebClient

您希望执行GET请求而不告诉客户端连接到端口80上的服务器。

if (client.connect(server, 80)) {

然后你发出你的http请求

// Make a HTTP request:
    client.println("GET /search?q=arduino HTTP/1.1");
    client.println("Host: www.google.com");
    client.println("Connection: close");
    client.println();

然后您尝试阅读请求

if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

通过以比上面的脚本更好的方式将这些部分组合在一起,您将成功获得php脚本的输出。