Home IoT & Hardware Raspberry Pi 3 Home Automation Projects

Raspberry Pi 3 Home Automation Projects

By Shantanu Bhadoria , Ruben Oliva Ramos
books-svg-icon Book
eBook $29.99 $20.98
Print $38.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $29.99 $20.98
Print $38.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Creating a Raspberry Pi-Powered Magic Mirror
About this book
Raspberry Pi 3 Home Automation Projects addresses the challenge of applying real-world projects to automate your house using Raspberry Pi 3 and Arduino. You will learn how to customize and program the Raspberry Pi 3 and Arduino-based boards in several home automation projects around your house. This book aims to help you integrate different microcontrollers like Arduino, ESP8266 Wi-Fi module, Particle Photon and Raspberry Pi 3 into the real world, taking the best of these boards to develop some exciting home automation projects. We will start with an interesting project creating a Raspberry Pi Powered smart mirror and move on to Automated Gardening System, which will help you build a simple smart gardening to keep your garden healthy with minimal effort. You will also learn to build projects such as CheerLights into a holiday display, a project to erase parking headaches with OpenCV and Raspberry Pi 3, create Netfl ix's "The Switch" for the living room and lock down your house like Fort Knox with a Windows IoT face recognition-based door lock system. By the end of the book, you will be able to build and automate the living space with intriguing IoT projects and bring a new degree of inter connectivity to your world.
Publication date:
November 2017
Publisher
Packt
Pages
226
ISBN
9781783283873

 

Creating a Raspberry Pi-Powered Magic Mirror

We’ll be operating with the understanding that this may be the first Raspberry Pi project that you have attempted to undertake. The Magic Mirror is a practical and easy way to introduce yourself to working the Raspberry Pi and will also serve a great conversation piece for your home. To briefly cover the contents of this chapter, you will learn about the Raspberry Pi single-board computer and how to navigate the command line using basic Linux commands. We will focus on downloading the latest version of the Magic Mirror project by Michael Teeuw from GitHub (https://github.com/MichMich/MagicMirror) and setting up the open source modular platform to work with the Pi 3. Once downloaded, we will take a look at editing the content for the Magic Mirror and how one might go about integrating third-party modules to create a custom Magic Mirror experience. As a final step, a discussion will surround the construction of the mirror’s frame and what might be best for your personal home experience.

By the end of this chapter, you’ll know how to:

  • Work with the Raspberry Pi
  • Operate within LXTerminal
  • Navigate the Magic Mirror repository
  • Do basic file editing with GNU Nano
  • Use the Raspberry Pi GPIO to attach sensors
 

What is the Raspberry Pi?

The Raspberry Pi is a credit-card-sized single-board computer that was developed by the Raspberry Pi Foundation in 2012. The foundation's main goal is to promote computer literacy across the globe by offering an affordable and mutable bit of hardware to the masses. It's become a huge hit among the maker communities and is paving its way through education as a cheap, practical, and convenient way to teach digital and physical making. As we move through the text, I will be centering my conversation on the base model and necessities of a Raspberry Pi 3, as this is the most current version of the Raspberry Pi on the market. If you're using a Raspberry Pi 2 or B+, I’ll make sure to point out the differences in hardware usage as we move along.

While taking a closer look, the Raspberry Pi 3 boasts of some impressive specs for its size:

  • A 1.2 GHz 64-bit quad-core ARMv8 CPU
  • 802.11n Wireless LAN
  • Bluetooth 4.1
  • Bluetooth Low Energy (BLE)
  • 1 GB RAM
  • Four USB ports
  • 40 GPIO pins
  • Full HDMI port
  • Ethernet port
  • Combined 3.5mm audio jack and composite video
  • Camera Interface (CSI)
  • Display Interface (DSI)
  • Micro SD card slot
  • VideoCore IV 3D graphics core

Furthermore, the Raspberry Pi 3 has the same form factor as the earlier models, the Raspberry Pi 2 and the B+, allowing you to reuse the casing and accessories.

Raspberry Pi Model 3:

You will need the following materials for this project:

  • Project materials:
    • Raspberry Pi 2/3
    • Micro USB charging cable
    • Wi-Fi dongle (if you are using Pi 2)
    • A microSD card
    • Monitor (HDMI/VGA)
    • Two-way glass/acrylic
    • Wooden frame
  • Optional materials:
    • PIR motion sensor
    • Pi Camera Module
    • Ultrasonic sensor—HC-SR04
    • HDMI-to-VGA converter

Purchasing the Raspberry Pi

When purchasing a Raspberry Pi, it may look a bit intimidating at first, given the sheer amount of add-ons or the variety of kits from which you can choose. At a minimum, for this project and the others in this book, you’ll need a kit that contains a Raspberry Pi 3, a micro-USB charging cable, an 8 gigabyte (or larger) microSD card preinstalled with NOOBS, and an HDMI cable. For the novice user, it’s generally recommended that you also acquire an HDMI monitor and a USB-connected keyboard and mouse to easily display and interact with the Raspberry Pi interface:

The Raspberry Pi revision 2 and B+ models differ from the Raspberry Pi revision 3, as neither revision 2 or B+ have Bluetooth or Wi-Fi built into the board itself. So, if you’re working with either of these models, be aware that you will have to purchase a Wi-Fi dongle (highly recommended) or a Bluetooth dongle in order to have these connectivity options available to you.

Setting up the Raspberry Pi

Assuming that you’ve gotten the required materials, it’s now time to get the Raspberry Pi up and running. Before powering it on, you're going to make sure that you connect the Pi to a monitor, connect the keyboard and mouse, and make sure that the microSD card is inserted. If you have any dongles to plug into the extra USB ports, now would be the time to do that.

In discussing the microSD card, with most kits bought online for the Raspberry Pi, the microSD card will come preloaded with NOOBS (known as New Out Of the Box Software), which lets you easily set up Raspbian, the Foundation’s officially supported operating system. Raspbian is a Linux distribution based on the Debian distribution. You can, however, purchase a microSD card that does not have the NOOBS installation preloaded on it. If this is the case, using your home computer or laptop, you can manually install NOOBS or the image of your choosing onto the SD card. Here are the steps for the manual installation, as aligned to the Raspberry Pi Foundation’s suggestions:

  1. Visit the SD Association’s website (https://www.sdcard.org/) and download SD Formatter 5.0 for either Windows or Mac systems.
  2. Follow the instructions to install the software.
  3. Insert your SD card into the computer or laptop’s SD card reader and make note of the drive letter allocated to it, for example, F or G.
  4. In SD Formatter, select the drive letter for your SD card and format it.
  5. Download the NOOBS ZIP file from the Raspberry Pi Foundation Downloads page (https://www.raspberrypi.org/downloads/noobs/).
  6. Save this to a folder on your computer and then extract the files.
  7. Once your SD card has been formatted and the files from the ZIP are extracted, you are going to drag the unzipped files onto the SD card. As a note, make sure you’re dragging the contents of the NOOBS folder onto the SD card. If you move the entire NOOBS folder itself, the installation process will not follow through.
  8. When the files have finished transferring, eject the SD card and place it into your Raspberry Pi.

Assuming the microSD card has made it to your Raspberry Pi and all of the requisite hardware is connected, it is now time to power on the board by plugging in the micro USB charging cable.

This will take a little time as you go through the setup screen, but you’ll be looking at the Raspbian desktop shortly:

 

Moving on to the LXTerminal

While the Raspberry Pi has a healthy variety of applications and programs for our consumption, we’re going to be primarily using the LXTerminal to download and interact with the Magic Mirror program. For those of you unfamiliar with the Terminal, it’s essentially a program that allows a user to directly manipulate their computer system through the use of commands. As we move through the text, when I refer to the command line, I’m talking about the Terminal and the location where a user will input the commands.

Understanding how the Terminal works and being able to use the command line is a very powerful tool when working to manipulate files on the Raspberry Pi. Commands can be strung together and input in order to efficiently carry out tasks that other applications cannot. When you initially open LXTerminal, you will see a screen with a blinking cursor. On the left-hand side, there will be a prompt that shows your current username and the hostname of the Pi. Both the username and hostname can be changed later on in settings if you’d like to tailor the Pi further for your uses:

Basic Linux commands

There are basic Linux commands that are going to be very useful in your navigation through your filesystems through the Terminal. In this section, I want to list some essential commands that will help you when building the Magic Mirror. With each command, I’ll provide a brief explanation. As with anything, the best way to learn how to successfully use these commands is with practice. Also, note that syntax is important when working with the command line. The computer interprets capitalized and uncapitalized letters as two different symbols, so we have to make sure we type our commands as they are shown. A good rule of thumb is that if something doesn’t work the first time, go back and proofread what you have typed.

Helpful commands

Here are some helpful Linux or NOOBS commands that will come in handy when you work on your Raspberry Pi:

  • sudo: Short for super user do, this command is powerful and necessary. When used before any others in the command line, you're telling the computer that you are running the command as the root user. This gives you the ability to alter files that may be unalterable to the regular user on the computer. When first working with the Terminal, I suggest you use sudo primarily, as opposed to su (though su is needed for particular actions). This will curtail your use of the super user command, putting a slight speed bump between you and any commands that may unintentionally delete necessary files from your system.
  • su: While similar to sudo, instead of running a command as root, su makes you root. As I said earlier, sudo is useful for targeted commands, but if you’re working extensively as root, su may be the better option. Just make sure you stay aware that you're working as a root user, as you do not want to delete anything necessary in your Raspberry Pi system files.
  • cd: This changes your location to a directory of your choosing. Remember, a directory is essentially a folder, and this allows you to navigate to a specific folder as long as you know the pathway. Furthermore, if you are in a specific directory and want to return to your /home directory, typing in cd will bring you immediately back to /home.
  • cd –: To build on the cd command, a useful command is to add the dash after the space after cd. This will allow you to immediately return to the previous directory in your pathway, for example, cd /MagicMirror/modules/. This will bring you to the modules folder within the MagicMirror folder. If you want to go back to the MagicMirror folder, you would then type cd –.

  • ls: When you're in a directory and wish to know the folder's contents, typing in this command will list the files within the folder.

  • pwd: This stands for print working directory. It is very useful if you’ve forgotten your current pathway or need to access that information.

  • mkdir: This command enables you to create a directory with a name of your choosing.

  • cp: This is the copy function. It allows you to copy a file from its source destination to another destination of your choosing.

  • nano: This command calls upon the Terminal’s nano text editor, enabling you to access and modify the contents of the file from within the Terminal emulator. This is very useful for quick changes to files on the Pi, and I will be using this as the command-line editor for this text.

Let's move forward. I find these to be the most useful commands for this project; however, there is a vast array of commands that will make your navigation more efficient. As you learn more with the Pi, it’s encouraged that you research more commands and how they work in order to maximize your experience in LXTerminal.

 

The Magic Mirror

The project was first put together by Michael Teeuw in 2014 and has since garnered much popularity in the maker community, inspiring smart mirror projects created by the average laymen. The project is open source and community-driven, enabling all users to download, edit, and create using this framework. On the most basic level, the Magic Mirror program is run on the Raspberry Pi, typically connected to a monitor specifically designated for this project.

The user then programs the Magic Mirror interface to his or her liking, adding functions such as e-mail notifications, NFL scores, weather alerts, reminders, and additional text. Once the Magic Mirror is set up to your liking, it’s common to see people install a wooden frame and a two-way mirror around the monitor, effectively creating a do-it-yourself smart mirror.

Downloading the Magic Mirror repository

Now that we’ve established how to set up our Raspberry Pi and familiarized ourselves with the Terminal, it’s time to download the Magic Mirror repository. In order to do this, you’ll have to clone the repository that is hosted on the popular website GitHub. GitHub is an online version control repository, basically, a place where the changes to computer files and code can be tracked and all workers on a particular project can come together to add the appropriate documentation. In line with the open source nature of this project, it’s very helpful for your future endeavors with this project. If you find that you have further questions, bug issues, or code to contribute, checking out their GitHub repository is the next and later step.

Now in terms of cloning the repository, using this phrasing is deliberate. To clone a repository means to not only download the current working copy of a project, but to also download every version of the project available. This is extremely useful for individuals who face problems with file corruption or server issues. So, moving into cloning the Magic Mirror repository, it’s fairly straightforward and we’ll get to it shortly. I’m having you walk through the manual installation of the Magic Mirror so that you have a better understanding of what is happening while interacting with the command line. I’ll show the alternate way later on in the text, but this builds some necessary skills for later on in this book. In turn, we have to install a few more packages before cloning into the repository in order to have the Magic Mirror run efficiently.

Installing Node.js

Node.js is an important aspect of the Magic Mirror setup as it creates the screen image with the specific modules on the monitor. It’s described as “an asynchronous event driven JavaScript runtime… designed to build scalable network applications” (about Node.js). While Raspbian, our operating system, does a timely job at staying updated, it behooves us to make sure that we have the latest version of Node.js in order to run our Magic Mirror program. We’re going to install the latest 64-bit ARM (known as Advanced Reduced Instruction Set Computer Machines) version for our Raspberry Pi. In order to install the latest version of Node.js, you’re going to execute the following steps:

  1. Make sure that you have an active Internet connection.
  2. Open up LXTerminal.
  3. In the Terminal, type the following:
wget http://node-arm.herokuapp.com/node_latest_armhf.deb
sudo dpkg –i node_latest_armhf.deb
  1. This was me telling the Pi to grab the most current version of Node.js and then switch to the root user in order to install the node package using dpkg, which is the Debian package management system.
  2. Wait for Node.js to download.
  3. Once the download has finished, double-check that you have the latest version by inputting node –v into the command line.

Installing Grunt

With some of the updates to the Magic Mirror program, I’ve found that it’s best to have the latest version of Grunt installed on your Pi as well. Grunt is basically a task manager and a build manager that integrates with Node.js. It has certain features that are helpful in the JavaScript environment, such as minification or the process of removing all unnecessary characters from source code without changing its functionality. On top of that, Grunt enables your program to reload as you make changes to your code during development. You’ll notice, when we start the Magic Mirror later on, that we’re going to call on Grunt usage with the npm start command. Grunt installation is very simple. We’re going to want to install Grunt’s command-line interface globally on the Pi. This way, we can readily call upon it when working from any directory:

sudo npm install –g grunt-cli

With Node.js and Grunt now downloaded, it’s time to finally clone into our repository:

  1. Make sure your Raspberry Pi is updated and upgraded. You can do this by typing sudo apt-get update && sudo apt-get upgrade.
  2. Clone the repository with git clone https://github.com/MichMich/MagicMirror ~/MagicMirror.
  3. This will download the directory containing the Magic Mirror files directly to your /home/pi folder.
  4. You’re going to enter the repository with cd ~/MagicMirror.
  5. You are then going to install and run the application using npm install && npm start.

It will take a second or two, but you will then see the default screen for your Magic Mirror pop up on your screen (Teeuw).

Working with the configuration file

Now that we have the Magic Mirror up and running, we have to personalize it. Consider where the Magic Mirror is going to be placed within your home. Are you going to be using it as a clock? Does it replace your bathroom mirror? Is this something that you’ve mounted near the front door so that you may scan some information as you leave for the day? All are excellent questions to consider and will mold how you choose which modules to include and which information should be highlighted. As you consider your options, take note of the default modules that are preinstalled with the application:

  • Clock: This displays the current date and time.
  • Calendar: This displays information from any public iCal calendar and can combine multiple calendars into one.
  • Current weather: This will display your chosen location’s weather information. It’s geared toward using the API from http://www.openweathermap.org/api.
  • Weather Forecast: Also using OpenWeatherMap, this will display the location’s forecast for the week.
  • News Feed: You can input news URLs of your choosing and the title of each news source, and this will scroll through the major headlines of the chosen news sources.
  • Compliments: This gives you the ability to randomize your own text content on the screen at a given the time of day: morning, afternoon, and evening.
  • Hello world: This places static text on your screen in a location of your choosing.
  • Alert: This module will display notifications from other modules.

As you can see, these working in tandem can create a very informative mirror for your everyday use. So, how do we actually customize? The customization process relies on the configuration file nestled in /MagicMirror/config. You’ll notice that when you move into the config directory, a file that you see listed is config.js.sample:

We have to make a copy of config.js.sample, and the easiest way to do that will be by making sure that you’re in the config directory and making a copy of the file:

cp config.js.sample config.js

So, any changes that you make to the config.js file will show up on the Magic Mirror screen. If you make an inexcusable error or find yourself needing to revert to the defaults entirely, you still have the sample copy to rely upon.

This is the sort of screen you will see with the default config.

Editing the configuration file

If you’re a complete novice to JavaScript, don’t worry too much about this process. Remember, the idea is to learn through trial and error and create a product that instills some pride. One way to build skills is to start editing and adding to the configuration file copy that you created in the previous section. The nice part about editing this file is that if your syntax is wrong or there’s a typo living somewhere in your document, the Magic Mirror will display a screen that alerts you to this problem. So there’s no harm in trying it out!

If you find it difficult to fix any problems or errors in the script, be mindful that there are browser-based JavaScript editors online that help you find the errors in your code. It comes down to a matter of copying and pasting, so I’d encourage you to turn to a website such as JSLint, found at http://www.jslint.com/. So, on to the configuration file as a whole:

/* Magic Mirror Config Sample
*
* By Michael Teeuw http://michaelteeuw.nl
* MIT Licensed.
*
* For more information how you can configurate this file
* See https://github.com/MichMich/MagicMirror#configuration
*
*/

var config = {
address: "localhost", // Address to listen on, can be:
// - "localhost", "127.0.0.1", "::1" to listen on loopback interface
// - another specific IPv4/6 to listen on a specific interface
// - "", "0.0.0.0", "::" to listen on any interface
// Default, when address config is left out, is "localhost"
port: 8080,
ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1"], // Set [] to allow all IP addresses
// or add a specific IPv4 of 192.168.1.5 :
// ["127.0.0.1", "::ffff:127.0.0.1", "::1", "::ffff:192.168.1.5"],
// or IPv4 range of 192.168.3.0 --> 192.168.3.15 use CIDR format :
// ["127.0.0.1", "::ffff:127.0.0.1", "::1", "::ffff:192.168.3.0/28"],

language: "en",
timeFormat: 24,
units: "metric",

modules: [
{
module: "alert",
},
{
module: "updatenotification",
position: "top_bar"
},
{
module: "clock",
position: "top_left"
},
{
module: "calendar",
header: "US Holidays",
position: "top_left",
config: {
calendars: [
{
symbol: "calendar-check-o ",
url: "webcal://www.calendarlabs.com/templates/ical/US-Holidays.ics"
}
]
}
},
{
module: "compliments",
position: "lower_third"
},
{
module: "currentweather",
position: "top_right",
config: {
location: "New York",
locationID: "", //ID from http://www.openweathermap.org/help/city_list.txt
appid: "YOUR_OPENWEATHER_API_KEY"
}
},
{
module: "weatherforecast",
position: "top_right",
header: "Weather Forecast",
config: {
location: "New York",
locationID: "5128581", //ID from http://www.openweathermap.org/help/city_list.txt
appid: "YOUR_OPENWEATHER_API_KEY"
}
},
{
module: "newsfeed",
position: "bottom_bar",
config: {
feeds: [
{
title: "New York Times",
url: "http://www.nytimes.com/services/xml/rss/nyt/HomePage.xml"
}
],
showSourceTitle: true,
showPublishDate: true
}
},
]

};

/*************** DO NOT EDIT THE LINE BELOW ***************/

While reprinted here, you can also access this file for editing by employing the use of the nano function in the command line. As always, make sure that you're in the configuration directory found within the Magic Mirror directory: /home/pi/MagicMirror/configuration. At this point, you want to tell the Pi that you wish to edit config.js. In order to do that, type sudo nano config.js into the command line. This will bring up the preceding file text on your screen, where you can easily move the cursor around to add and remove items.

In terms of observation, there are a few items to which I wish to call your attention. Toward the top of the script, you’ll notice that there are some initial customizable options, such as port, ipWhitelist, language, timeFormat, and units. Let’s explore each briefly:

  • port: Not to be confused with a USB port, this is regarded as the endpoint of information in an operating system. You can change the port address, but 8080 is the conventional address that you’ll see used somewhat ubiquitously as your personally hosted web server. Over your local network, it’s easily accessed and can be used to view your Magic Mirror in a browser, as opposed to the application view. As a side note, running the Magic Mirror on a local host would be useful if you wanted multiple browser displays showing the same information. Some museums and venues use this setup for guests.
  • ipWhitelist: If you’d like to remote into your Magic Mirror, you’ll have to add the IP address of the machine you’d like to use. With updates to the Magic Mirror happening frequently, I would suggest that you look to the active Magic Mirror community and its discussions in case there are any issues.
  • language: While setting to English, you also have the options of nl, ru, and fr, Dutch, Russian, and French, respectively.
  • timeFormat: You can change this from the 24-hour clock format to the 12-hour format by inputting 12 in this space.
  • units: While setting to metric, you can replace this with imperial.

After going through these preferential settings, you’ll notice that the body of the script deals directly with the modules that are going to be displayed on your screen. You’ll notice a pattern with the curly brackets, as they enclose each module. There is a standardization to how each module is set up, which may be helpful if you find yourself puzzled about how to incorporate preferences and variables:

{
module: 'module name',
position: 'position',
header: 'optional header',
config: {
extra option: 'value'
}
},

Understanding the module

So, let’s take the compliments module as our example working piece. If you pass your eyes back over the config.js file, you’ll notice that the compliments module is nestled fifth from the top. You’ll notice that the only information in the config.js file for the compliments module is its placement: lower third. How does the compliments module know what information to display? Where is the revolving text coming from? The config.js file is using and calling up the information stored in the compliments directory, found in /home/pi/MagicMirror/defaults/compliments, specifically, compliments.js. Logically, we would need to edit the compliments.js file in order to change the content of the compliments module. Accordingly, we must understand that the config.js file literally deals with the spacing and configuration of the Magic Mirror display. Moving forward, let’s take a look at a portion of the compliments.js file after you’ve navigated to the compliments directory:

cd /home/pi/MagicMirror/defaults/compliments
sudo nano compliments.js

While looking at this file, we see the most important content aspects—anytime, morning, afternoon, and evening, toward the top. As you can guess, these compliments or text portions roll through the screen given the appropriate times of the day. Consider what content you would like to change or add and play around with modifying it. Also, make note that later in the compliments file, you have the ability to modify the hours dedicated to morning and afternoon, the leftover hours being dedicated to the evening:

complimentArray: function() {
var hour = moment().hour();
var compliments;

if (hour >= 3 && hour < 12 && this.config.compliments.hasOwnProperty("morning")) {
compliments = this.config.compliments.morning.slice(0);
} else if (hour >= 12 && hour < 17 && this.config.compliments.hasOwnProperty("afternoon")) {
compliments = this.config.compliments.afternoon.slice(0);
} else if(this.config.compliments.hasOwnProperty("evening")) {
compliments = this.config.compliments.evening.slice(0);
}
if (typeof compliments === "undefined") {
compliments = new Array();
}
if (this.currentWeatherType in this.config.compliments) {
compliments.push.apply(compliments, this.config.compliments[this.currentWeatherType]);
}
compliments.push.apply(compliments, this.config.compliments.anytime);
return compliments;
},

Once you’ve played around with modifying, understand that this process is replicated for the majority of modules in this program. I’d recommend that you take the time to look through the default folders and see what else you can change. If you’re worried about mistakes or editing a file in an error, make a copy of the original file, rename it, and leave it so that you have a reference point or a file to revert to.

Installing third-party modules

While the Magic Mirror comes with default modules, there are industrious Internet folk out there creating new, open source modules for download and addition by going to the third-party module portion of the Magic Mirror GitHub website, https://github.com/MichMich/MagicMirror/wiki/MagicMirror%C2%B2-Modules#3rd-party-modules. While extensive to list, you’ll note that there are modules for Twitter, Instagram, NFL scores, and Amazon’s Alexa, to name a few. These come with varying degrees of skill needed to set up, so it’s suggested that you assess which seems to be the best to try and then work through the installation and setup steps. Importantly, when installing a third-party module, you’re going to clone the repository into the Magic Mirror modules folder. Your steps would involve the following:

  1. Navigate to the Magic Mirror modules folder.
  2. Determine the URL of the GitHub repository you wish to clone.
  3. Clone the repository using the steps mentioned previously in the chapter.

Here is an example of what your mirror may look like once you place a two way mirror on the screen plugged into your Raspberry Pi 3:

 

Summary

In this chapter you learned how to set up a cool Magic Mirror that updates you on the news, shows you your local weather and so on while you check yourself out in the mirror. You also learned the basics of Raspberry Pi and the NOOBS operating system. You can enhance your mirror using motion sensors to activate your mirror when you are nearby. You can now continue to explore the Magic Mirror repository for some exciting modules to explore how others are using their Magic Mirror.

About the Authors
  • Shantanu Bhadoria

    Shantanu Bhadoria is an avid traveler and the author of several popular open source projects in Perl, Python, Golang, and Node.js, including many IoT projects. When in Singapore, he works on paging and building control systems for skyscrapers and large campuses in Singapore, Hong Kong, and Macau. He has authored and contributed to public projects dealing with control over gyroscopes, accelerometers, magnetometers, altimeters, PWM generators, and other sensors and controllers, as well as sensor fusion algorithms such as Kalman filters. Shantanu's work in IoT and other fields can be accessed on his GitHub account with the name shantanubhadoria. He is also the author of Device::SMBus, a popular Perl library used to control devices over the I2C bus.

    Browse publications by this author
  • Ruben Oliva Ramos

    Ruben Oliva Ramos is a computer systems engineer from Tecnologico de Leon Institute, with a master's degree in computer and electronic systems engineering and a specialization in teleinformatics and networking from the University of Salle Bajio in Leon, Guanajuato, Mexico. He has more than 5 years of experience of developing web applications to control and monitor devices connected with Arduino and Raspberry Pi, using web frameworks and cloud services to build the Internet of Things applications. He is a mechatronics teacher at the University of Salle Bajio and teaches students of the master's degree in design and engineering of mechatronics systems. Ruben also works at Centro de Bachillerato Tecnologico Industrial 225 teaching subjects such as electronics, robotics and control, automation, and microcontrollers. He is a consultant and developer for projects in areas such as monitoring systems and datalogger data using technologies (such as Android, iOS, HTML5, and ASP.NET), databases (such as SQlite, MongoDB, and MySQL), web servers, hardware programming, and control and monitor systems for data acquisition and programming.

    Browse publications by this author
Latest Reviews (4 reviews total)
The book covered RPI 3 the projects were not interesting.
Very good books in your store
Very good. I like it. Great.
Raspberry Pi 3 Home Automation Projects
Unlock this book and the full library FREE for 7 days
Start now