I have problems with the values of some of the bits I receive via SPI. I configure a Max31855 with a k-type thermocouple. When reading the internal temperature it is fine, the disconnection errors are read perfectly, but the temperature value in the thermocouple shows erroneous values, sometimes even negative.
This is the code in general terms, I am using an M524 board
void setup() {
pinMode( (MAXCS, OUTPUT);
digitalWrite(MAXCS, HIGH); // Iniciar con el chip deshabilitado
SPI.beginTransaction(SPISettings(5000000, MSBFIRST,
SPI_MODE0));
SPI.begin();
}
void loop() {
readThermocouple();
delay(1000);
}
double readThermocouple() {
uint32_t v = 0;
// Activar el MAX31855
digitalWrite(MAXCS, LOW);
delayMicroseconds(100); // Pequeño retardo para asegurar la transmisión
// Leer 32 bits de datos del MAX31855
for (int i = 0; i < 4; i++) {
v <<= 8;
v |= SPI.transfer(0x00);
}
// Desactivar el MAX31855
digitalWrite(MAXCS, HIGH);
// Verificar si hay fallos
if (v & 0x00010000) { // Verificar el bit D16 (falla)
Serial.println("Error en la termocupla");
if (v & 0x00000001) Serial.println("Termocupla abierta (OC Fault)");
if (v & 0x00000002) Serial.println("Cortocircuito a GND (SCG Fault)");
if (v & 0x00000004) Serial.println("Cortocircuito a VCC (SCV Fault)");
return NAN; // Retornar un valor no numérico si hay un error
}
// Extraer la temperatura de la termocupla
int32_t tempData = (v >> 18) & 0x3FFF; // Los bits D31:18 contienen la temperatura de la termocupla
if (v & 0x80000000) { // Comprobar si es un valor negativo
tempData |= 0xFFFFC000; // Extensión de signo para manejar números negativos
}
int32_t thermocoupleTemperature = tempData * 0.25; // Multiplicar por 0.25 para obtener la temperatura en °C
// Extraer la temperatura de la unión fría (bits D15:4)
int32_t internalTempData = (v >> 4) & 0x0FFF; // Los bits D15:4 contienen la temperatura interna
if (v & 0x00008000) { // Comprobar si es un valor negativo
internalTempData |= 0xFFFFF000; // Extensión de signo para manejar números negativos
}
double internalTemperature = internalTempData * 0.0625; // Multiplicar por 0.0625 para obtener la temperatura en °C
// Imprimir ambas temperaturas
Serial.print("Temperatura del termopar: ");
Serial.println(thermocoupleTemperature);
Serial.print("Temperatura interna (UnionFria): ");
Serial.println(internalTemperature);
return thermocoupleTemperature;
}