#include <OneWire.h>
#include <DallasTemperature.h>
#include <Servo.h>
OneWire oneWire(2); // Data pin for temperature sensor
DallasTemperature sensors(&oneWire);
Servo myServo; // Create servo object
float desiredTemperature = 3.0; // Default desired temperature in Celsius
void setup() {
Serial.begin(9600);
sensors.begin();
myServo.attach(9); // Servo connected to pin 9
myServo.write(90); // Initialize servo to middle position (neutral setting)
Serial.println("Enter desired temperature (in Celsius):");
}
void loop() {
if (Serial.available() > 0) {
desiredTemperature = Serial.parseFloat(); // Read the user input from the serial monitor
Serial.print("New desired temperature set to: ");
Serial.println(desiredTemperature);
// Clear the serial buffer
while(Serial.available() > 0) {
Serial.read();
}
}
sensors.requestTemperatures(); // Send the command to get temperatures
float tempC = sensors.getTempCByIndex(0); // Read temperature in Celsius
Serial.print("Current Temperature: ");
Serial.println(tempC);
// Adjust the thermostat based on the current temperature vs desired temperature
if (tempC < desiredTemperature) { // If temp is less than the desired temp
myServo.write(180); // Simulate turning the thermostat up (heating)
Serial.println("Heating activated");
} else if (tempC > desiredTemperature) { // If temp is more than the desired temp
myServo.write(0); // Simulate turning the thermostat down (cooling)
Serial.println("Cooling activated");
} else {
myServo.write(90); // Neutral position
Serial.println("Thermostat on hold");
}
delay(10000); // Wait 10 seconds between readings
}
Loading
ds18b20
ds18b20