将由arduino读取的变量发送到php脚本(电子收费系统)

时间:2013-02-01 21:13:10

标签: php arduino

我正在使用基于rfid的arduino构建电子收费系统;我想将标签的“唯一ID”(由arduino读取)发送到php脚本(存储在本地apache服务器根文件夹中)。我写了代码请指出错误,并查看以太网设置是否在程序中正确..

#include <SPI.h>
#include <Ethernet.h>
EthernetServer server(80);
byte mac[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
IPAddress ip(192,168,1,4);
EthernetClient client;
int  val = 0; 
char code[10]; 
int bytesread = 0; 
void setup() 
{ 
Ethernet.begin(mac, ip, gateway, subnet);
Serial.begin(9600); 
pinMode(2,OUTPUT);   
digitalWrite(2, HIGH);                 
}  

 void loop() <br>
{ 
 if(Serial.available() > 0) {          
    if((val = Serial.read()) == 10) {   
      bytesread = 0; 
      while(bytesread<10) {             
        if( Serial.available() > 0) { 
          val = Serial.read();
          if((val == 10)||(val == 13)) {  
            break;                       
          } 
          code[bytesread] = val;               
          bytesread++;                   
        }
      } 
      if(bytesread == 10) {             
       client.print("GET try.php?code=");
      client.print(code);

client.println(" HTTP/1.1");
client.println("Host: localhost");  
client.println();        
      } 
      bytesread = 0; <br>
      digitalWrite(2, LOW);                  
           delay(1500);                       
           digitalWrite(2, HIGH);                  // Activate the RFID reader
    } 
  } 
}
the php script:

<?php   
$variable = $_GET['code']
echo  "code is  $variable ";
?>

2 个答案:

答案 0 :(得分:1)

您忘记将EthernetClient连接到服务器了!看看Arduino documentation

if (client.connect(server, 80)) {
    Serial.println("connected");
    client.println("GET /search?q=arduino HTTP/1.0");
    client.println();
} else {
    Serial.println("connection failed");
}

在你的例子中,你必须写:

Serial.println("connected");
client.print("GET /try?code=");
client.print(code);
client.print(" HTTP/1.0");
client.println();

编辑:这是一个完整的例子:

替换

client.print("GET try.php?code=");
client.print(code);
client.println(" HTTP/1.1");
client.println("Host: localhost");
client.println();

if (client.connect(serverIP, 80)) {
    Serial.println("connected");
    client.print("GET /try?code=");
    client.print(code);
    client.print(" HTTP/1.0");
    client.println();
} else {
    Serial.println("connection failed");
}

并将其添加到声明

byte serverIP[] = { 127, 0, 0, 1 }; //That's localhost. Change it to whatever you need!

答案 1 :(得分:0)

在发送HTTP请求之前,似乎你错过了“client.connect(...)”连接到PHP服务器:

http://arduino.cc/en/Reference/EthernetClient