我有 ESP8266 ESP-12E,微动开关连接到 GPIO13(和接地)。
我想发送(最好使用 HTTP POST,但如果选择不好,我愿意接受其他事情)按住按钮的持续时间和从 ESP8266 开始到按下按钮的时间的时间。
这是我到目前为止编码的内容:
#include <ESP8266WiFi.h>
long duration = 0;
long startTime = 0;
const char* ssid = "SSID";
const char* password = "password";
void sendClick(int startTime, int duration) {
char* server = "192.168.0.15";
Serial.println(server);
WiFiClient client;
if (client.connect(server,80)) {
String postStr = "id=1&time=";
postStr += String(startTime);
postStr +="&duration=";
postStr += String(duration);
postStr += "\n";
client.print("POST /click HTTP/1.1\n");
client.print("Host: ");
client.print(server);
client.print("\n");
client.print("Connection: close\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);
client.stop();
}
}
void setup() {
Serial.begin(115200);
pinMode(13, INPUT_PULLUP);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
if (digitalRead(13) == LOW) {
delay(25); //for eliminating microswitch's bounce
if (digitalRead(13) == LOW) {
duration = 25;
startTime = millis();
while (digitalRead(13) == LOW) {}
duration += millis()-startTime;
Serial.print("Duration: ");
Serial.print(duration);
Serial.print(" startTime: ");
Serial.print(startTime);
Serial.print("\r\n");
sendClick(startTime, duration);
}
}
}
但是,我的代码是错误的,因为我需要等待请求完成才能再次按下按钮。
我正在考虑使用中断将duration
和放入一些数组中,例如:startTime
attachInterrupt(13, buttonClick, CHANGE);
然后我可以不断检查数组是否包含新的点击并将它们发送到服务器。
但我不确定这是否可行,而且我在 Arduino/C 方面的经验通常太少。任何帮助,将不胜感激。