Termocupla MAX6675 da valor 0 cuando trabaja con ILI9341

Hola y gracias por vuestra atención.

Estoy intentando realizar una lectura por termocupla con circuito MAX6675 y una pantalla ILI9341 (TFT SPI Táctil). Ambos funcionan por SPI y utilizo un ESP32 Dev Board de 30 pines. Por separado funcionan perfectamente, pero a la vez no consigo que MAX6675 de un valor que no sea 0ºC/32ºF . He separado ambos, uno en VSPI y otro en HSPI, y a la inversa, y tampoco responde. He probado librerias TFT_eSPI.h y SPI.h, en el mismo bus SPI o en buses separados, sin éxito. Aquí os dejo el código por si se os ocurre cual puede ser el problema.

#include <TFT_eSPI.h>                // Librería para ILI9341
#include <XPT2046_Touchscreen.h>     // Librería para XPT2046
#include <max6675.h>                 // Librería para MAX6675

// Pines HSPI (TFT + Touch)
#define TFT_CS   15
#define TFT_DC   2
#define TFT_RST  4

#define TOUCH_CS 33
#define TOUCH_IRQ 36 // Opcional, puedes omitirlo si no usas la interrupción

#define HSPI_MOSI 13
#define HSPI_MISO 12
#define HSPI_SCLK 14

// Pines VSPI (MAX6675)
#define MAX6675_CS   5
#define VSPI_MISO    19
#define VSPI_MOSI    23 // No usado en MAX6675 pero requerido por VSPI
#define VSPI_SCK     18

// Inicialización de SPI y periféricos
SPIClass hspi(HSPI);
TFT_eSPI tft = TFT_eSPI();
XPT2046_Touchscreen touch(TOUCH_CS, TOUCH_IRQ);

// Para el MAX6675 usando VSPI
SPIClass vspi(VSPI);
MAX6675 thermocouple(VSPI_SCK, MAX6675_CS, VSPI_MISO); // Adafruit lib: SCK, CS, SO (MISO)

unsigned long lastTempRead = 0;
float lastTemp = 0;

void setup() {
  Serial.begin(115200);

  // Inicializa SPI HSPI (TFT y Touch)
  hspi.begin(HSPI_SCLK, HSPI_MISO, HSPI_MOSI, -1);
  tft.init();
  tft.setRotation(1);
  tft.fillScreen(TFT_BLACK);
  tft.setTextColor(TFT_WHITE, TFT_BLACK);
  touch.begin();
  touch.setRotation(1);

  tft.drawString("TFT, Touch y MAX6675 OK!", 30, 50, 2);

  // Inicializa VSPI para MAX6675
  vspi.begin(VSPI_SCK, VSPI_MISO, VSPI_MOSI, -1);
}

void loop() {
  // Lectura del touch
  if (touch.touched()) {
    TS_Point p = touch.getPoint();
    int x = p.x;
    int y = p.y;
    tft.fillCircle(x, y, 5, TFT_RED);
    Serial.printf("Touch: x=%d, y=%d\n", x, y);
    delay(100);
  }

  // Lectura del MAX6675 cada segundo
  if (millis() - lastTempRead > 1000) {
    lastTemp = thermocouple.readCelsius();
    Serial.printf("Temp: %.2f°C\n", lastTemp);

    // Muestra en la pantalla
    tft.fillRect(30, 80, 150, 30, TFT_WHITE);
    tft.setTextColor(TFT_GREEN, TFT_BLACK);
    tft.drawString("Temp: " + String(lastTemp, 2) + " C", 30, 80, 2);
    lastTempRead = millis();
  }
}

Gracias por vuestra atención y perdonar si no he creado bien el tema, soy nuevo en estas lares.

No entiendo porque usas SPI diferentes.
EL Bus SPI require 4 lineas MOSI MISO SCLK (Clock) y un CS por cada dispositivo. Lo único que debe cambiar es el Chip Select. Que es activo bajo.
Entonces conecta TFT y MAX a los mismos 3 pines y con diferentes CS.
Eso por un lado.
Pruebalos individualmente y luego hablamos.
Esta es la disposición de pines para tu caso.

Veo que los pines estan bien, entonces todo al mismo bus VSPI o HSPI.
CS 5 para el Max6675 como ya tienes y 15 para el TFT como tambien ya tienes.
Solo unifica los MOSI MISO Y SCLK
Luego vemos como se comporta, ya nos comentarás.

Hola, gracias por contestar tan rápido.

Inicialmente lo monté todo en el bus VSPI con SCK D18, MOSI D23,MISO D19, y usando D15 para TFT CS, y D5 para MAX6675. Como vi que CS de VSPI se correspondía con D05 los invertí. La pantalla funcionaba perfectamente, así como el programa, pero la temperatura que leía era 0ºC/32ºF: MAX6675 respondía pero con un valor nulo. Si retiro la pantalla entonces leo perfectamente la termocupla. Es por ello que probé a separar buses. He probado diferentes configuraciones, con uno o dos buses, respetando los terminales que indicas, mismo resultado, en realidad llevo una semana haciendo pruebas y revisando el montaje una y otra vez, todo bien, pero no funciona.

He buscado por youtube proyectos que incluyan ESP32,ILI9341 y MAX6675 a la vez, pero no he encontrado ninguno.

¿ es posible que esté utilizando en arduino IDE un board incorrecto?, uso ESP32 dev board y mi placa es un ESP32 de 30 pines montado en una placa de desarrollo.

En el chip ESP32 que monta, indica ZY ESP32 WIFI+BT MODEL SRRC, y el patillaje corresponde con los pines de un ESP-WROOM32

Hasta ahora no había tenido ningún problema con los montajes, con ese board todos los programas corrían perfectamente.

Un saludo y gracias de nuevo

PD: He compilado con ESP32-WROOM-DA Module y ESP32 Wrover Module, con el mismo resultado, el programa corre perfectamente, pero el valor recibido de temperatura es 0

Prueba poniendo una resistencia pull-up de 4K7 (4700Ω) en la línea SO del 6675 (MISO en el micro) y usa distintos buses para prevenir que la R interfiera con la pantalla.

O sea, una R de 4700Ω entre SO (o MISO) y 3.3V.

La resistencia puede ser incluso de menor valor, hasta 1K (1000Ω) trabaja bien.

Hi,

Haz tratado el ejemplo de la libreria. No necesistas usar el interface spi para leer el sensor.



Gracias por la idea, tauro0221! No se me había ocurrido, el ejemplo me parece que es para arduino, lo he adaptado para ESP32 y no funciona

Hola MaximoEsfuerzo

He probado lo que has comentado y no he notado ningún cambio ni con 1000 ohm ni con 1000+3300ohm. El caso es que la termocupla funciona bien si no hay otro dispositivo funcionando en SPI. No sé si puede ser un problema de frecuencia de trabajo en SPI, me parece que el TFT trabaja a 27000000 y la termocupla necesita tiempo entre lectura y lectura,

Gracias por tus ideas!

No.

Muéstrame tu archivo de configuración User_Setup.h. Para IDE 2.3.6, debe guardarse en la carpeta del boceto.

Hola ua6em

Este es el User_Setup.h despejado de comentarios

#define USER_SETUP_INFO "User_Setup"

// Only define one driver, the other ones must be commented out
#define ILI9341_DRIVER       // Generic driver for common displays


// ##################################################################################
//
// Section 2. Define the pins that are used to interface with the display here
//
// ##################################################################################

#define TFT_SPI_PORT HSPI		// fuerzo el bus HSPI
#define TFT_MISO 12
#define TFT_MOSI 13
#define TFT_SCLK 14
#define TFT_CS   15  // Chip select control pin
#define TFT_DC    2  // Data Command control pin
#define TFT_RST   4  // Reset pin (could connect to RST pin)
//#define TFT_RST  -1  // Set TFT_RST to -1 if display RESET is connected to ESP32 board RST


#define TOUCH_CS 21     // Chip select pin (T_CS) of touch screen

// ##################################################################################
//
// Section 3. Define the fonts that are to be used here
//
// ##################################################################################

#define LOAD_GLCD   // Font 1. Original Adafruit 8 pixel font needs ~1820 bytes in FLASH
#define LOAD_FONT2  // Font 2. Small 16 pixel high font, needs ~3534 bytes in FLASH, 96 characters
#define LOAD_FONT4  // Font 4. Medium 26 pixel high font, needs ~5848 bytes in FLASH, 96 characters
#define LOAD_FONT6  // Font 6. Large 48 pixel font, needs ~2666 bytes in FLASH, only characters 1234567890:-.apm
#define LOAD_FONT7  // Font 7. 7 segment 48 pixel font, needs ~2438 bytes in FLASH, only characters 1234567890:-.
#define LOAD_FONT8  // Font 8. Large 75 pixel font needs ~3256 bytes in FLASH, only characters 1234567890:-.
//#define LOAD_FONT8N // Font 8. Alternative to Font 8 above, slightly narrower, so 3 digits fit a 160 pixel TFT
#define LOAD_GFXFF  // FreeFonts. Include access to the 48 Adafruit_GFX free fonts FF1 to FF48 and custom fonts

// Comment out the #define below to stop the SPIFFS filing system and smooth font code being loaded
// this will save ~20kbytes of FLASH
#define SMOOTH_FONT


// ##################################################################################
//
// Section 4. Other options
//
// ##################################################################################

#define SPI_FREQUENCY  27000000		// (SPI2 maximum is 27MHz) HSPI

// Optional reduced SPI frequency for reading TFT
#define SPI_READ_FREQUENCY  20000000

// The XPT2046 requires a lower SPI clock rate of 2.5MHz so we define that here:
#define SPI_TOUCH_FREQUENCY  2500000

#define USE_HSPI_PORT

esto es cuando uso TFT_eSPI.h, pero con la libreria SPI.h me hace los mismo, funciona TFT pero termocupla da valor 0C/32F

Sí, la configuración es correcta. A mí me funciona así:
Puedes encontrar instrucciones en línea sobre cómo y dónde inicializarlo con este ejemplo.

//uninitalised pointers to SPI objects
SPIClass* vspi1 = NULL;  // SD
SPIClass* vspi2 = NULL;  // AD9833
SPIClass* vspi3 = NULL;  // MCP41010 Potenciometr
SPIClass* vspi4 = NULL;  // MCP41010 Alc
//SPIClass * hspi = NULL;   // TFT

¿Has probado sin usar la touch?

Por cierto, entiendo que no necesitarías la librería XPT2046_Touchscreen porque TFT_eSPI tiene soporte para la touch.

Hola MaximoEsfuerzo

Sin la touch tampoco funcionaba.

Finalmente he conseguido que funcione (usando tft_eSPI.h, y montando tft en HSPI y termocupla en SPI), he hecho variaciones pero me parece que el problema se encuentra en el User_Setup.h . Si bajo la frecuencia a 1MHz la termocupla y el tft funcionan a la vez, pero he de seguir probando con los componentes que le faltan al proyecto. Con frecuencias superiores (5MHz,10MHz,27Mhz,40MHz) da un valor diferente de cero, pero no varía.

Por ahora, aunque funciona la termocupla, varía sus valores alrededor de 2 grados C al tomar medidas consecutivas. Aquí os dejo unas muestras de la temperatura obtenida


28.50
27.25
28.75
28.75
27.25
29.25
29.00
27.25
28.75
28.50
27.00
28.50

Como veis hay un error de hasta 2C, y me parece que no variaba tanto cuando probé el MAX6675 como único dispositivo, tanto con arduino uno como con esp32

Estoy intentando hacer un control auxiliar para un horno de cocina con mandos clásicos, que la convierta en un horno digital. Cuando lo monte todo os comento si finalmente funciona sin problema.

Muchísimas gracias a todos por vuestra atención, me habéis ayudado un montón con vuestras ideas.

Curioso problema, quedará anotado y esta para ser investigado.

El microcircuito MAX31855 dará resultados significativamente mejores

Hola ua6em

Yo creo que es un problema del montaje en SPI con el ILI9341, inicialmente lo monté como único dispositivo para probarlo, mostrando los datos por Serial, y la temperatura la daba sin saltos apenas, como debe de ser. Es buena idea probar otra termocupla, ya que si funciona a la primera podré seguir con el proyecto. Vi un video con esa termocupla, aunque no lo entendí demasiado bien, creo que recomiendan poner un condensador cerámico de bajo valor entre los terminales T+ y T-, también lo probé con mi termocupla y no variaba el resultado.

No entiendo ese código, soy bastante nuevo en esto.

¿Qué te has pasado? Así funciona: el monitor está VSPI

#include <TFT_eSPI.h>                // Librería para ILI9341
#include <XPT2046_Touchscreen.h>     // Librería para XPT2046
#include <max6675.h>                 // Librería para MAX6675

#define TOUCH_CS 33
#define TOUCH_IRQ 36 // Opcional, puedes omitirlo si no usas la interrupción

// Pines VSPI (MAX6675)
int thermoDO = 16;
int thermoCS = 5;
int thermoCLK = 17;
MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);

// Inicialización de SPI y periféricos
TFT_eSPI tft = TFT_eSPI();
XPT2046_Touchscreen touch(TOUCH_CS, TOUCH_IRQ);

unsigned long lastTempRead = 0;
float lastTemp = 0;

void setup() {
  // VDD on MAX6675
  pinMode(21,OUTPUT);
  digitalWrite(21, HIGH);

  Serial.begin(115200);

  tft.init();
  tft.setRotation(1);
  tft.fillScreen(TFT_BLACK);
  tft.setTextColor(TFT_WHITE, TFT_BLACK);
  touch.begin();
  touch.setRotation(1);

  tft.drawString("TFT, Touch y MAX6675 OK!", 30, 50, 2);
}


void loop() {
  // Lectura del touch
  if (touch.touched()) {
    TS_Point p = touch.getPoint();
    int x = p.x;
    int y = p.y;
    tft.fillCircle(x, y, 5, TFT_RED);
    Serial.printf("Touch: x=%d, y=%d\n", x, y);
    delay(100);
  }

  // Lectura del MAX6675 cada segundo
  if (millis() - lastTempRead > 1000) {
    lastTemp = thermocouple.readCelsius();
    Serial.printf("Temp: %.2f°C\n", lastTemp);

    // Muestra en la pantalla
    tft.fillRect(30, 80, 150, 30, TFT_WHITE);
    tft.setTextColor(TFT_GREEN, TFT_BLACK);
    tft.drawString("Temp: " + String(lastTemp, 2) + " C", 30, 80, 2);
    lastTempRead = millis();
  }
}

User_Setup.h

#define USER_SETUP_INFO "User_Setup"

// Only define one driver, the other ones must be commented out
#define ILI9341_DRIVER       // Generic driver for common displays


// ##################################################################################
//
// Section 2. Define the pins that are used to interface with the display here
//
// ##################################################################################

//#define TFT_SPI_PORT HSPI		// fuerzo el bus HSPI
//#define TFT_MISO 12
//#define TFT_MOSI 13
//#define TFT_SCLK 14
//#define TFT_CS   15  // Chip select control pin
//#define TFT_DC    2  // Data Command control pin
//#define TFT_RST   4  // Reset pin (could connect to RST pin)
//#define TFT_RST  -1  // Set TFT_RST to -1 if display RESET is connected to ESP32 board RST

// ESP32 DEV Module
#define TFT_MISO 19
#define TFT_MOSI 23
#define TFT_SCLK 18
#define TFT_CS 15 // Chip select control pin
#define TFT_DC 2 // Data Command control pin
#define TFT_RST 4 // Reset pin (could connect to RST pin)
//#define TFT_RST -1 // Set TFT_RST to -1 if display RESET is connected to ESP32 board RST
#define TFT_BL   22            // LED back-light control pin
#define TFT_BACKLIGHT_ON HIGH  // Level to turn ON back-light (HIGH or LOW)

#define TOUCH_CS 12     // Chip select pin (T_CS) of touch screen

// ##################################################################################
//
// Section 3. Define the fonts that are to be used here
//
// ##################################################################################

#define LOAD_GLCD   // Font 1. Original Adafruit 8 pixel font needs ~1820 bytes in FLASH
#define LOAD_FONT2  // Font 2. Small 16 pixel high font, needs ~3534 bytes in FLASH, 96 characters
#define LOAD_FONT4  // Font 4. Medium 26 pixel high font, needs ~5848 bytes in FLASH, 96 characters
#define LOAD_FONT6  // Font 6. Large 48 pixel font, needs ~2666 bytes in FLASH, only characters 1234567890:-.apm
#define LOAD_FONT7  // Font 7. 7 segment 48 pixel font, needs ~2438 bytes in FLASH, only characters 1234567890:-.
#define LOAD_FONT8  // Font 8. Large 75 pixel font needs ~3256 bytes in FLASH, only characters 1234567890:-.
//#define LOAD_FONT8N // Font 8. Alternative to Font 8 above, slightly narrower, so 3 digits fit a 160 pixel TFT
#define LOAD_GFXFF  // FreeFonts. Include access to the 48 Adafruit_GFX free fonts FF1 to FF48 and custom fonts

// Comment out the #define below to stop the SPIFFS filing system and smooth font code being loaded
// this will save ~20kbytes of FLASH
#define SMOOTH_FONT


// ##################################################################################
//
// Section 4. Other options
//
// ##################################################################################

#define SPI_FREQUENCY  27000000		// (SPI2 maximum is 27MHz) HSPI

// Optional reduced SPI frequency for reading TFT
#define SPI_READ_FREQUENCY  20000000

// The XPT2046 requires a lower SPI clock rate of 2.5MHz so we define that here:
#define SPI_TOUCH_FREQUENCY  2500000

//#define USE_HSPI_PORT

El MAX 6675 usa un protocolo similar a SPI, pero no es SPI. Además, se usa una biblioteca táctil de terceros, que ya está incluida en la biblioteca de pantallas. Puedes ver cómo usarla en los ejemplos de la biblioteca de pantallas.

Aquí está el código que utiliza sólo la biblioteca TFT_eSP!

#include <TFT_eSPI.h>  // Librería para ILI9341
#include <max6675.h>   // Librería para MAX6675

// Pines VSPI (MAX6675)
int thermoDO = 16;
int thermoCS = 5;
int thermoCLK = 17;
MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);

// Inicialización de SPI y periféricos (TFT, TOUCH)
TFT_eSPI tft = TFT_eSPI();

unsigned long lastTempRead = 0;
float lastTemp = 0;

void setup() {
  // VDD on MAX6675
  pinMode(21, OUTPUT);
  digitalWrite(21, HIGH);

  Serial.begin(115200);
  tft.init();
  tft.setRotation(1);
  tft.fillScreen(TFT_BLACK);
  tft.setTextColor(TFT_WHITE, TFT_BLACK);
  tft.drawString("TFT, Touch y MAX6675 OK!", 30, 50, 2);
}


void loop() {
  // Lectura del MAX6675 cada segundo
  if (millis() - lastTempRead > 1000) {
    // TOUCH
    uint16_t x, y;
    tft.getTouchRaw(&x, &y);
    tft.fillCircle(x, y, 5, TFT_RED);
    Serial.printf("Touch: x=%d, y=%d\n", x, y);

    lastTemp = thermocouple.readCelsius();
    Serial.printf("Temp: %.2f°C\n", lastTemp);

    // Muestra en la pantalla
    tft.fillRect(30, 80, 150, 30, TFT_WHITE);
    tft.setTextColor(TFT_GREEN, TFT_BLACK);
    tft.drawString("Temp: " + String(lastTemp, 2) + " C", 30, 80, 2);
    lastTempRead = millis();
  }
}

User_Setup.h

#define USER_SETUP_INFO "User_Setup"

// Only define one driver, the other ones must be commented out
#define ILI9341_DRIVER       // Generic driver for common displays


// ##################################################################################
//
// Section 2. Define the pins that are used to interface with the display here
//
// ##################################################################################

//#define TFT_SPI_PORT HSPI		// fuerzo el bus HSPI
//#define TFT_MISO 12
//#define TFT_MOSI 13
//#define TFT_SCLK 14
//#define TFT_CS   15  // Chip select control pin
//#define TFT_DC    2  // Data Command control pin
//#define TFT_RST   4  // Reset pin (could connect to RST pin)
//#define TFT_RST  -1  // Set TFT_RST to -1 if display RESET is connected to ESP32 board RST

// ESP32 DEV Module
#define TFT_MISO 19
#define TFT_MOSI 23
#define TFT_SCLK 18
#define TFT_CS 15 // Chip select control pin
#define TFT_DC 2 // Data Command control pin
#define TFT_RST 4 // Reset pin (could connect to RST pin)
//#define TFT_RST -1 // Set TFT_RST to -1 if display RESET is connected to ESP32 board RST
#define TFT_BL   22            // LED back-light control pin
#define TFT_BACKLIGHT_ON HIGH  // Level to turn ON back-light (HIGH or LOW)

#define TOUCH_CS 33     // Chip select pin (T_CS) of touch screen
#define TOUCH_IRQ 36

// ##################################################################################
//
// Section 3. Define the fonts that are to be used here
//
// ##################################################################################

#define LOAD_GLCD   // Font 1. Original Adafruit 8 pixel font needs ~1820 bytes in FLASH
#define LOAD_FONT2  // Font 2. Small 16 pixel high font, needs ~3534 bytes in FLASH, 96 characters
#define LOAD_FONT4  // Font 4. Medium 26 pixel high font, needs ~5848 bytes in FLASH, 96 characters
#define LOAD_FONT6  // Font 6. Large 48 pixel font, needs ~2666 bytes in FLASH, only characters 1234567890:-.apm
#define LOAD_FONT7  // Font 7. 7 segment 48 pixel font, needs ~2438 bytes in FLASH, only characters 1234567890:-.
#define LOAD_FONT8  // Font 8. Large 75 pixel font needs ~3256 bytes in FLASH, only characters 1234567890:-.
//#define LOAD_FONT8N // Font 8. Alternative to Font 8 above, slightly narrower, so 3 digits fit a 160 pixel TFT
#define LOAD_GFXFF  // FreeFonts. Include access to the 48 Adafruit_GFX free fonts FF1 to FF48 and custom fonts

// Comment out the #define below to stop the SPIFFS filing system and smooth font code being loaded
// this will save ~20kbytes of FLASH
#define SMOOTH_FONT


// ##################################################################################
//
// Section 4. Other options
//
// ##################################################################################

#define SPI_FREQUENCY  40000000		// (SPI2 maximum is 27MHz) HSPI

// Optional reduced SPI frequency for reading TFT
#define SPI_READ_FREQUENCY  20000000

// The XPT2046 requires a lower SPI clock rate of 2.5MHz so we define that here:
#define SPI_TOUCH_FREQUENCY  2500000

//#define USE_HSPI_PORT

Entonces, ¿cuál fue el resultado con el termopar?