Thursday, April 4, 2019

Cara Menggunakan Sensor Temperature DS18B20 Dengan Arduino


Program:
/*
  Arduino DS18B20
  By ALC
*/

#include <OneWire.h>
#include <DallasTemperature.h>

int greenLedPin = 5;           // Pin Green LED is connected to
int yellowLedPin = 3;          // Pin Yellow LED is connected to
int redLedPin = 4;             // Pin Red LED is connected to

int temp_sensor = A2;       // Pin DS18B20 Sensor is connected to

float temperature = 0;      //Variable to store the temperature in
int lowerLimit = 15;      //define the lower threshold for the temperature
int upperLimit = 35;      //define the upper threshold for the temperature

OneWire oneWirePin(temp_sensor);

DallasTemperature sensors(&oneWirePin);

void setup(void) {
  Serial.begin(9600);
  pinMode(temp_sensor, INPUT_PULLUP);

  //Setup the LEDS to act as outputs
  pinMode(redLedPin, OUTPUT);
  pinMode(greenLedPin, OUTPUT);
  pinMode(yellowLedPin, OUTPUT);

  sensors.begin();
}

void loop() {
  Serial.print("Requesting Temperatures from sensors: ");
  sensors.requestTemperatures();
  Serial.println("DONE");

  temperature = sensors.getTempCByIndex(0);

  digitalWrite(redLedPin, LOW);
  digitalWrite(greenLedPin, LOW);
  digitalWrite(yellowLedPin, LOW);

  Serial.print("Temperature is ");
  Serial.print(temperature);

  //Setup the LEDS to act as outputs
  if (temperature <= lowerLimit) {
    Serial.println(", Yellow LED is Activated");
    digitalWrite(yellowLedPin, HIGH);
  }
  else if (temperature > lowerLimit && temperature < upperLimit) {
    Serial.println(", Green LED is Activated");
    digitalWrite(greenLedPin, HIGH);
  }
  else if (temperature >= upperLimit) {
    Serial.println(", Red LED is Activated");
    digitalWrite(redLedPin, HIGH);
  }
  delay(500);
}