#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into pin 5 on the Arduino
#define ONE_WIRE_BUS 5
// Pin Definitions for LEDs
const int redLEDPin = 2;
const int greenLEDPin = 3;
const int blueLEDPin = 4;
// Setup a oneWire instance to communicate with any OneWire devices (DS18B20)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);
// Variables for storing temperatures
float predetectTemp = 0;
float detectTemp = 0;
float currentTemp = 0;
void setup() {
// Start up the library for the DS18B20 sensor
sensors.begin();
// Set LED pins as outputs
pinMode(redLEDPin, OUTPUT);
pinMode(greenLEDPin, OUTPUT);
pinMode(blueLEDPin, OUTPUT);
// Start Serial communication for debugging
Serial.begin(9600);
// Get the initial temperature reading
predetectTemp = getTemperature();
Serial.print("Initial Temperature: ");
Serial.println(predetectTemp);
}
void loop() {
// Get the current temperature
detectTemp = getTemperature();
// Calculate the difference between the current and initial temperature
currentTemp = (detectTemp);
Serial.print("Current Temperature: ");
Serial.println(currentTemp);
// Light up the appropriate LED based on the temperature difference
if (currentTemp > 25) {
lightLED(redLEDPin);
Serial.print("Aaah, panas!! ");
} else if (currentTemp <= 25 && currentTemp >= 0) {
lightLED(greenLEDPin);
Serial.print("Normal, yeay! ");
} else if (currentTemp < 0) {
lightLED(blueLEDPin);
Serial.print("Brrr, dingin... ");
}
// Small delay between readings
delay(500);
}
// Function to get temperature from DS18B20 sensor
float getTemperature() {
// Request temperature reading from the sensor
sensors.requestTemperatures();
// Get the temperature in Celsius
return sensors.getTempCByIndex(0);
}
// Function to light one LED and turn off others
void lightLED(int ledPin) {
// Turn off all LEDs
digitalWrite(redLEDPin, LOW);
digitalWrite(greenLEDPin, LOW);
digitalWrite(blueLEDPin, LOW);
// Turn on the selected LED
digitalWrite(ledPin, HIGH);
}