以下是代码:
#include <SPI.h>
#include <Ethernet.h>
#include <Wire.h>
#include <math.h>
//QQ群:51798659 XiaoHe此代码是用以太网连接yeelink平台实现点亮一个led,访问http://api.yeelink.net/v1.1/device/357400/sensor/405555/datapoints/后面提交的是key来获取一个网页信息,然后再加以提出需要的判断
byte buff[2];
int led=5;//led脚
// for yeelink api
#define APIKEY "c2a4877a26b7bd000872227c60b67406" // 此处替换为你自己的API KEY
#define DEVICEID 357400 // 此处替换为你的设备编号
#define SENSORID 405555 // 此处替换为你的传感器编号
char pd='v'; //写的一个字符判断
byte mac[] = { 0x00, 0x1D, 0x72, 0x82, 0x35, 0x9D};
EthernetClient client ;
char server[] = "api.yeelink.net"; // 连接 的服务器地址
unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
boolean lastConnected = false; // state of the connection last time through the main loop
const unsigned long postingInterval = 1*1000; // delay between 2 datapoints, 延时多少秒访问一次
String returnValue = "";
boolean ResponseBegin = false;
void setup() {
pinMode(5, OUTPUT);
Wire.begin();
Serial.begin(115200);
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
for(;;)
;
}
else {
Serial.println("Ethernet configuration OK");
}
}
void loop() {
if (client.available()) {
char c = client.read();
// Serial.print(c);
if (c == '{')
ResponseBegin = true;
else if (c == '}')
ResponseBegin = false;
if (ResponseBegin)
returnValue += c;
}
if (returnValue.length() !=0 && (ResponseBegin == false))
{
Serial.println(returnValue);//打印出接收的数据
pd=returnValue.charAt(9);//取第几位字符
Serial.print("Jie Shou de zifu:");//串口方便好看
Serial.println(pd);
if (pd == '1') {
Serial.println("turn ON ON ON ON the LED");
digitalWrite(led, HIGH);
}
else if(pd== '0') {
Serial.println("turn off off off the LED_____________");
digitalWrite(led, LOW);
}
returnValue = "";
}
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
Serial.print("yeelink:");
getData();
}
lastConnected = client.connected();
}
void getData(void) {
if (client.connect(server, 80)) {
Serial.println("connecting...");
// send the HTTP GET request:
client.print("GET /v1.1/device/");
client.print(DEVICEID);
client.print("/sensor/");
client.print(SENSORID);
client.print("/datapoints");
client.println(" HTTP/1.1");
client.println("Host: api.yeelink.net");
client.print("Accept: *");
client.print("/");
client.println("*");
client.print("U-ApiKey: ");
client.println(APIKEY);
client.println("Content-Length: 0");
client.println("Connection: close");
client.println();
Serial.println("print get done.");
}
else {
// if you couldn't make a connection:
Serial.println("connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
lastConnectionTime = millis();
}
这是api教程地址:
http://www.yeelink.net/developer/apidoc/11