Código de Pesquisa

Lesson 47: Using K-Type MAX6675 as thermostat with relay | Arduino Step By Step Course

Lesson 47: Using K-Type MAX6675 as thermostat with relay | Arduino Step By Step Course

This project guides you through building a temperature control system using an Arduino, a MAX6675 K-type thermocouple, and a relay. This system can maintain a desired temperature range, making it suitable for various applications. You can use this to build:

  • A temperature-controlled incubator for delicate experiments or seedlings.
  • An automated brewing system for maintaining consistent wort temperatures.
  • A climate-controlled enclosure for reptiles or other temperature-sensitive animals.
  • A simple heating or cooling system for a small space.

The system uses the MAX6675 to read temperatures from a K-type thermocouple, providing accurate temperature readings over a wide range (depending on the thermocouple type, up to 1000°C or more). The Arduino processes these readings and controls a relay to switch a heating or cooling element on or off, maintaining the temperature within a user-defined range. (in video at 00:32)

Hardware/Components

To build this project, you will need the following components:

  • Arduino board (Uno, Nano, etc.)
  • MAX6675 thermocouple amplifier
  • K-type thermocouple
  • Relay module
  • AC bulb (or other load, such as a fan or heater)
  • Jumper wires
  • Breadboard (optional, but recommended)

Wiring Guide

The wiring is explained in detail in the video. (in video at 03:28) Refer to the video for a visual guide. The key connections include connecting the MAX6675 to the Arduino (pins 2-6), the relay module to the Arduino (pin 8 and power), and the relay module to the AC load. A critical aspect is correctly identifying the live and neutral wires of your AC load before connecting them to the relay. Incorrect wiring can lead to dangerous situations.

Code Explanation

The Arduino code (shown in snippets below) utilizes the MAX6675 library to read temperature values from the thermocouple. The user-configurable parts of the code are:

  • relayPin: The Arduino pin connected to the relay module (default: 8). (in video at 07:35)
  • relayON and relayOFF: These constants define the logic levels to turn the relay on and off, respectively. These are usually LOW and HIGH, but might need to be adjusted depending on your relay module. (in video at 07:35)
  • TEMPERATURE_UNIT: Sets the unit for temperature readings (1 for Celsius, 2 for Fahrenheit, 3 for Kelvin). (in video at 08:21)
  • START_TEMPERATURE and STOP_TEMPERATURE: These variables define the temperature range for the control system. The system will turn on the relay when the temperature falls below START_TEMPERATURE and turn it off when the temperature reaches STOP_TEMPERATURE (or vice-versa, depending on whether you're controlling a heater or cooler). (in video at 08:31)
  • CONTROL_TYPE: A variable that determines whether the system acts as a heater (1) or cooler (2). (in video at 08:36)

The code includes functions like readTemperature(), printTemperature(), loadControl(), and relayControl() to handle temperature reading, display, and relay operation. These functions are clearly defined and explained in the video. (in video at 09:37, 10:00, 10:43, 11:30)


const int relayPin =8;
const int relayON = LOW;// do not change
const int relayOFF = HIGH; //do not change 
int relayState = relayOFF;//initial state of relay

const int TEMPERATURE_UNIT =1;//1=Celsius, 2=Fahrenheit, 3=Kelvin
const float START_TEMPERATURE = 80.0;//unit above
const float STOP_TEMPERATURE = 100.0;//unit above
const int CONTROL_TYPE = 1;// 1= heater, 2=cooler

Live Project/Demonstration

The video demonstrates the functioning of the temperature control system for both heating and cooling scenarios. (in video at 13:15 and 15:28) The demonstration clearly shows how the system maintains the temperature within the set range by turning the relay on and off as needed.

Chapters

  • [00:00] Introduction
  • [00:55] Heater/Cooler Control Explanation
  • [03:28] Wiring Diagram
  • [06:26] Code Explanation
  • [13:15] Heater Control Demonstration
  • [15:28] Cooler Control Demonstration
  • [17:29] Conclusion
25-Arduino code for a MAX6675 K-type thermocouple with relay (no display)
Idioma: C++
/*
 * Este é o código Arduino para o termopar K-Type MAX6675 com relé e display. O pino de saída 10 está conectado ao relé. Quando a temperatura atinge o valor desejado, o pino 10 liga o relé.
 * 
 * Este código foi explicado em nosso vídeo em https://youtu.be/cD5oOu4N_AE
 * 
 * Escrito por Ahmad Nejrabi para Robojax Video. Data: 9 de dezembro de 2017, em Ajax, Ontário, Canadá. Permissão concedida para compartilhar este código, desde que esta nota seja mantida com o código. Isenção de responsabilidade: este código é "COMO ESTÁ" e para fins educacionais apenas. 
 * 
 * /
 * 
 *  // Este exemplo é de domínio público. Aproveite! // www.ladyada.net/learn/sensors/thermocouple
 */
#include "max6675.h"


int thermoDO = 4;
int thermoCS = 5;
int thermoCLK = 6;


MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);
int vccPin = 3;
int gndPin = 2;

void setup() {
  Serial.begin(9600);
 // Use pinos do Arduino
  pinMode(vccPin, OUTPUT); digitalWrite(vccPin, HIGH);
  pinMode(gndPin, OUTPUT); digitalWrite(gndPin, LOW);
    pinMode(10, OUTPUT); // defina o pino 10 como saída

  Serial.println("Robojax: MAX6675 test");
 // aguardar o chip MAX estabilizar
  delay(500);
}

void loop() {
 // teste básico de leitura, apenas imprima a temperatura atual


   Serial.print("C = ");
   Serial.println(thermocouple.readCelsius());
   Serial.print("F = ");
   Serial.println(thermocouple.readFahrenheit());

 // Se a temperatura ultrapassar 80,0 °C, ative o relé.
   if(thermocouple.readCelsius() > 80.00){
    digitalWrite(10, LOW); // defina o pino 10 como baixo
   }else{
    digitalWrite(10, HIGH); // defina o pino 10 como ALTO
   }


   delay(1000);
}
757-Arduino code to measure a MAX6675 K-type thermocouple
Idioma: C++
++
/*
 * Biblioteca de: // www.ladyada.net/learn/sensors/thermocouple
 * 
 * Este é o código Arduino para medir o sensor de termopar K-Type MAX6675 e controlar um relé como aquecedor ou refrigerador.
 * 
 * Assista ao vídeo de instrução para este código: https://youtu.be/dVh77wT-4Ao
 * 
 * Escrito por Ahmad Shamshiri em 20 de maio de 2020 em Ajax, Ontário, Canadá www.robojax.com
 * 
 * Obtenha este código e outros códigos Arduino em Robojax.com. Aprenda Arduino passo a passo em um curso estruturado com todo o material, diagramas de ligação e bibliotecas tudo em um só lugar. Compre meu curso em Udemy.com http://robojax.com/L/?id=62
 * 
 * Se você achou este tutorial útil, por favor me apoie para que eu possa continuar criando conteúdo como este. Você pode me apoiar no Patreon http://robojax.com/L/?id=63
 * 
 * ou fazer uma doação usando PayPal http://robojax.com/L/?id=64
 * Vídeos relacionados:
 * Introdução ao MAX6675 K-Type: https://youtu.be/VGqONmUinqA
 * Usando o termopar K-Type MAX6675 com display LED: https://youtu.be/cD5oOu4N_AE
 * Usando o termopar K-Type MAX6675 com LCD1602-I2C: https://youtu.be/BlhpktgPdKs
 * Usando 2 ou mais termopares K-Type MAX6675: https://youtu.be/c90NszbNG8c
 * Usando o termopar K-Type MAX6675 como controlador de aquecedor ou refrigerador: [este vídeo]
 *  * Este código é "COMO ESTÁ" sem garantia ou responsabilidade. Livre para ser usado desde que você mantenha esta nota intacta.* 
 * Este código foi baixado do Robojax.com
 *  Este programa é um software livre: você pode redistribuí-lo e/ou modificá-lo sob os termos da Licença Pública Geral GNU conforme publicada pela Fundação de Software Livre, na versão 3 da Licença ou (a seu critério) qualquer versão posterior.
 * 
 *  Este programa é distribuído na esperança de que seja útil, mas SEM QUAISQUER GARANTIAS; sem mesmo a garantia implícita de COMERCIALIZAÇÃO ou ADEQUAÇÃO A UM FIM ESPECÍFICO. Veja a Licença Pública Geral GNU para mais detalhes.
 * 
 *  Você deve ter recebido uma cópia da Licença Pública Geral GNU juntamente com este programa. Se não, veja <https://www.gnu.org/licenses/>.
 */


#include "max6675.h"
 // Aquecedor/Resfriador Robojax.com com Termopar MAX6675
int GNDpin = 2;
int VCCpin =3;
int thermoCLK = 4;
int thermoCS = 5;
int thermoDO = 6;
MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);


const int relayPin =8;
const int relayON = LOW; // não mudar
const int relayOFF = HIGH; // não mudar
int relayState = relayOFF; // estado inicial do relé

const int TEMPERATURE_UNIT =1; // 1=Grau Celsius, 2=Grau Fahrenheit, 3=Kelvin
const float START_TEMPERATURE = 80.0; // unidade acima
const float STOP_TEMPERATURE = 100.0; // unidade acima
const int CONTROL_TYPE = 1; // 1= aquecedor, 2= resfriador
float temperature;

void setup() {
 // Aquecedor/Resfriador Robojax.com com Termopar MAX6675
  Serial.begin(9600);
  Serial.println("MAX6675 test with relay");
 // use pinos do Arduino
  pinMode(relayPin, OUTPUT); // pino para relé
  digitalWrite(relayPin, relayState);

  pinMode(VCCpin, OUTPUT);
  digitalWrite(VCCpin, HIGH);

  pinMode(GNDpin, OUTPUT);
  digitalWrite(GNDpin, LOW);

 // aguarde o chip MAX estabilizar
  delay(500);
 // Aquecedor/Resfriador Robojax.com com Termopar MAX6675
}

void loop() {
 // Aquecedor/Resfriador Robojax.com com Termopar MAX6675
   readTemperature();
   printTemperature();
   loadControl();
   if(temperature >=89.5)
   {
 // /
   }
   delay(1000);
 // Aquecedor/Resfriador Robojax.com com Termopar MAX6675
} // laço



/*
 * loadControl()
 * @brief controla a carga baseada
 * @param state pode ser : relayON ou relayOFF
 * @return não retorna nada
 * Escrito por Ahmad Shamshiri para robojax.com
 * em 20 de maio de 2020 às 15:23 em Ajax, Ontário, Canadá
 */
void loadControl()
{
 // Aquecedor/Resfriador Robojax.com com Termopar MAX6675
 // Serial.print("Iniciar: ");
 // Serial.print(TEMPERATURA_INICIAL);
 // Serial.print(" Parar: ");
 // Serial.println(TEMPERATURA_DE_PARADA);
  if(CONTROL_TYPE ==1)
  {
    if(START_TEMPERATURE >= temperature && STOP_TEMPERATURE >=temperature)
    {
      relayControl(relayON);
    }
    if(STOP_TEMPERATURE <=temperature)
    {
      relayControl(relayOFF);
    }
  }else{
    if(START_TEMPERATURE >= temperature && STOP_TEMPERATURE >=temperature)
    {
      relayControl(relayOFF);
    }
    if(STOP_TEMPERATURE <=temperature)
    {
      relayControl(relayON);
    }
  }

 // Aquecedor/Resfriador Robojax.com com Termopar MAX6675
} // loadControl()


/*
 * relayControl(int estado))
 * @brief ativa ou desativa o relé
 * @param estado é "relayON" ou "relayOFF" definido no início do código
 * @return não retorna nada
 * Escrito por Ahmad Shamshiri para robojax.com
 * em 20 de maio de 2020 às 15:23 em Ajax, Ontário, Canadá
 */
void relayControl(int state)
{
 // Aquecedor/Resfriador Robojax.com com Termopar MAX6675
  if(state ==relayON)
  {
    digitalWrite(relayPin, relayON);
    Serial.println("Relay ON");
  }else{
   digitalWrite(relayPin, relayOFF);
    Serial.println("Relay OFF");
  }
 // Aquecedor/Resfriador Robojax.com com Termopar MAX6675

} // relayControl()


/*
 * readTemperature()
 * @brief lê a temperatura com base na TEMPERATURE_UNIT
 * @param temperatura média
 * @return retorna um dos valores acima
 * Escrito por Ahmad Shamshiri para robojax.com
 * em 20 de maio de 2020 às 15:23 em Ajax, Ontário, Canadá
 */
void readTemperature()
{
 // Aquecedor/Resfriador Robojax.com com Termopar MAX6675

  if(TEMPERATURE_UNIT ==2)
   {
   temperature = thermocouple.readFahrenheit(); // converter para Fahrenheit
   }else if(TEMPERATURE_UNIT ==3)
   {
    temperature = thermocouple.readCelsius() + 273.15; // converter para Kelvin
   }else{
    temperature = thermocouple.readCelsius(); // retornar Celsius
   }
 // Aquecedor/Resfriador Robojax.com com Termopar MAX6675
} // lerTemperatura()

/*
 * printTemperature()
 * @breve imprime a temperatura no monitor serial
 * @param tipo caractere
 * @param "tipo" é um caractere
 *  C = Celsius
 *  K = Kelvin
 *  F = Fahrenheit
 * @return nenhum
 * Escrito por Ahmad Shamshiri para robojax.com
 * em 08 de maio de 2020 às 02:45 em Ajax, Ontário, Canadá
 */
void printTemperature()
{
 // Aquecedor/Resfriador Robojax.com com Termopar MAX6675
   Serial.print(temperature);
    printDegree();
  if(TEMPERATURE_UNIT ==2)
   {
     Serial.print("F");
    }else if(TEMPERATURE_UNIT ==3)
   {
     Serial.print("K");
   }else{
     Serial.print("C");
   }
  Serial.println();
 // Aquecedor/Resfriador Robojax.com com Termopar MAX6675
} // printTemperature()

/*
 * @brief imprime o símbolo de grau no monitor serial
 * @param nenhum
 * @return não retorna nada
 * Escrito por Ahmad Shamshiri em 13 de julho de 2019
 * para o Tutorial Robojax Robojax.com
 */
void printDegree()
{
    Serial.print("\\xC2");
    Serial.print("\\xB0");
}

Coisas que você pode precisar

Recursos e referências

Arquivos📁

Nenhum arquivo disponível.