Components Required
- 1 x Arduino (any model)
- 1 x DS18B20 Temperature Sensor
- 1 x 10kΩ Resistor
- 1 x Relay Module
- Jumper wires
- Breadboard
- Fan or Heater (connected to the relay)
Wiring Diagram
Connect the components as follows:
- DS18B20 Temperature Sensor:
- VCC to 5V on Arduino
- GND to GND on Arduino
- Data pin to digital pin 2 on Arduino (with a 10kΩ resistor between data pin and VCC)
- Relay Module:
- IN pin to digital pin 7 on Arduino
- VCC to 5V on Arduino
- GND to GND on Arduino
- Connect the appliance (fan or heater) to the relay as per the module's specifications (refer to relay documentation for high-voltage connections).
Code Explanation
The system reads the temperature using the DS18B20 sensor and compares it to a predefined threshold. If the temperature exceeds the threshold, the relay will activate to turn on the appliance.
Key Functions
digitalWrite(pin, state)
: Turns the relay on or off by sending HIGH or LOW to the relay control pin.sensors.getTempCByIndex(0)
: Reads the temperature value from the DS18B20 sensor.if()
: A conditional statement to check if the temperature exceeds the threshold.
Arduino Code
Here’s the Arduino code for temperature-based control using a relay:
#include
#include
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
const int relayPin = 7;
const float thresholdTemp = 30.0;
void setup() {
Serial.begin(9600);
sensors.begin();
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, LOW);
}
void loop() {
sensors.requestTemperatures();
float currentTemp = sensors.getTempCByIndex(0);
Serial.print("Current Temperature: ");
Serial.print(currentTemp);
Serial.println(" °C");
if (currentTemp >= thresholdTemp) {
digitalWrite(relayPin, HIGH);
Serial.println("Appliance ON");
} else {
digitalWrite(relayPin, LOW);
Serial.println("Appliance OFF");
}
delay(1000);
}
Upload and Test
- Connect your Arduino to your computer and upload the code.
- Open the Serial Monitor in the Arduino IDE to view the current temperature.
- As the temperature exceeds the threshold (e.g., 30°C), the relay will turn on, powering the connected appliance.
- When the temperature drops below the threshold, the relay will turn off.
Applications
This system can be applied in several real-world scenarios:
- Smart home automation, such as climate control.
- Overheating prevention for devices or systems.
- Temperature-sensitive industrial processes.
Conclusion
This project demonstrates how to use a relay to control an electrical appliance based on temperature readings from a DS18B20 sensor. You can adapt this system for various automation and control applications to save energy or enhance convenience.