working-with-code-experiments

Components Required

Wiring Diagram

Connect the components as follows:

No Ads Available.

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

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

  1. Connect your Arduino to your computer and upload the code.
  2. Open the Serial Monitor in the Arduino IDE to view the current temperature.
  3. As the temperature exceeds the threshold (e.g., 30°C), the relay will turn on, powering the connected appliance.
  4. When the temperature drops below the threshold, the relay will turn off.

Applications

This system can be applied in several real-world scenarios:

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.

Contact Us

If you have any questions or inquiries, feel free to reach out to us at Microautomation.no@icloud.com .

Follow our Socials for the newest updates!