esp8266-weather-station-color/TouchControllerWS.cpp
2023-10-21 14:51:48 -04:00

119 lines
2.8 KiB
C++

#include "TouchControllerWS.h"
#if defined(TOUCH_CS)
TouchControllerWS::TouchControllerWS(Adafruit_STMPE610 *touchScreen) {
#else
TouchControllerWS::TouchControllerWS(Adafruit_TSC2007 *touchScreen) {
#endif
this->touchScreen = touchScreen;
}
bool TouchControllerWS::loadCalibration() {
// always use this to "mount" the filesystem
bool result = SPIFFS.begin();
Serial.print("SPIFFS opened: ");
Serial.println(result);
if (!result) return false;
// this opens the file "calibration.txt" in read-mode
File f = SPIFFS.open("/calibration.txt", "r");
if (!f) {
return false;
}
//Lets read line by line from the file
String dxStr = f.readStringUntil('\n');
String dyStr = f.readStringUntil('\n');
String axStr = f.readStringUntil('\n');
String ayStr = f.readStringUntil('\n');
dx = dxStr.toFloat();
dy = dyStr.toFloat();
ax = axStr.toInt();
ay = ayStr.toInt();
f.close();
return true;
}
bool TouchControllerWS::saveCalibration() {
bool result = SPIFFS.begin();
if (!result) return false;
// open the file in write mode
File f = SPIFFS.open("/calibration.txt", "w");
if (!f) {
Serial.println("file creation failed");
return false;
}
// now write two lines in key/value style with end-of-line characters
f.println(dx);
f.println(dy);
f.println(ax);
f.println(ay);
f.close();
return true;
}
void TouchControllerWS::startCalibration(CalibrationCallback *calibrationCallback) {
state = 0;
this->calibrationCallback = calibrationCallback;
}
void TouchControllerWS::continueCalibration() {
TS_Point p = touchScreen->getPoint();
if (state == 0) {
(*calibrationCallback)(10, 10);
if (isTouched()) {
p1 = p;
state++;
lastStateChange = millis();
}
} else if (state == 1) {
(*calibrationCallback)(230, 310);
if (isTouched() && (millis() - lastStateChange > 1000)) {
p2 = p;
state++;
lastStateChange = millis();
dx = 240.0 / abs(p1.y - p2.y);
dy = 320.0 / abs(p1.x - p2.x);
ax = p1.y < p2.y ? p1.y : p2.y;
ay = p1.x < p2.x ? p1.x : p2.x;
}
}
}
bool TouchControllerWS::isCalibrationFinished() {
return state == 2;
}
bool TouchControllerWS::isTouched() {
#if defined(TOUCH_CS)
return touchScreen->touched();
#else
TS_Point p = touchScreen->getPoint();
return (p.z > 50);
#endif
}
bool TouchControllerWS::isTouched(int16_t debounceMillis) {
if (isTouched() && millis() - lastTouched > debounceMillis) {
lastTouched = millis();
return true;
}
return false;
}
TS_Point TouchControllerWS::getPoint() {
TS_Point p = touchScreen->getPoint();
int x = (p.y - ax) * dx;
int y = 320 - (p.x - ay) * dy;
p.x = x;
p.y = y;
return p;
}