Touchscreen calibation
I have written a small function to calibtrate the TS with the display. In every examples I have seen, calibration is done at compile time, and require multiple trys and recompile if touch point is not aligned with TFT pixels. I was inspired by my vintage Palm, it has the same feature.
Maybe someone will save time to reuse it.
It is written for TFTLCD library (from Adafruit, June 2014) + TouchScreen (also from Adafruit)
The macros with TS calibration parameters must be changed to variables
/*//Macros replaced by variables
#define TS_MINX 150
#define TS_MINY 120
#define TS_MAXX 920
#define TS_MAXY 940*/
short TS_MINX=150;
short TS_MINY=120;
short TS_MAXX=920;
short TS_MAXY=940;
and the function, that can be called at the end of Setup() function. It works well with tftpaint example
void calibrate_TS(void){
TSPoint p1, p2;
int16_t temp;
int32_t tempL;
tft.fillScreen(BLACK);
tft.fillCircle(10,10,4,WHITE); //show the first point
tft.setCursor(5, 30); tft.setTextColor(WHITE); tft.setTextSize(1);
tft.println("Please touch the dot");
do { p1 = ts.getPoint(); }while((p1.z < MINPRESSURE) || (p1.z > MAXPRESSURE)); // wait touch
pinMode(XM, OUTPUT); pinMode(YP, OUTPUT); //Pins configures again for TFT control
tft.fillScreen(BLACK);
tft.fillCircle(230,310,4,WHITE); //show the 2nd point
tft.setCursor(50, 280);
tft.println("Please touch the other dot");
delay (500); // debunce
do { p2= ts.getPoint(); }while((p2.z < MINPRESSURE )|| (p2.z > MAXPRESSURE));
pinMode(XM, OUTPUT); pinMode(YP, OUTPUT);
tft.fillScreen(BLACK);
delay (300);
temp=p2.x-p1.x; // Calculate the new coefficients, get X difference
tempL=((long)temp*1024)/(tft.width()-20);
TS_MINX=p1.x-( (tempL*10)>>10);// 10 pixels du bord
TS_MAXX=p1.x+( (tempL*tft.width())>>10);// 220 pixels entre points
temp=p2.y-p1.y; // ¨get Y difference
tempL=((long)temp*1024)/(tft.height()-20);
TS_MINY=p1.y-( (tempL*10)>>10);// 10 pixels du bord
TS_MAXY=TS_MINY+( (tempL*tft.height())>>10);
/*
// For debug, show results
tft.setCursor(5, 30);
tft.println("After calibration: ");
tft.print("TS_MINX= ");tft.println(TS_MINX);
tft.print("TS_MAXX= ");tft.println(TS_MAXX);
tft.print("TS_MINY= ");tft.println(TS_MINY);
tft.print("TS_MAXY= ");tft.println(TS_MAXY);
p1.x = map(p1.x, TS_MAXX,TS_MINX, tft.width(), 0);
p1.y = map(p1.y, TS_MAXY,TS_MINY, tft.height(), 0);
p2.x = map(p2.x, TS_MAXX,TS_MINX, tft.width(), 0);
p2.y = map(p2.y, TS_MAXY,TS_MINY, tft.height(), 0);
tft.println("Last touched points: ");
tft.print("Pt 1: ");tft.print(p1.x);tft.print(" : ");tft.println(p1.y);
tft.print("Pt 2: ");tft.print(p2.x);tft.print(" : ");tft.println(p2.y);
// wait 1 more touch to exit finction
do { p2= ts.getPoint(); }while((p2.z < MINPRESSURE )|| (p2.z > MAXPRESSURE));
pinMode(XM, OUTPUT); pinMode(YP, OUTPUT);
*/
}