I have ESP8266 ESP-12E with microswitch connected to GPIO13 (and ground).
I want to send (preferably using HTTP POST but I'm open to something else if it's bad choice) duration of time holding down the button and time counting from ESP8266 start to the time when the button is pushed.
Here is what I coded so far:
#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);
}
}
}
However, my code is wrong because I need to wait for the request to be completed before pushing down the button again.
I'm thinking about putting duration
and startTime
in some arrays using interrupts, eg.:
attachInterrupt(13, buttonClick, CHANGE);
and then I could continuously check if the arrays contains new clicks and send them to the server.
But I'm not sure if that would work and I have too little experience in Arduino/C in general. Any help would be appreciated.