背景:
- Arduino需要发送4个sensor数据给server。
- 使用的网络模块为Ethernet W5100网络扩展板开发板模块。
- 库文件为arduino 自带的Ethernet.h。
- server上是php写的表格数据。发送数据前需要加入一个api_key。
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
EthernetClient client;
int HTTP_PORT = 8080;
String HTTP_METHOD = "POST";
char HOST_NAME[] = "xx.xx.xx.xx";
String PATH_NAME = "/ss/.php";
String queryString = "?api_key=aaa&value1=26&value2=70&value3=30&sensor=Ardiono&location=aa";
void setup()
{
Serial.begin(9600);
if (Ethernet.begin(mac) == 0)
{
Serial.println("Failed to obtaining an IP address using DHCP");
while(true);
}
if(client.connect(HOST_NAME,HTTP_PORT))
{
Serial.println("Connected to server");
client.println(HTTP_METHOD + " " + PATH_NAME + " HTTP/1.1");//
client.println("Host: " + String(HOST_NAME));
client.println("Connection: close\r\nContent-Type: application/x-www-form-urlencoded");//;
client.println("Content-Length: "); client.println(queryString.length());client.println();//
client.println(queryString);
while(client.connected())
{
if(client.available()){
char c = client.read();
Serial.print(c);
}
}
// the server's disconnected, stop the client:
client.stop();
Serial.println();
Serial.println("disconnected");
}
else
{// if not connected:
Serial.println("connection failed");
}
}
void loop()
{
}
以上code这次测验好些回。
之前测试过好几次,发现连上的是bad request,如下图:
request 修正后,提示API key error,如下:
?真是一波三折,最终还是调好了,以前没有整过网络通讯,对client,server通讯不太了解。
?
|