Conflict of TFT display and SD card SPI communication

This code sensor data display and store to SD card. below code is working. but there is problem. after uncomment the if condition inside the go_to_menu_mode() function. It shows SD card attached but Error opening file in Serial monitor. Is it possible? What is the reason for that?

#include <SD.h>
#include <SPI.h>
#include <TFT_eSPI.h>
#include <HardwareSerial.h>
#include "logo.h"

#define RE 2
#define DE 2
#define RO 13  // Modbus -> RX on GPIO13
#define DI 15  // Modbus -> TX on GPIO15
#define EN 25
#define PWR_EN 12
#define CS_SD 5            // Chip select pin for SD card
#define CS_TFT 4           // Chip select pin for display
#define BTN_1 32           // S2
#define BACK_BTN 33        // S3
#define DWN_BTN 35         // S4
#define OK_BTN 34          // S5
#define WIFI_BTN 39        // S6
#define PWR_AND_UP_BTN 36  // S7

#define powerOnTimeOut 1000
#define powerOffTimeOut 2000

bool btnPressed = 0;
unsigned long currentMillis = 0;
int btnDebounceDelay = 200;

#define TFT_GRAY 0x5AEB  // Define background colour

TFT_eSPI tft = TFT_eSPI();

HardwareSerial modSerial(2);  // Use UART2 which allows you to set custom pins to serial

// Define mod addresses
const byte nitro[] = { 0x01, 0x03, 0x00, 0x1e, 0x00, 0x01, 0xe4, 0x0c };
const byte phos[] = { 0x01, 0x03, 0x00, 0x1f, 0x00, 0x01, 0xb5, 0xcc };
const byte pota[] = { 0x01, 0x03, 0x00, 0x20, 0x00, 0x01, 0x85, 0xc0 };
const byte soil_ph[] = { 0x01, 0x03, 0x00, 0x06, 0x00, 0x01, 0x64, 0x0b };
const byte soil_moist[] = { 0x01, 0x03, 0x00, 0x12, 0x00, 0x01, 0x24, 0x0f };
const byte elec_conduct[] = { 0x01, 0x03, 0x00, 0x15, 0x00, 0x01, 0x95, 0xce };
const byte soil_temp[] = { 0x01, 0x03, 0x00, 0x13, 0x00, 0x01, 0x75, 0xcf };

byte values[11];

void setup() {
  pinMode(RE, OUTPUT);
  pinMode(DE, OUTPUT);
  pinMode(EN, OUTPUT);
  pinMode(PWR_AND_UP_BTN, INPUT);
  pinMode(BTN_1, INPUT);
  pinMode(BACK_BTN, INPUT);
  pinMode(DWN_BTN, INPUT);
  pinMode(OK_BTN, INPUT);
  pinMode(WIFI_BTN, INPUT);
  pinMode(PWR_EN, OUTPUT);
  pinMode(CS_TFT, OUTPUT);
  pinMode(CS_SD, OUTPUT);

  digitalWrite(EN, HIGH);
  digitalWrite(CS_TFT, HIGH);
  digitalWrite(CS_SD, HIGH);

  delay(powerOnTimeOut);
  digitalWrite(PWR_EN, HIGH);
  while (digitalRead(PWR_AND_UP_BTN))
    ;

  Serial.begin(115200);
  modSerial.begin(9600, SERIAL_8N1, RO, DI);

  SPI.begin();

  // Initialize TFT
  digitalWrite(CS_TFT, LOW);
  delay(100);
  tft.init();
  tft.setRotation(3);

  tft.fillScreen(TFT_WHITE);
  tft.setSwapBytes(true);
  tft.pushImage(60, 0, 200, 200, logo);
  delay(200);

  tft.setCursor(50, 220, 4);
  tft.setTextColor(TFT_YELLOW);
  tft.setFreeFont(&FreeSansBold12pt7b);
  auto_typing_text("ELZIAN AGRO EYE");
  tft.setFreeFont(NULL);
  delay(1000);
  digitalWrite(CS_TFT, HIGH);
  delay(100);

  // Initialize SD caed
  digitalWrite(CS_SD, LOW);
  delay(100);
  while (!SD.begin(CS_SD)) {
    Serial.println("SD card mount failed, retrying...");
    delay(1000);
  }
  digitalWrite(CS_SD, HIGH);
  delay(100);
}

void loop() {
  go_to_menu_modes();
}

// Handle menu
void go_to_menu_modes() {
  String menuOptions[] = { "Measuring", "Records", "Upload to Internet", "Wifi Settings" };  // Can add more options
  int currentMode = 0;
  int maxModes = sizeof(menuOptions) / sizeof(menuOptions[0]);

  while (true) {
    digitalWrite(CS_TFT, LOW);
    delay(100);

    clear_screen();
    print_header();

    tft.setCursor(130, 40, 4);
    tft.setTextColor(TFT_GREEN);
    tft.setFreeFont(&FreeSansBold12pt7b);
    tft.println("Menu");
    tft.setFreeFont(NULL);

    tft.setTextColor(TFT_BLUE);
    tft.setTextFont(4);

    // for (int i = 0; i < maxModes; i++) {
    //   if (i == currentMode) {
    //     tft.setTextColor(TFT_YELLOW);  // Highlight current mode
    //   } else {
    //     tft.setTextColor(TFT_BLUE);
    //   }
    //   tft.println("   " + String(i + 1) + ". " + menuOptions[i]);
    // }

    digitalWrite(CS_TFT, HIGH);
    delay(100);

    digitalWrite(CS_SD, LOW);
    delay(100);

    uint8_t cardType = SD.cardType();
    if (cardType == CARD_NONE) {
      Serial.println("No SD card attached");
    } else {
      Serial.println("SD card attached");
      if (SD.exists("/data.txt")) {
        Serial.println("File exists");
      } else {
        Serial.println("File does not exist, creating file...");
      }
      File file = SD.open("/data.txt", FILE_WRITE);
      if (file) {
        file.println("kavinda");
        file.close();
        Serial.println("data written to file");
      } else {
        Serial.println("Error opening file for writing");
      }
    }

    digitalWrite(CS_SD, HIGH);
    delay(100);

    delay(2000);
  }
}

Is the SD card full? Faulty? Have you checked it in PC/laptop?

Is this the full code? This seems like a problem where you are writing outside the bounds of an array somewhere else in the code, since there is no obvious problem with the if statement that is commented out.

The respective libraries take care of the CS_SD and CS_TFT lines. Only need to be set HIGH in setup.

Try the filename without the leading slash.

Yes, There is no any data in SD card.

What type SD card is it? How big? Format?

It is not full code. I will send it by another sample code. In here also same issue. after uncomment the if condition, It show "Error opening file".

#include <SD.h>
#include <SPI.h>
#include <TFT_eSPI.h>

#define CS_SD 5
#define CS_TFT 4

TFT_eSPI tft = TFT_eSPI();

void setup() {
  pinMode(CS_TFT, OUTPUT);
  pinMode(CS_SD, OUTPUT);

  digitalWrite(CS_TFT, HIGH);
  digitalWrite(CS_SD, HIGH);

  Serial.begin(115200);

  SPI.begin();

  // Initialize TFT
  digitalWrite(CS_TFT, LOW);
  delay(50);
  tft.init();
  tft.setRotation(3);
  digitalWrite(CS_TFT, HIGH);
  delay(50);

  // Initialize SD card
  digitalWrite(CS_SD, LOW);
  delay(50);
  while (!SD.begin(CS_SD)) {
    Serial.println("SD card mount failed, retrying...");
    delay(1000);  // Wait for 1 second before retrying
  }
  digitalWrite(CS_SD, HIGH);
  delay(50);
}

void loop() {
  digitalWrite(CS_TFT, LOW);
  delay(50);
  tft.fillScreen(TFT_GREEN);
  delay(1000);

  // if (true) {
  //   tft.setCursor(130, 40, 4);
  //   tft.setTextColor(TFT_GREEN);
  //   tft.println("Menu");
  // }

  tft.fillScreen(TFT_BLUE);
  digitalWrite(CS_TFT, HIGH);
  delay(50);

  digitalWrite(CS_SD, LOW);
  delay(50);

  uint8_t cardType = SD.cardType();
  if (cardType == CARD_NONE) {
    Serial.println("No SD card attached");
  } else {
    Serial.println("SD card attached");
    File file = SD.open("/data.txt", FILE_APPEND);
    if (file) {
      file.print("kavinda");
      file.print(", ");
      file.println("shammi");
      file.close();
      Serial.println("data written to file");
    } else {
      Serial.println("Error opening file for writing");
    }
  }

  digitalWrite(CS_SD, HIGH);
  delay(50);

  delay(2000);
}

It is empty card

OK, empty.
Size? 32 GB or smaller?
Format? FAT16 or FAT32?

This code working properly. But there is a problem. After uncomment the if condition in line 46, the serial monitor show "Error opening file". What is this happen.

#include <SD.h>
#include <SPI.h>
#include <TFT_eSPI.h>

#define CS_SD 5
#define CS_TFT 4

TFT_eSPI tft = TFT_eSPI();

void setup() {
  pinMode(CS_TFT, OUTPUT);
  pinMode(CS_SD, OUTPUT);

  digitalWrite(CS_TFT, HIGH);
  digitalWrite(CS_SD, HIGH);

  Serial.begin(115200);

  SPI.begin();

  // Initialize TFT
  digitalWrite(CS_TFT, LOW);
  delay(50);
  tft.init();
  tft.setRotation(3);
  digitalWrite(CS_TFT, HIGH);
  delay(50);

  // Initialize SD card
  digitalWrite(CS_SD, LOW);
  delay(50);
  while (!SD.begin(CS_SD)) {
    Serial.println("SD card mount failed, retrying...");
    delay(1000);  // Wait for 1 second before retrying
  }
  digitalWrite(CS_SD, HIGH);
  delay(50);
}

void loop() {
  digitalWrite(CS_TFT, LOW);
  delay(50);
  tft.fillScreen(TFT_GREEN);
  delay(1000);

  // if (true) {
  //   tft.setCursor(130, 40, 4);
  //   tft.setTextColor(TFT_GREEN);
  //   tft.println("Menu");
  // }

  tft.fillScreen(TFT_BLUE);
  digitalWrite(CS_TFT, HIGH);
  delay(50);

  digitalWrite(CS_SD, LOW);
  delay(50);

  uint8_t cardType = SD.cardType();
  if (cardType == CARD_NONE) {
    Serial.println("No SD card attached");
  } else {
    Serial.println("SD card attached");
    File file = SD.open("/data.txt", FILE_APPEND);
    if (file) {
      file.print("kavinda");
      file.print(", ");
      file.println("shammi");
      file.close();
      Serial.println("data written to file");
    } else {
      Serial.println("Error opening file for writing");
    }
  }

  digitalWrite(CS_SD, HIGH);
  delay(50);

  delay(2000);
}

the SD library manages the Chip Select (CS) pin for the SD card ➜ try not messing around yourself with the pin state. (you don't even need to set the CS pin as an OUTPUT).

If there is more than one SPI device on the bus. I suggest at least setting all SPI CS pins as INPUT_PULLUP. I use OUTPUT and HIGH.

I have merged your cross-posts @kavindaelzian.

Cross-posting is against the Arduino forum rules. The reason is that duplicate posts can waste the time of the people trying to help. Someone might spend a lot of time investigating and writing a detailed answer on one topic, without knowing that someone else already did the same in the other topic.

Repeated cross-posting can result in a suspension from the forum.

In the future, please only create one topic for each distinct subject matter. This is basic forum etiquette, as explained in the "How to get the best out of this forum" guide. It contains a lot of other useful information. Please read it.

Thanks in advance for your cooperation.

Can you identify if there is a particular line within the if statement that is causing the problem?

In the User_Setup.h file of the TFT_eSPI library, is the line #define USE_HSPI_PORT commented out? There seem to be a lot of issues about SD card usage involving that on the TFT_eSPI github page.