Goal
Write a sketch that implements a minigame, using a piezo sensor and a LED. It works as the following :
- during setup, it intialize a connection to the wifi access point, to obtain an IP address,
- in the loop :
- wait for 5 second,
- light on the LED for a random amount of time between 500 and 2000 ms,
- wait for the user to tap on the piezo and compute the time elapsed from the moment the LED lighted off.
- print that time on serial and send it to the web server on 192.168.0.2, with a GET request. URI is : echo_get.php?string=val, where val is the value to send so the elapsed time.
Solution
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
// PB: for esp32, must include #include <WiFi.h>
#define PIN_PIEZZO A0
#define PIN_LED D1
#define STATE_IDLE 0
#define STATE_LED 1
#define STATE_TAP 2
int state = STATE_IDLE;
unsigned long t = 0;
WiFiClient client;
HTTPClient http;
void sendRequest(String val) {
http.begin(client, "http://192.168.0.2/echo_get.php?string="+val);
int httpCode = http.GET();
if (httpCode > 0) {
Serial.printf("HTTP Response Code: %d\n", httpCode);
String payload = http.getString();
Serial.println("Response:");
Serial.println(payload);
} else {
Serial.printf("Request failed: %s\n",
http.errorToString(httpCode).c_str());
}
http.end();
}
void setupWifi() {
const char *ssid = "testingiot"; // the ssid of the AP
const char *password = "testingiot"; // the password of the AP
WiFi.setAutoConnect(false);
WiFi.setSleepMode(WIFI_NONE_SLEEP);
WiFi.mode(WIFI_STA); // setup as a wifi client
WiFi.begin(ssid,password); // try to connect
while (WiFi.status() != WL_CONNECTED) { // check connection
delay(500);
Serial.print(".");
}
// debug messages
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
}
void setup() {
Serial.begin(115200);
pinMode(PIN_LED, OUTPUT);
delay(500);
Serial.println("Starting game");
setupWifi();
}
void loop() {
if (state == STATE_IDLE) {
delay(5000);
state = STATE_LED;
}
else if (state == STATE_LED) {
int wait = random(500, 2000);
digitalWrite(PIN_LED, HIGH);
delay(wait);
digitalWrite(PIN_LED, LOW);
t = millis();
state = STATE_TAP;
}
else if (state == STATE_TAP) {
int level = analogRead(PIN_PIEZZO);
if ( level > 500) {
t = millis() - t;
Serial.println("time taken:" +String(t));
sendRequest(String(t));
state = STATE_IDLE;
}
delay(5);
}
}