Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
BeagleBone Home Automation Blueprints
BeagleBone Home Automation Blueprints

BeagleBone Home Automation Blueprints: Automate and control your home using the power of the BeagleBone Black with practical home automation projects

Arrow left icon
Profile Icon Rodolfo Giometti
Arrow right icon
€36.99
Paperback Feb 2016 378 pages 1st Edition
eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Rodolfo Giometti
Arrow right icon
€36.99
Paperback Feb 2016 378 pages 1st Edition
eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

BeagleBone Home Automation Blueprints

Chapter 1. Dangerous Gas Sensors

In this chapter, we will learn how to use the BeagleBone Black to monitor some dangerous gases in a room, such as CO, methane, LPG, and so on, and then enabling an acoustic and visive alarm in case of danger. Also, by using a GSM module, the user will be able to send an SMS message to a predefined phone number to alert, for instance, a relative.

Also, the user will be able to control, log, and display the measured concentrations from the system console/terminal by using a command-line interface (this to keep the code simple).

We'll see how to build the circuitry to manage the sensors and how to get the gas concentration from them. Then, we'll take a look at how to manage a GSM module in order to send SMS messages.

The basic of functioning

In this project, our BeagleBone Black will periodically read the environmental data from the sensors, comparing them with user selectable ranges, and then generate an alarm in case one (or more) data read is out of that range.

The sensors will be connected to the BeagleBone Black ADCs with a dedicated circuitry, while the alarms will be enabled with dedicated GPIO lines. Then a GSM module will be connected to our BeagleBone Black's serial port in order to send other alarm messages via SMS.

Setting up the hardware

As just stated, all devices are connected with the BeagleBone Black, which is the real core of the system, as shown in the following screenshot:

Setting up the hardware

The data flow is from the sensors to the alarm actuators (LED, buzzer, and GSM module) and the user will be able to send commands to the system, or check the system status and the collected data, by using the system console.

Connecting the gas sensors

The gas sensors are used to monitor the environment and we can choose different kinds of such devices. I decided to use the ones shown in the following screenshot due to the fact they act as a variable resistor according to the gas concentration, so they can be easily read with a normal ADC:

Connecting the gas sensors

In the prototype presented here, the gas sensors are actually four, but the ones named MQ-2 (smoke detector), MQ-4 (methane detector), and MQ-7 (LPG detector) look very similar to each other (except the label on each sensor), so I reported only one of them in the preceding screenshot, while the carbon monoxide detector is the red device labeled with MQ-7.

Looking carefully at the datasheet of the gas sensors, we can see exactly how these sensors' class varies their internal resistance according to the gas concentration (in reality, it depends on environment humidity and temperature too; but for an indoor functioning, we can consider these values as constants). So, if we put it in series with a resistor and apply a constant voltage). We can get an output voltage that is proportional to the actual gas concentration.

The following diagram shows a possible schematics where the gas sensor is connected to 5V power supply and the RL resistor is formed by two resistors (R1 & R2) due to the fact we cannot put more than 1.8V at a BeagleBone Black's ADC pin. So, by choosing these two resistors in such a way that R1 ≥ 2*R2, we can be sure we have no more than 5.0V/3 ≈ 1.67V at the ADC input pin on every possible functioning condition, even if the sensor's internal resistance is shorted. However, to be completely sure we can add a Zener diode (Z) with a reverse threshold on 1.8V (but I didn't use it on my prototype).

The following diagram shows the circuitry I used to connect each sensor:

Connecting the gas sensors

Tip

Note that the GAS sensors have six pins labeled in pairs as A, B, and H; while the A and B pair pins are shortened, the H labeled pairs must be connected at one end to the input voltage (5V in our case) and the other end to the GND (see the datasheet for further information).

Another important issue regarding these sensors is the calibration we should perform before using them. This last adjustment is very important; as reported in the MQ-2 datasheet, we read the following recommendation:

We recommend that you calibrate the detector for 1000 ppm liquefied petroleum gas (LPG), or 1000ppm iso-butane (i-C4H10) concentration in air and use value of load resistance that (RL) about 20K (5K to 47K).

This step can be done by replacing resistors R1 or R2 with a varistor and then fine tuning its resistance. However, I decided to use normal resistors (R1 = 15KΩ, R2 = 6.8KΩ in such a way that RL = R1 + R2 ≈ 20KΩ, as suggested by the datasheet) and then implemented a little translation in software (see the following section), that is, we can translate raw data from the ADCs into a ppm (part-per-million) value in such a way the user can work with physic data.

This translation can be done using a gain and an offset value in the following formula for each sensor:

  • ppm = raw * gain + offset

During the calibration procedure, we just need to use two known points (ppm1 and ppm2), read the corresponding raw data (raw1 and raw2), and then apply the following formulas:

  • gain = (ppm1 – ppm2) / (raw1 – raw2)
  • offset = ppm1 – raw1 * gain

Of course, we need four gain/offset couples, one per sensor (the calibration procedure is quite long!)

Once we have fixed the input circuits, we simply have to connect each Vout to the BeagleBone Black's ADC input pins. Our board has 8 ADCs inputs, so we can use the following connections:

Pin

Gas sensor

P9.39 - AIN0

Vout @MQ-2

P9.37 - AIN2

Vout @MQ-4

P9.35 - AIN6

Vout @MQ-5

P9.33 - AIN4

Vout @MQ-7

To enable them, we use the following command:

root@beaglebone:~# echo cape-bone-iio > /sys/devices/bone_capemgr.9/slots

If everything works well, we should get the following kernel messages:

part_number 'cape-bone-iio', version 'N/A'
slot #7: generic override
bone: Using override eeprom data at slot 7
slot #7: 'Override Board Name,00A0,Override Manuf,cape-bone-iio'
slot #7: Requesting part number/version based 'cape-bone-iio-00A0.dtbo
slot #7: Requesting firmware 'cape-bone-iio-00A0.dtbo' for board-name 'Override Board Name', version '00A0'
slot #7: dtbo 'cape-bone-iio-00A0.dtbo' loaded; converting to live tree
slot #7: #1 overlays
helper.12: ready
slot #7: Applied #1 overlays.

Then, the files AIN0, AIN1, …, AIN7 should become available as follows:

root@beaglebone:~# find /sys -name '*AIN*'
/sys/devices/ocp.3/helper.12/AIN0
/sys/devices/ocp.3/helper.12/AIN1
/sys/devices/ocp.3/helper.12/AIN2
/sys/devices/ocp.3/helper.12/AIN3
/sys/devices/ocp.3/helper.12/AIN4
/sys/devices/ocp.3/helper.12/AIN5
/sys/devices/ocp.3/helper.12/AIN6
/sys/devices/ocp.3/helper.12/AIN7

Note

These settings can be done using the bin/load_firmware.sh script in the book's example code repository, as follows:

root@beaglebone:~# ./load_firmware.sh adc

Then, we can read the input data by using the cat command:

root@beaglebone:~# cat /sys/devices/ocp.3/helper.12/AIN0
1716

Tip

Note that the ADC can also be read by using other files still into the sysfs filesystem. The following command, for instance, reads from AIN0 input pin:

root@beaglebone:~# cat /sys/bus/iio/devices/iio:device0/in_voltage0_raw

Connecting the alarm actuators

Now, we have to connect the alarm actuators in such a way the user can have a visual and acoustic feedback of any possible dangerous gas concentration. Also, we have to connect the GSM module to a serial port to communicate with it.

LED and buzzer

The LED and buzzer connections are very simple. The LEDs can be directly connected (with a resistor) with the BeagleBone Black's GPIO pins without problems, while the buzzer needs a little more work due to the fact that it needs a higher current than the LED to work. However, we can resolve the problem by using a transistor as shown in the following diagram to manage the buzzer with a higher current.

Tip

Note that the buzzer can't be a simple piezo without an internal oscillator, otherwise an external oscillator circuit or a PWM signal must be used!

LED and buzzer

In my circuitry, I used an R (470Ω) resistor for the LED (L), an R (2KΩ), Rd (4.7KΩ) resistors for the buzzer, and a BC546 transistor (T). Note that, regarding the LEDs, an R = 100Ω resistor can result in a higher brightness, so you may change it according to the LED color to have different results.

Note also that the resistor Rd in the buzzer circuitry is needed to pull-down the GPIO during the boot. In fact, during this stage it is set as input, and even in such configuration the current that flows out from the pin can turn on the buzzer!

The BeagleBone Black has a lot of GPIOs lines, so we can use the following connections:

Pin

Actuator

P8.9 - GPIO69

R @LED

P8.10 - GPIO68

R @Buzzer

Now, to test the connections, we can set up the GPIOs by exporting them and then setting these lines as outputs with the following commands:

root@beaglebone:~# echo 68 > /sys/class/gpio/export
root@beaglebone:~# echo out > /sys/class/gpio/gpio68/direction
root@beaglebone:~# echo 0 > /sys/class/gpio/gpio68/value     
root@beaglebone:~# echo 69 > /sys/class/gpio/export
root@beaglebone:~# echo out > /sys/class/gpio/gpio69/direction
root@beaglebone:~# echo 0 > /sys/class/gpio/gpio69/value

Note

Note that it will be a good idea to use blinking LEDs to do this job. However, for this first chapter I'm going to use normal GPIO lines, leaving this topic for the following chapters.

Now, to turn on and off both the LED and the buzzer, we simply write 1 or 0 into the proper files, as follows:

root@beaglebone:~# echo 1 > /sys/class/gpio/gpio68/value     
root@beaglebone:~# echo 0 > /sys/class/gpio/gpio68/value
root@beaglebone:~# echo 1 > /sys/class/gpio/gpio69/value
root@beaglebone:~# echo 0 > /sys/class/gpio/gpio69/value

Note

These settings can be done by using the bin/gpio_set.sh script in the book's example code repository, as follows:

root@beaglebone:~# ./gpio_set 68 out
root@beaglebone:~# ./gpio_set 69 out

GSM module

As stated in the introduction of this chapter, we wish to add a GSM module to be able to alert the user remotely too. In order to do this, we can connect this device with a normal serial port with TTL level signals. In this case, we have only to choose one of the serial ports available on our BeagleBone Black.

The following screenshot shows the GSM module I decided to use:

GSM module

Note

The device can be purchased at the following link (or by surfing the Internet):

http://www.cosino.io/product/serial-gsmgprs-module

The user manual con be retrieved at http://www.mikroe.com/downloads/get/1921/gsm_click_manual_v101c.pdf.

The BeagleBone Black has four available serial ports. By deciding to use the device /dev/ttyO1, we can use the following connections:

Pin

GSM module

P9.24 - TX-O1

RX

P9.26 - RX-O1

TX

P9.1 - GND

GND

P9.3 - 3.3V

3.3V

P9.5 - 3.3V

5V

To enable the serial port, we have to use the following command:

root@beaglebone:~# echo BB-UART1 > /sys/devices/bone_capemgr.9/slots

If everything works well, we should get the following kernel messages:

part_number 'BB-UART1', version 'N/A'
slot #8: generic override
bone: Using override eeprom data at slot 8
slot #8: 'Override Board Name,00A0,Override Manuf,BB-UART1'
slot #8: Requesting part number/version based 'BB-UART1-00A0.dtbo
slot #8: Requesting firmware 'BB-UART1-00A0.dtbo' for board-name 'Override Board Name', version '00A0'
slot #8: dtbo 'BB-UART1-00A0.dtbo' loaded; converting to live tree
slot #8: #2 overlays
48022000.serial: ttyO1 at MMIO 0x48022000 (irq = 73) is a OMAP UART1
slot #8: Applied #2 overlays.

The device file /dev/ttyO1 should now become available.

Note

These settings can be done by using the bin/load_firmware.sh script in the book's example code repository, as follows:

root@beaglebone:~# ./load_firmware.sh ttyO1

To verify that the new device is ready, we can use the ls command as follows:

root@beaglebone:~# ls -l /dev/ttyO1
crw-rw---T 1 root dialout 248, 1 Apr 23 22:25 /dev/ttyO1

Note

The reader can take a look at the book BeagleBone Essentials, Packt Publishing, which was written by the author of this book, in order to have more information regarding how to activate and use the GPIO lines and the serial ports available on the system.

Now, we can test whether we actually talk with the modem by using the screen command as follows:

root@beaglebone:~# screen /dev/ttyO1 115200

Note

The screen command can be installed by using the aptitude command as follows:

root@beaglebone:~# aptitude install screen

After pressing the ENTER key, you should get a blank terminal where, if you enter the ATZ string, you should get the string OK as answer, as shown in the following code:

ATZ
OK

It's the GSM module that answers that it's okay and fully functional. To quit from the screen command, you have to enter the CTRL + A + \ keys sequence and then answer yes by pressing the y key when the program asks you to Really quit and kill all your windows [y/n].

The final picture

Well, now we have to put it all together! The following image shows the prototype I made to implement this project and to test the software:

The final picture

Note that we need an external power supplier due to the fact that the external circuitry (and especially the GSM module) needs the 5V power supply.

Setting up the software

Now, it's time to think about the software needed to implement the desired functioning, that is, checking the gas concentrations, logging them, and eventually activating the alarms. We need the following:

  1. A periodic procedure (read_sensors.php) that periodically scans all the sensors and then logs their data into a database.
  2. A periodic procedure (monitor.php) that reads the sensors' data, checks them against preset thresholds, and then sets some internal status.
  3. A periodic procedure (write_actuators.php) that enables the alarms according to the previously saved status.

The following diagram shows the situation:

Setting up the software

The core of the system is the database, where we store both the data we wish to log and the system's status. In this manner, all periodic functions can be realized as separate tasks that talk to each other by using the database itself. Also, we can control all the tasks from the system console by just altering the config table at runtime.

I used MySQL to implement the database system, and the preceding configuration can be created by using the my_init.sh script, where we define the proper tables.

Tip

The MySQL daemon can be installed by using the aptitude command as follows:

root@beaglebone:~# aptitude install mysql-client mysql-server

Here is a snippet of the script:

CREATE TABLE status (
   n VARCHAR(64) NOT NULL,
   v VARCHAR(64) NOT NULL,
   PRIMARY KEY (n)
) ENGINE=MEMORY;

# Setup default values
INSERT INTO status (n, v) VALUES('alarm', 'off');

#
# Create the system configuration table
#

CREATE TABLE config (
   n VARCHAR(64) NOT NULL,
   v VARCHAR(64) NOT NULL,
   PRIMARY KEY (n)
);

# Setup default values
INSERT INTO config (n, v) VALUES('sms_delay_s', '300');

INSERT INTO config (n, v) VALUES('mq2_gain', '1');
INSERT INTO config (n, v) VALUES('mq4_gain', '1');
INSERT INTO config (n, v) VALUES('mq5_gain', '1');
INSERT INTO config (n, v) VALUES('mq7_gain', '1');
INSERT INTO config (n, v) VALUES('mq2_off', '0');
INSERT INTO config (n, v) VALUES('mq4_off', '0');
INSERT INTO config (n, v) VALUES('mq5_off', '0');
INSERT INTO config (n, v) VALUES('mq7_off', '0');

INSERT INTO config (n, v) VALUES('mq2_th_ppm', '2000');
INSERT INTO config (n, v) VALUES('mq4_th_ppm', '2000');
INSERT INTO config (n, v) VALUES('mq5_th_ppm', '2000');
INSERT INTO config (n, v) VALUES('mq7_th_ppm', '2000');

#
# Create one table per sensor data
#

CREATE TABLE MQ2_log (
   t DATETIME NOT NULL,
   d float,
   PRIMARY KEY (t)
);

CREATE TABLE MQ4_log (
   t DATETIME NOT NULL,
   d float,
   PRIMARY KEY (t)
);

CREATE TABLE MQ5_log (
   t DATETIME NOT NULL,
   d float,
   PRIMARY KEY (t)
);

CREATE TABLE MQ7_log (
   t DATETIME NOT NULL,
   d float,
   PRIMARY KEY (t)
);

Note

The my_init.sh script is stored in the chapter_01/my_init.sh file in the book's example code repository.

The reader should notice that we define a status table with the MEMORY storage engine since we don't need to preserve it at reboot but need a good performance in accessing it, while the config table and the per-sensor logging tables (MQ2_log, MQ4_log, MQ5_log, and MQ7_log) are defined as normal tables since we need to save these data even during a complete restart. Note that we defined one table per variable in order to easily get access to the logged data; however, nothing changes, even if we decide to keep the logged data into a global logging table.

Note also that during the database initialization, we can define some default settings by simply recording these values by using an INSERT command. For the status table, we just need the alarm variable to be set to off, while into the config table, we can set up the minimum delay in seconds (sms_delay_s) to wait before resending a new SMS alarm, the gain/offset translation couple variables (mq2_gain/mq2_off and friends), and the per-sensor threshold variables (mq2_th_ppm and friends) to be used to activate the alarms.

Managing the ADCs

Now, to get data from the ADC and save them into the database, we have to write a periodic task. This is quite easy and the following code snippet shows a PHP implementation of the main function of the file read_sensors.php, which does this:

function daemon_body()
{
   global $loop_time;
   global $sensors;

   # The main loop
   dbg("start main loop (loop_time=${loop_time}s)");
   while (sleep($loop_time) == 0) {
      dbg("loop start");

      # Read sensors
      foreach ($sensors as $s) {
         $name = $s['name'];
         $file = $s['file'];
         $var = $s['var'];
         $log = $s['log'];

         # Get the converting values
         $gain = db_get_config($var . "_gain");
         $off = db_get_config($var . "_off");

         dbg("gain[$var]=$gain off[$var]=$off");

         # Read the ADC file
         $val = file_get_data($file);
         if ($val === false) {
            err("unable to read sensor $name");
            continue;
         }

      # Do the translation
      $ppm = $val * $gain + $off;

      dbg("file=$file val=$val ppm=$ppm");

      # Store the result into the status table
      $ret = db_set_status($var, $ppm);
      if (!$ret) {
         err("unable to save $name status db_err=%s",
             mysql_error());
         continue;
      }

      # Store the result into the proper log table
      $ret = db_log_var($log, $ppm);
      if (!$ret)
         err("unable to save $name log db_err=%s",
             mysql_error());
      }

      dbg("loop end");
   }
}

Note

The complete script is stored in the chapter_01/read_sensors.php file in the book's example code repository.

The function is quite simple. It starts the main loop to periodically read the ADC data, get the gain and offset conversion values for the current variable needed to convert it into the corresponding ppm number, then alters the current status variables, and adds a new value into the logging table of the read sensor.

If we execute the script enabling all debugging command-line options, we get:

root@beaglebone:~# ./read_sensors.php -d -f -l -T 5
read_sensors.php[5388]: signals traps installed
read_sensors.php[5388]: start main loop (loop_time=5s)
read_sensors.php[5388]: loop start
read_sensors.php[5388]: gain[mq2]=0.125 off[mq2]=0
read_sensors.php[5388]: file=/sys/devices/ocp.3/helper.12/AIN0 val=810 ppm=101.25
read_sensors.php[5388]: gain[mq4]=1 off[mq4]=0
read_sensors.php[5388]: file=/sys/devices/ocp.3/helper.12/AIN2 val=1477 ppm=1477
read_sensors.php[5388]: gain[mq5]=1 off[mq5]=0
read_sensors.php[5388]: file=/sys/devices/ocp.3/helper.12/AIN6 val=816 ppm=816
read_sensors.php[5388]: gain[mq7]=1 off[mq7]=0
read_sensors.php[5388]: file=/sys/devices/ocp.3/helper.12/AIN4 val=572 ppm=572
read_sensors.php[5388]: loop end
read_sensors.php[5388]: loop start
read_sensors.php[5388]: gain[mq2]=0.125 off[mq2]=0
read_sensors.php[5388]: file=/sys/devices/ocp.3/helper.12/AIN0 val=677 ppm=84.625
read_sensors.php[5388]: gain[mq4]=1 off[mq4]=0
read_sensors.php[5388]: file=/sys/devices/ocp.3/helper.12/AIN2 val=1456 ppm=1456
read_sensors.php[5388]: gain[mq5]=1 off[mq5]=0
read_sensors.php[5388]: file=/sys/devices/ocp.3/helper.12/AIN6 val=847 ppm=847
read_sensors.php[5388]: gain[mq7]=1 off[mq7]=0
read_sensors.php[5388]: file=/sys/devices/ocp.3/helper.12/AIN4 val=569 ppm=569
read_sensors.php[5388]: loop end
...

Tip

Note that only the first sensor has been (more or less) calibrated!

The process can be stopped as usual with the CTRL + C sequence.

Now, we can read the system status (in this case, the last read sensors datum) by using the my_dump.sh script, as follows:

root@beaglebone:~# ./my_dump.sh status
n   v
alarm   off
mq2   84.625
mq4   1456
mq5   815
mq7   569

Note

The my_dump.sh script is stored in the chapter_01/my_dump.sh file in the book's example code repository.

The same script can be used to dump a logging table too. For instance, if we wish to see the MQ-2 logged data, we can use the following command:

root@beaglebone:~# ./my_dump.sh mq2_log
t   v
2015-05-15 17:39:36	101.25
2015-05-15 17:39:41	84.625
2015-05-15 17:39:46	84.625

Managing the actuators

When a sensor detects a dangerous gas concentration, the alarm status variable is set to on state. Therefore, when this happens, we have to turn both the LED and the buzzer on, and we must send an SMS message to the user's predefined number.

In order to do these actions, we have to properly set up the GPIO lines that manage the LED and the buzzer as shown previously, and then we have to talk with the GSM module through the serial port to send the SMS message. To do this last step, we have to to install the gsm-utils package where we can find the gsmsendsms command, which is used to actually send the SMS. In order to install the package, we use the following command:

root@beaglebone:~# aptitude install gsm-utils

Then, after placing a functioning SIM into the module, we can verify to be able to talk with the GSM module with the gsmctl command, as shown in the following code:

root@beaglebone:~# gsmctl -d /dev/ttyO1 me    
<ME0>  Manufacturer: Telit
<ME1>  Model: GL865-QUAD
<ME2>  Revision: 10.00.144
<ME3>  Serial Number: 356308042878501

Then, we can verify the current PIN status by using the following command:

root@beaglebone:~# gsmctl -d /dev/ttyO1 pin
<PIN0> READY

The preceding message shows us that the GSM module is correctly configured and the SIM in it is ready to operate; however, the SIM must be enabled by inserting the proper PIN number if we get the following message:

gsmsendsms[ERROR]: ME/TA error 'SIM PIN required' (code 311)

In this case, we must use the following command:

root@beaglebone:~# gsmctl -d /dev/ttyO1 -I "+cpin=NNNN"

In the preceding command, NNNN is the PIN number of your SIM. If the command hangs with no output at all, it means that the connection is wrong.

Now that we've checked the connection and the SIM is enabled, we can start to send SMS messages by using the following command:

root@beaglebone:~# gsmsendsms -d /dev/ttyO1 "+NNNNNNNNNNNN" 'Hello world!'

In the preceding command, the NNNNNNNNNNNN string is the number where the SMS must be sent.

Tip

If the module answers is as follows it means that SMS Service Centre Address (SCA); which is the phone number of the centre that is accepting SMS for delivery is not set correctly in your phone:

gsmsendsms[ERROR]: ME/TA error 'Unidentified subscriber' (code 28)

In this case, you should ask to your GSM operator and then try the following command:

root@beaglebone:~# gsmctl -o setsca "+SSSSSSSSSSSS"

In the preceding command, the SSSSSSSSSSSS string is the number of your centre.

Okay, now we have all the needed information to control our actuators. A possible implementation of main function of the managing task is as follows:

function daemon_body()
{
   global $loop_time;
   global $actuators;

   $sms_delay = db_get_config("sms_delay_s");

   $old_alarm = 0;
   $sms_time = strtotime("1970");

   # The main loop
   dbg("start main loop (loop_time=${loop_time}s)");
   while (sleep($loop_time) == 0) {
   dbg("loop start");

      # Get the "alarm" status and set all alarms properly
      $alarm = db_get_status("alarm");
         foreach ($actuators as $a) {
            $name = $a['name'];
            $file = $a['file'];

            dbg("file=$file alarm=$alarm");
            $ret = gpio_set($file, $alarm);
               if (!$ret)
                  err("unable to write actuator $name");
         }

      # Send the SMS only during off->on transition
      if ($alarm == "on" && $old_alarm == "off" &&
         strtotime("-$sms_time seconds") > $sms_delay) {
            do_send_sms();
            $sms_time = strtotime("now");
         }

      $old_alarm = $alarm;

      dbg("loop end");
   }
}

Note

The complete script is stored in the chapter_01/write_actuators.php file in the book's example code repository.

Again, the function is really simple—we simply have to read the current alarm variable status from the database and then set up the actuators according to it. Note that a special job must be done for the SMS management; in fact, the system must send one SMS at time and only during the off-to-on transition and not before sms_delay seconds. To do the trick, we use the old_alarm and sms_time variables to save the last loop status.

To test the code, we can control the alarm variable by using the my_set.sh command as follows:

root@beaglebone:~# ./my_set.sh status alarm on
root@beaglebone:~# ./my_set.sh status alarm off

Note

The script is stored in the chapter_01/my_set.sh file in the book's example code repository.

So, let's start the script with the command:

root@beaglebone:~# ./write_actuators.php -d -f -l -T 5
write_actuators.php[5474]: signals traps installed
write_actuators.php[5474]: start main loop (loop_time=5s)
write_actuators.php[5474]: loop start
write_actuators.php[5474]: file=/sys/class/gpio/gpio68 alarm=off
write_actuators.php[5474]: file=/sys/class/gpio/gpio69 alarm=off
write_actuators.php[5474]: loop end
write_actuators.php[5474]: loop start
write_actuators.php[5474]: file=/sys/class/gpio/gpio68 alarm=off
write_actuators.php[5474]: file=/sys/class/gpio/gpio69 alarm=off
write_actuators.php[5474]: loop end

On another terminal, we can change the alarm variable, as already stated, by using the following command:

root@beaglebone:~# ./my_set.sh status alarm on

After this we notice that the script does its job:

write_actuators.php[5474]: loop start
write_actuators.php[5474]: file=/sys/class/gpio/gpio68 alarm=on
write_actuators.php[5474]: file=/sys/class/gpio/gpio69 alarm=on
write_actuators.php[5474]: send SMS...
write_actuators.php[5474]: loop end

Regarding how to send an SMS message in PHP, I simply used the following code:

function do_send_sms()
{
   dbg("send SMS...");
   system('gsmsendsms -d /dev/ttyO1 "' . PHONE_NUM . '" "GAS alarm!"');
}

Basically, here we use the system() function to call the gsmsendsms command.

Note

You may note that gsmsendsms takes a while to send the SMS. It's normal.

Controlling the environment

Now, we only need the glue between the sensors and actuators managing tasks, that is, a periodic function that according to the user inputs periodically checks whether the alarms must be activated according to the information read, or not.

A possible implementation of the main function of the monitor.php script is as follows:

function daemon_body()
{
   global $loop_time;
   global $actuators;

   # The main loop
   dbg("start main loop (loop_time=${loop_time}s)");
   while (sleep($loop_time) == 0) {
      dbg("loop start");

      # Get the gas concentrations and set the "alarm" variable
      $mq2 = db_get_status("mq2");
      $mq2_th_ppm = db_get_config("mq2_th_ppm");
      dbg("mq2/mq2_th_ppm=$mq2/$mq2_th_ppm");
      $mq4 = db_get_status("mq4");
      $mq4_th_ppm = db_get_config("mq4_th_ppm");
      dbg("mq4/mq4_th_ppm=$mq4/$mq4_th_ppm");
      $mq5 = db_get_status("mq5");
      $mq5_th_ppm = db_get_config("mq5_th_ppm");
      dbg("mq5/mq5_th_ppm=$mq5/$mq5_th_ppm");
      $mq7 = db_get_status("mq7");
      $mq7_th_ppm = db_get_config("mq7_th_ppm");
      dbg("mq7/mq7_th_ppm=$mq7/$mq7_th_ppm");

      $alarm = $mq2 >= $mq2_th_ppm ||
         $mq2 >= $mq2_th_ppm ||
         $mq2 >= $mq2_th_ppm ||
         $mq2 >= $mq2_th_ppm ? 1 : 0;

      db_set_status("alarm", $alarm);
      dbg("alarm=$alarm");

      dbg("loop end");
   }
}

Note

The complete script is stored in the chapter_01/monitor.php file in the book's example code repository.

The function starts the main loop where, after getting the sensors' thresholds, it simply gets the last sensor's values and sets up the alarm variable accordingly.

Again, we can change the gas concentration thresholds by using the my_set.sh command as follows:

root@beaglebone:~# ./my_set.sh config mq2_th_ppm 5000

We can test the script by executing it in the same manner as the previous two, as follows:

root@beaglebone:~# ./monitor.php -d -f -l -T 5
monitor.php[5819]: signals traps installed  
monitor.php[5819]: start main loop (loop_time=5s)
monitor.php[5819]: loop start
monitor.php[5819]: mq2/mq2_th_ppm=84.625/5000
monitor.php[5819]: mq4/mq4_th_ppm=1456/2000
monitor.php[5819]: mq5/mq5_th_ppm=815/2000
monitor.php[5819]: mq7/mq7_th_ppm=569/2000
monitor.php[5819]: alarm=0
monitor.php[5819]: loop end
monitor.php[5819]: loop start
monitor.php[5819]: mq2/mq2_th_ppm=84.625/5000
monitor.php[5819]: mq4/mq4_th_ppm=1456/2000
monitor.php[5819]: mq5/mq5_th_ppm=815/2000
monitor.php[5819]: mq7/mq7_th_ppm=569/2000
monitor.php[5819]: alarm=0
monitor.php[5819]: loop end
...

To stop the test, just use the CTRL + C sequence. You should get an output as follows:

^Cmonitor.php[5819]: signal trapped!

Final test

Once everything has been connected and the software is ready, it's time to do a little test of our new system. The demonstration can be done by using a lighter. In fact, our system is really sensitive to the gas inside the lighter!

First of all, we have to check the system configuration:

root@beaglebone:~# ./my_dump.sh config
n   v
mq2_gain   0.125
mq2_off   0
mq2_th_ppm   150
mq4_gain   0.125
mq4_off   0
mq4_th_ppm   150
mq5_gain   0.125
mq5_off   0
mq5_th_ppm   150
mq7_gain   0.125
mq7_off   0
mq7_th_ppm   150
sms_delay_s   300

Tip

Note that I used a very weak calibration setting; however, these are okay for a demo.

Then, we can take a look at the system's current status:

root@beaglebone:~# ./my_dump.sh status
n   v
mq2   73.5
mq4   121.75
mq5   53
mq7   80.5
alarm   0

Then, we can do all hardware settings at once by using the chapter_01/SYSINIT.sh script in the book's example code repository as follows:

root@beaglebone:~# ./SYSINIT.sh
done!

Okay, now let's start all the required process daemons:

root@beaglebone:~# ./read_sensors.php -d -T 2
root@beaglebone:~# ./write_actuators.php -d -T 2
root@beaglebone:~# ./monitor.php -d -T 2

Tip

Note that all the daemons are running in background in this way; however, the debugging messages are enabled and they can be viewed into the system log with the following command:

# tail -f /var/log/syslog

Now, we have to approach the lighter to the sensors and press the button on the lighter in order to allow the sensor to detect the gas. After a while, the alarms should be turned on, and looking at the system status, we should get the following:

root@beaglebone:~# ./my_dump.sh status
n   v
mq2   203.875
mq4   166.5
mq5   52.5
mq7   122.625
alarm   1

Also, if we have set up a phone number, we should receive an SMS on the phone!

As last step, let's display the data logged by plotting them. We can use the following command to extract the data from the database:

root@beaglebone:~# ./my_dump.sh mq2_log | awk '{ print $2 " " $3 }' > mq2.log

In the mq2.log file, we should find something like the following:

root@beaglebone:~# cat mq2.log
15:02:07 75.25
15:02:10 74.25
15:02:12 74.25
15:02:14 74.375
15:02:16 74.25
...

Now, using the next command, we're going to create a PNG image holding a plot of our data:

$ gnuplot mq2.plot

Tip

Note that in order to execute this command, you need the gnuplot command, which can be installed by using the following command:

# aptitude install gnuplot

Also, both the mq2.log and mq2.plot files are need. The former is created by the preceding command line, while the latter can be found in the chapter_01/mq2.plot file in the book's example code repository. It holds the gnuplot instructions to effectively draw the plot.

The plot of the MQ-2 data of my test is shown in the following screenshot:

Final test

As you can see, the sensors are very sensitive to the gas; as soon as I opened my lighter and the gas reached them, the ppm concentration went to high values very quickly.

To stop the test, we can use the following commands:

root@beaglebone:~# killall read_sensors.php
root@beaglebone:~# killall write_actuators.php
root@beaglebone:~# killall monitor.php

Summary

In this chapter, we discovered how to manage the ADCs, the GPIOs lines, a GSM module thought, and a serial port. We also saw how to implement a simple monitoring program that can communicate (through a database server) with a sensors reader task to collect input data, and with an actuators manager to alert the user in case of emergency.

In the next chapter, we'll see how to manage an ultrasonic distance sensor to implement a parking assistant that can communicate to the driver, the distance between the car and the garage's wall. However, the really interesting part of the next chapter is about how to manage the distance sensor in two different setups: one with all the peripherals near the BeagleBone Black, and another with a remote connection of the sensor through a USB cable.

Left arrow icon Right arrow icon

Key benefits

  • Build, set up, and develop your circuits via step-by-step tutorial of practical examples, from initial board setup to device driver management
  • Get access to several kinds of computer peripherals to monitor and control your domestic environment using this guide
  • This book is spread across 10 chapters all focused on one practical home automation project

Description

BeagleBone is a microboard PC that runs Linux. It can connect to the Internet and can run OSes such as Android and Ubuntu. BeagleBone is used for a variety of different purposes and projects, from simple projects such as building a thermostat to more advanced ones such as home security systems. Packed with real-world examples, this book will provide you with examples of how to connect several sensors and an actuator to the BeagleBone Black. You’ll learn how to give access to them, in order to realize simple-to-complex monitoring and controlling systems that will help you take control of the house. You will also find software examples of implementing web interfaces using the classical PHP/HTML pair with JavaScript, using complex APIs to interact with a Google Docs account, WhatsApp, or Facebook. This guide is an invaluable tutorial if you are planning to use a BeagleBone Black in a home automation project.

Who is this book for?

This book is for developers who know how to use BeagleBone and are just above the “beginner” level. If you want to learn to use embedded machine learning capabilities, you should have some experience of creating simple home automation projects.

What you will learn

  • Build a CO (and other gas) sensor with a buzzer/LED alarm to signal high concentrations
  • Log environment data and plot it in a fancy manner
  • Develop a simple web interface with a LAMP platform
  • Prepare complex web interfaces in JavaScript and get to know how to stream video data from a webcam
  • Use APIs to get access to a Google Docs account or a WhatsApp/Facebook account to manage a home automation system
  • Add custom device drivers to manage an LED with different blinking frequencies
  • Discover how to work with electronic components to build small circuits
  • Use an NFS, temperature sensor, relays, and other peripherals to monitor and control your surroundings
Estimated delivery fee Deliver to Sweden

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 03, 2016
Length: 378 pages
Edition : 1st
Language : English
ISBN-13 : 9781783986026
Vendor :
BeagleBoard.org
Category :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Sweden

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Feb 03, 2016
Length: 378 pages
Edition : 1st
Language : English
ISBN-13 : 9781783986026
Vendor :
BeagleBoard.org
Category :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 66.98
BeagleBone Home Automation Blueprints
€36.99
Building a Home Security System with Raspberry Pi
€29.99
Total 66.98 Stars icon

Table of Contents

12 Chapters
1. Dangerous Gas Sensors Chevron down icon Chevron up icon
2. Ultrasonic Parking Assistant Chevron down icon Chevron up icon
3. Aquarium Monitor Chevron down icon Chevron up icon
4. Google Docs Weather Station Chevron down icon Chevron up icon
5. WhatsApp Laundry Room Monitor Chevron down icon Chevron up icon
6. Baby Room Sentinel Chevron down icon Chevron up icon
7. Facebook Plant Monitor Chevron down icon Chevron up icon
8. Intrusion Detection System Chevron down icon Chevron up icon
9. Twitter Access Control System with Smart Card and RFID Chevron down icon Chevron up icon
10. A Lights Manager with a TV Remote Controller Chevron down icon Chevron up icon
11. A Wireless Home Controller with Z-Wave Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela