#include "HX711.h" #include #include // for NTP #include // for NTP #include #include #include "config.h" int16_t compressMeasurement(int32_t value) { return (int16_t)(measurement / DIVIDER) } HX711 scale; WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, "pool.ntp.org"); TrainingSession session; ESP8266WebServer webServer(80); bool makeMeasurement(long & measurementOut) { if (scale.is_ready()) { measurementOut = scale.get_value(MEASUREMENT_AVG_COUNT); return true; } else return false; } void setup() { digitalWrite(LED_PIN, HIGH); // Serial Serial.begin(115200); while(!Serial) {} // wifi WiFi.mode(WIFI_STA); WiFi.hostname(HOSTNAME); WiFi.begin(WIFI_SSID, WIFI_PASSWD); Serial.print(F("\n\n")); Serial.println(F("Waiting for WIFI connection...")); while (WiFi.status() != WL_CONNECTED) { delay(1000); } Serial.print(F("Connected to WiFi. IP:")); Serial.println(WiFi.localIP()); timeClient.begin(); timeClient.update(); // initialize cell scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN); scale.tare( TARE_AVG_COUNT ); // NTP session.init( &timeClient ); Serial.print("Initialized NTP client: "); Serial.println(timeClient.getEpochTime()); // webserver webServer.on("/api/session", [] () { session.send(&webServer); }); webServer.on("/api/save", [] () { webServer.send(200, "text/plain", session.saveToFileSystem()); }); webServer.on("/api/tare", [] () { scale.tare( TARE_AVG_COUNT ); webServer.send(200, "text/plain", "OK"); }); webServer.on("/", HTTP_GET, [](){ Serial.println("index.html requested"); File file = SPIFFS.open("/index.html", "r"); size_t sent = webServer.streamFile(file, "text/html"); file.close(); }); webServer.on("/swimtrainer.webmanifest", HTTP_GET, [](){ File file = SPIFFS.open("/swimtrainer.webmanifest", "r"); size_t sent = webServer.streamFile(file, "application/manifest+json"); file.close(); }); webServer.begin(); Serial.println("Webserver started"); // flash file system if(!SPIFFS.begin()){ Serial.println("An Error has occurred while mounting SPIFFS"); } } void loop() { const long cycleStart = millis(); digitalWrite(LED_PIN, HIGH); long measurement = 0; if(makeMeasurement(measurement)) { session.addPoint(measurement); } else { Serial.println("Measurement skipped - cell not ready"); } webServer.handleClient(); const long cycleDuration = millis() - cycleStart; if( cycleDuration <= DELAY) { delay(DELAY - cycleDuration); } else { Serial.print("Skipping measurement, cycle duration was "); Serial.println(cycleDuration); const long skipped = (cycleDuration / DELAY); //for(int i=0; i < skipped; ++i) // session.addPoint(0xFFFFFFFE); delay(DELAY * (skipped + 1) - cycleDuration); } }