I am making a system that uses the Arduino mega and a 2.4 inch tft touchscreen shield to control lights and a fan in my room. I am trying to make buttons for it that control certain pins. The only way I could get this to happen was by using a slightly modified example sketch. The issue is that I can only get 2 buttons to because that is how many the example sketch had. I am very bad at coding and hoping that someone else with more experience than me could help me add the other two buttons.
#if 1
#include <Adafruit_GFX.h>
#include <MCUFRIEND_kbv.h>
MCUFRIEND_kbv tft;
#include <TouchScreen.h>
#define MINPRESSURE 200
#define MAXPRESSURE 1000
// ALL Touch panels and wiring is DIFFERENT
// copy-paste results from TouchScreen_Calibr_native.ino
const int XP=8,XM=A2,YP=A3,YM=9; //240x320 ID=0x9341
const int TS_LEFT=137,TS_RT=894,TS_TOP=93,TS_BOT=893;
TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);
Adafruit_GFX_Button on_btn, off_btn;
int pixel_x, pixel_y; //Touch_getXY() updates global vars
bool Touch_getXY(void)
{
TSPoint p = ts.getPoint();
pinMode(YP, OUTPUT); //restore shared pins
pinMode(XM, OUTPUT);
digitalWrite(YP, HIGH); //because TFT control pins
digitalWrite(XM, HIGH);
bool pressed = (p.z > MINPRESSURE && p.z < MAXPRESSURE);
if (pressed) {
pixel_x = map(p.x, TS_LEFT, TS_RT, 0, tft.width()); //.kbv makes sense to me
pixel_y = map(p.y, TS_TOP, TS_BOT, 0, tft.height());
}
return pressed;
}
#define BLACK 0x0000
#define BLUE 0x001F
#define RED 0xF800
#define GREEN 0x07E0
#define CYAN 0x07FF
#define MAGENTA 0xF81F
#define YELLOW 0xFFE0
#define WHITE 0xFFFF
void setup(void)
{
Serial.begin(9600);
uint16_t ID = tft.readID();
Serial.print("TFT ID = 0x");
Serial.println(ID, HEX);
Serial.println("Calibrate for your Touch Panel");
if (ID == 0xD3D3) ID = 0x9486; // write-only shield
tft.begin(ID);
tft.setRotation(0); //PORTRAIT
tft.fillScreen(BLACK);
on_btn.initButton(&tft, 60, 290, 100, 40, WHITE, CYAN, BLACK, "ON", 2);
off_btn.initButton(&tft, 180, 290, 100, 40, WHITE, CYAN, BLACK, "OFF", 2);
on_btn.drawButton(false);
off_btn.drawButton(false);
pinMode(22, OUTPUT);
}
/* two buttons are quite simple
*/
void loop(void){
{
tft.setTextColor(WHITE);
tft.fillRect(0, 230, 240, 3, BLUE);
tft.fillRect(0, 317, 240, 3, BLUE);
tft.fillRect(0, 0, 240, 3, BLUE);
tft.fillRect(237, 0, 3, 320, BLUE);
tft.fillRect(0, 0, 3, 320, BLUE);
tft.setCursor(65, 240);
tft.setTextSize(2);
tft.print("Fan Control");
}
{
bool down = Touch_getXY();
on_btn.press(down && on_btn.contains(pixel_x, pixel_y));
off_btn.press(down && off_btn.contains(pixel_x, pixel_y));
if (on_btn.justReleased())
on_btn.drawButton();
if (off_btn.justReleased())
off_btn.drawButton();
if (on_btn.justPressed()) {
on_btn.drawButton(true);
digitalWrite(22, HIGH);
}
if (off_btn.justPressed()) {
off_btn.drawButton(true);
digitalWrite(22, LOW);
}
}
}
#endif