I am going to show you how to make a small RaspberryPI server to monitor a temperature using a sensor. I will be using a RaspberryPI, DS18B20 Waterproof Digital temperature sensor. I'll start with how to set up the hardware first and jump to the server side code later. 

Here is what we need for this project: 

  • Hardware: RaspberryPI, breadboard, jumper cables and a resistor, and DS18B20 Waterproof Digital temperature sensor
  • Software: I'll be using Python to write the server side code and Javascript, I'll also be using Firebase to store the data I collected. 

Hardware Setup 

The DS18B20 Waterproof Digital temperature sensor has three wires: Yellow - data(GPIO), Red - power(3v) and Blue - ground. Now use the breadboard to make a simple circuit. User the 4.7k resistor that between the power supply and the data. Using the jumper cables provide power to the sensor from the PI using the first pin. Then use any ground pin on the PI and connect to the board. 

Now let's test the sensor 

Before you run the command to test the sensor, edit the /boot/config.txt file. Here I am using nano to edit the file

AخA
 
1
sudo nano /boot/config.txt

Then, add the following line:

1
 
1
dtoverlay=w1-gpio

Here, we are enabling the wire interface with the raspi-config tool.  If you open the manual: /boot/overlays/README, you can see the full documentation of the "dtoverlay" command.

x
 
1
Name:   w1-gpio
2
Info:   Configures the w1-gpio Onewire interface module.
3
        Use this overlay if you *don't* need a GPIO to drive an external pullup.
4
Load:   dtoverlay=w1-gpio,<param>=<val>
5
Params: gpiopin                 GPIO for I/O (default "4")
6
7
        pullup                  Non-zero, "on", or "y" to enable the parasitic
8
                                power (2-wire, power-on-data) feature
9
10
11
Name:   w1-gpio-pullup
12
Info:   Configures the w1-gpio Onewire interface module.
13
        Use this overlay if you *do* need a GPIO to drive an external pullup.
14
Load:   dtoverlay=w1-gpio-pullup,<param>=<val>
15
Params: gpiopin                 GPIO for I/O (default "4")
16
17
        pullup                  Non-zero, "on", or "y" to enable the parasitic
18
                                power (2-wire, power-on-data) feature
19
20
        extpullup               GPIO for external pullup (default "5")

Now save the file and reboot the PI. 

To test the sensor, we need to communicate with the operating system and load the kernel modules:

2
 
1
sudo modprobe w1-gpio
2
sudo modeprobe w1-therm

Then locate the device by running the following command:

2
 
1
cd /sys/bus/w1/devices
2
ls -la // list all files 

When you list the files, you should see 28-xxxxxxxxxxxx device directory. This is the ROM of DS18B20. If more than one DS18B20 are connected, you will find more directories.  Cd into the directory and, type:

1
 
1
cat w1_slave

The interface is not that great so look for crc=da YES. The YES means it’s working, and the t=n is the celsius*1000. This verifies the sensor is functioning. Now that we're sure the hardware is working, let's collect some data and store it. 

Now let's gather some data. The code is fairly simple. As the operating system to load the kernel modules, locate the device's location, read the file and parse the data and finally do the appropriate calculation to get the temperature data. Here is a code I lifted from the Adafruit website:

x
1
import os
2
import glob 
3
import time
4
5
#load the kenel modules 
6
os.system('modprobe w1-gpio')   
7
os.system('modprobe w1-therm')
8
# locate the devices location 
9
base_dir = '/sys/bus/w1/devices/'
10
device_folder = glob.glob(base_dir + '28*')[0]
11
device_file = device_folder + '/w1_slave'
12
13
# read the row data from file and return 
14
def read_temp_raw():
15
    f = open(device_file, 'r')
16
    lines = f.readlines()
17
    f.close()
18
    return lines
19
20
def read_temp():
21
    lines = read_temp_raw()
22
    while lines[0].strip()[-3:] != 'YES':
23
        time.sleep(0.2)
24
        lines = read_temp_raw()
25
    equals_pos = lines[1].find('t=')
26
    if equals_pos != -1:
27
        temp_string = lines[1][equals_pos+2:]
28
        temp_c = float(temp_string) / 1000.0
29
        temp_f = temp_c * 9.0 / 5.0 + 32.0
30
        return temp_c, temp_f
31
    
32
while True:
33
    print(read_temp())  
34
    time.sleep(1)
35

This code a good starting point and when you execute the Python script, the application should display the temperature in Celsius and Fahrenheit. But Our goal is to persist this data to a Firebase real-time database so we can use the data to build an app. So we have to change a couple of things: 

First, we need to format this data as a JSON format and to send it to Firebase. 

To be able to do this, we need to add time and calendar to the python script and remove the while loop. 

x
1
import time 
2
import calendar
3
import json
4
import urllib2
5
#remove 
6
while True:
7
    print(read_temp())  
8
    time.sleep(1)

Now add the following to the python script:

x
 
1
# this is a simple script with out authentication
2
# you add firebase authentication later
3
url = 'https://yourfirebaseapp.firebaseio.com/database.json'
4
5
#prepare the data to be sent to firebase
6
postdata = {
7
    'datetime': str(calendar.timegm(time.gmtime())),
8
    'sensorId': "1",
9
    'tempRecord': str(read_temp())
10
}
11
12
req = urllib2.Request(url)
13
req.add_header('Content-Type','application/json')
14
data = json.dumps(postdata)
15
16
response = urllib2.urlopen(req,data)

At this point, we are almost done with the server side of the application but there is one more thing we need to do since we remove the loop from the python script we need some kind of mechanism to automate the data record process. Some might think why not add the loop back to the script and run the code. This is not a good idea for many reasons but the main reason is we need to add additional service to run this small script which adds more overhead, and we don't want that but rather we can use Cron Jobs. Cron is used for scheduling tasks that run on the server. It is a daemon process that runs on the system. To do this scheduled task, type in:

1
 
1
crontab -e  

If it's your first time running the application it will prompt you to select an editor, i use nano edit. 

x
 
1
*/10 * * * * /usr/bin/python /home/pi/applicationname.py

This command is telling Cron to get the temperature every 10 minutes but you can change it whatever setting you desire to. Now the schedule is all set and we should be getting new data to our database. On the next article, we will use this data and create our Ionic application.