In this article my aim is to shows how to connect a DS18B20 Temperature sensor to the CYD and get the Temperature from it. The DS18B20 is a programmable resolution 1-wire digital thermometer with an temperature range of -55°C to +125°C with ±0.5°C accuracy.

The DS18B20 comes in two styles: Three pin TO-92 package and a waterproof package – where the sensor is house inside a metal housing, you also can get the sensor on a development board

In this article we will be using the waterproof version, the wiring is : Red (VCC), Yellow (DATA), Black (GND) and will be connecting data to GPIO 27 on the CYD. GPIO 27 is available on the CN1 connector, Pin 3 (where ping 4 is next to the SD Card reader)

Connections

  • CN01 DS18B20
  • Pin 1: GND ——–> GND (BLACK)
  • Pin 2: IO22 — N/C
  • Pin 3: IO27 ——–> DATA (YELLOW)
  • Pin 4: 3.3V ——–> VDD (RED)

Pin4 next to the SD Card Reader:

You will also need to add a 4.7K pull up resistor between the data pin and VDD. Note: If you use the development board type, the pull up resistor is already fitted.

Program

Now lets look a a simple code to read the sensor every second

#include <Arduino.h>

#include <OneWire.h>              // Used for DS18B20
#include <DallasTemperature.h>    // Used for DS18B20

// DS18B20 Temperature Sensor GPIO Pin 
#define DS18B20PIN 27 

// Setup DS18B20 Temperature Sensor
OneWire oneWire(DS18B20PIN);            
DallasTemperature sensors(&oneWire); 

void setup() {
  Serial.begin(115200);       // Start the Serial Monitor
  Serial.println("Simple Code to read DS18B20 Temperature Sensor");
}

void loop() {
  sensors.requestTemperatures(); 
  float tempC = sensors.getTempCByIndex(0);
  // Display Temperature as it has changed
  Serial.printf("Temperature: %.1fC\n", tempC);
  delay(1000);
}

Include the required Libraries:

#include <OneWire.h>

#include <DallasTemperature.h>

#define DS18B20PIN 27 // Defines the GPIO pin (27)

Add the following lines to set to set up the sensor:

OneWire oneWire(DS18B20PIN);

DallasTemperature sensors(&oneWire);

To read the sensor

sensors.requestTemperatures();

tempC = sensors.getTempCByIndex(0);

Note you can use getTempFByIndex if you want the temperature in F. Change the ‘0’ to n if you have move than one sensor connected. If the Temperature returns -127 unless it very cold, -127 indicated that the sensor is connect connected correctly

Demo code can be download here

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *