Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials - Single Board Computers

71 Articles
article-image-setting-your-raspberry-pi
Packt
23 Jun 2017
19 min read
Save for later

Setting up your Raspberry Pi

Packt
23 Jun 2017
19 min read
In this article by Pradeeka Seneviratne and John Sirach, the authors of the book Raspberry Pi 3 Projects for Java Programmers we will cover following topics: Getting started with the Raspberry Pi Installing Raspbian (For more resources related to this topic, see here.) Getting started with the Raspberry Pi With the release of the Raspberry Pi 3 the Raspberry Pi foundation has made a very big step in the history of the Raspberry Pi. The current hardware architecture is now based on a 1.2 Ghz 64 bit ARMv7. This latest release of the Raspberry Pi also includes support for wireless networking and has an onboard Bluetooth 4.1 chip available. To get started with the Raspberry Pi you will be needing the following components: Keyboard and mouse Having both a keyboard and mouse present will greatly help with the installation of the Raspbian distribution. Almost any keyboard or mouse will work. Display You can attach any compatible HDMI display which can be a computer display or a television. The Raspberry Pi also has composite output shared with the audio connector. You will be needing an A/V cable if you want to use this output. Power adapter Because of all the enhancements done the Raspberry Pi foundation recommends a 5V adapter capable to deliver 2.5 A. You would be able to use a lower rated one, but I strongly advice against this if you are planning to use all the available USB ports. The connector for powering the device is done with a Micro USB cable. MicroSD card The Raspberry Pi 3 uses a microSD card. I would advice to use at least a 8 GB class 10 version. This will allow to use the additional space to install applications and as our projects will log data you won’t be running out of space soon. The Raspberry Pi 3 Last but not least a Raspberry Pi 3. Some of our projects will be using the on-board Bluetooth chip and this version is also being focussed on in this article. Our first step will be preparing a SD card for usage with the Raspberry Pi. You will be needing a MicroSD card as the Raspberry Pi 3 only supports this format. The preparation of the SD card is being done on a normal PC so it is wise to purchase one with an adapter fitting a full size SD card slot. There are webshops selling pre-formatted SD cards with the NOOBS installer already present on the card. If you have bought one of these pre-formatted cards you can skip to the Installing Raspbian section. Get a compatible SD card There are a large numbers of SD cards available. The Raspberry Pi foundation advices an 8 GB card leaving space to install different kind of applications and supplies enough space for us to write any log data. When you buy a SD card it is wise to keep your eyes open for the quality of these cards. Buying them from well known and established manufactures often supplies better quality then the counterfeit ones. SD cards are being sold with different class definitions. These classes explain the minimal combined read and write speeds. Class 6 should provide at least 6 MB (Mega Byte) per second and class 10 cards should provide at least 10 MB/s. There is a good online resource available which provides tested results of used SD cards with the Raspberry Pi. If you would need any resource to check for compatible SD cards I would advice you to go to the embedded Linux page at http://elinux.org/RPi_SD_cards. Preparing and formatting the SD card To be able to use the SD card it first needs to be formatted. Most cards are already formatted with the FAT32 file system, which the Raspberry Pi NOOBS installer requires, unless you have bought a large SD card it is possible it is formatted with the exFAT file system. These then should also be formatted as FAT32. To format the SD card we will be using the SD association’s SDformatter utility which you can download from http://elinux.org/RPi_SD_cards as default Operating System supplied formatters are not always providing optimal results. In the below screenshot, the SDformatter for the Mac is shown. This utility is also available for Windows and has the same options. If you are using Linux you can use GParted. Make sure when using GParted you use FAT32 as the formatting option. As in the screenshot select the Overwrite format option and give the SD card a label. The example shows RPI3JAVA but this can be a personal label of your choice to quickly recognize the card when inserted: Press the Format button to start formatting the SD card. Depending on the size of the SD card this can take some time enabling you to get a cup of coffee. The utility will show a done message in the form of Card Format complete when the formatting is done. You will now have an usable SD card. To be able to use the NOOBS installer you will be needing to follow the following steps: Download the NOOBS installer from https://www.raspberrypi.org/downloads/. Unzip the file with your favorite unzip utility. Most Operating Systems already have one installed. Copy the contents of the unzipped file into the SD card’s root directory so the copy result is shown. When selecting the NOOBS for download do only select the lite version if you do not mind to install Raspbian using the Raspberry Pi’s network connection. Now after we have copied the required files into the SD card we can start installing the Raspbian Operating System. Installing Raspbian To install Raspbian we need to get the Raspberry Pi ready for use. As the Raspberry Pi has no power on and off button the powering of the Raspberry Pi will be done as the last step: At the bottom of the Raspberry Pi on the side you will see a slot to put your MicroSD card. Insert the SD card with the connectors pointing to the board. Next connect the HDMI or the Composite connector and your keyboard and mouse. You won’t be needing a network cable as we will be using the wireless functionality build into the Raspberry Pi. We will now connect the Raspberry Pi with the micro USB cabled power supply. When the Raspberry Pi boots up you will be presented with the installation options of Operating Systems available to be installed. Depending on the download of NOOBS you have done you will be able to see if the Raspbian Operating System is already available on the SD card or it will be installed by downloading it. This is being visualized by showing an SD card image or a network image behind the Operating system name. In the below screenshot you see the NOOBS installer with the Raspbian Image available on the SD card. At the bottom of the installation screen you will find the Language and Keyboard drop down menu’s. Make sure you select the appropriate language and keyboard selection otherwise it will become quite difficult to enter correct characters on  the command line and other tools requiring text input. Select the Raspbian [RECOMMENDED] option and click the Install (i) button to start installing the Operating System: You will be prompted with a popup confirming the installation as it will overwrite any existing installed Operating Systems. As we are using a clean SD card we will not be overwriting any. It is safe to press Yes to start the installation. This installation will take up a couple of minutes, so it is a good time to go for a second cup of coffee. When the installation is done you can press Ok in the popup which appears and the Raspberry Pi will reboot. Because Raspbian is a Linux OS you will see text scrolling by of services which are being started by the OS. hen all services are started the Raspberry Pi will start the default graphical environment called LXDE which is one of the Linux window managers. Configuring Raspbian Now that we have installed Raspbian and have it booting into the graphical environment we can start configuring the Raspberry Pi for our purposes. To be able to configure the Raspberry Pi the graphical has got an utility tool installed which eases up the configuration called Raspberry Pi Configuration. To open this tool use the mouse and click on the Menu button on the top left, navigate to Preferences and press the Raspberry Pi Configuration menu option like shown in the screenshot: When clicked on the Raspberry Pi Configuration tool menu option a popup will appear with the graphical version of the known raspi-config command line tool. In thegraphicalpopup we see 4 tabs explaining different parts of possible configuration options. We first focus on the System tab which allows us to:       Change the Password      Change the Hostname which helps to identify the Raspberry Pi in the network      Change the Boot method to, as we are looking at, To Desktop or the CLI which is the command line interface      And set the Network at Boot option With the system newly installed the default username is pi and the password is set to raspberry. Because these are the default settings it is recommended that we change the password into a new one. Press the Change Password button and enter a newly chosen password twice. One time for setting the password and the second time to make sure we have entered the new password correctly. Press Ok when the password has been entered twice. Try to come up with a password which contains capital letters, numbers and some strange characters as this will make it more difficult to guess. Now after we have set a new password we are going to change the hostname of the Raspberry Pi. With the hostname we are able to identify the device on the network. I have changed the hostname into RASPI3JAVA which helps me to identify this Raspberry Pi to be used for the article. The hostname is used on the Command Line Interface so you will immediately identify this Raspberry Pi when you login. By default the Raspberry Pi boots into the graphical user interface which you are looking at right now. Because a future project will require us to make use of a display with our application we will be choosing to boot into the CLI mode. Click on the radio button which says To CLI. The next time we are rebooting we will be shown the command line interface. Because we will be going to use the integrated WI-FI  connection on this Raspberry Pi we are going to change the Network at Boot option to set it to have it waiting for the network. Tick the box which says Wait for network. We are done with setting some default settings which sets some primary options to help us identify the Raspberry Pi and changed the boot mode. We will now be changing some advanced settings which enables us to make use of the hardware provided by the Raspberry Pi. Click on the Interface tab which will give us a list of the available hardware provided. This list consists of:      Camera: The Official Raspberry Pi Camera interface      SSH: To be able to login in from remote locations      SPI: Serial Peripheral Interface Bus for communicating with hardware      I2C: serial communication bus mostly used between chips      Serial: The serial communication interface      1-Wire: Low data, power supplying bus interface conceptual based on I2C      Remote GPIO A future project we will be working on will require some kind of Camera interface. This project will be able to use both the local attached official Raspberry Pi Camera module as well as a USB connected webcam. If you got the camera module tick Enabled radio box behind Camera. We will be deploying our applications immediately from the editor. This means we need to enable the SSH option. By default this already is so we leave the setting as is. If the SSH option is not enabled tick the radio button Enabled behind the SSH option. For now you can leave the other interfaces disabled as we will only enable them when we need them. As we now have enabled default interfaces we will be going to need, we are going to do some performance tweaking. Click on the Performance tab to open the performance options. We will not be needing to overclock the Raspberry Pi so you can leave this options as it is. Later on in the article we will be interfacing with the Raspberry Pi’s display and do some neat tricks with it. For this we need some amount of memory for the Graphical Processor Unit, the GPU. By default this is set to 64 MB. We will ask for the most amount of memory possible to be assigned to the GPU which is 512 MB. Put 512 behind the GPU Memory option, there is no need to enter the text “MB”. The memory on the Raspberry Pi is shared between the system and the GPU. By having this option set to 512 MB results in only 512 MB available for the system. I can assure you this is more then sufficient. Now that we are done with the system configuration we are making sure we can work with the Raspberry Pi. Click on the Localisation tab to show the options applicable to the location the Raspberry Pi resides. We have the options:      Set Locale Where you set your locale settings      Timezone The time zone you currently at      Keyboard The layout of the keyboard      Wi-Fi  Country The country you will be making the Wi-Fi  connection This article is focused on US-English language with a broad character set. Unless you prefer to continue with your own personal preferences change the following by pressing the Set Locale button:      Language to en (English)      Country to US (USA)      Character Set to UTF-8 Press the OK button to continue. As this needs to build up the Locale settings this can take up about 20 seconds to setup, you will be notified with a small window until this process is finished. The next step is to set the Timezone. This is needed as we want to have time and dates be shown correctly. Click on the Set Timezone button and select your appropriate Area and Location from the drop down menu’s. When done press the OK button. To make sure that the text we enter in any input field is the correct one we  are going to set the layout of our keyboard. There are a lot of layouts available so you need to check yours. The Raspberry Pi is quite helpful in providing any keyboard options. Press the Set Keyboard button to open up a popup showing the keyboard options. Here you are able to select your country and the keyboard layout available for this country. In my case I have to select United States as the Country and the Variant as English (US, with euro on 5). After you have made the selection you can test your keyboard setup in the input field below the Country and Variant selection lists. Press the OK button when you are satisfied with your selection. Unless you are connecting your Raspberry Pi with a wired network connection we are going to setup the country we are going to make the Wi-Fi  connection so we are able to connect remotely to the Raspberry Pi. Press the Set Wi-Fi  Country button to have a the Wi-Fi  Country Code shown which provides us the list of available countries for t. he Wi-Fi  connection. Press the OK button after you have made the selection. We are now done with the minimal Raspberry Pi system configuration. Press OK in the settings window to have all our settings stored and press No in the popup following which says a reboot is needed to have the settings applied as we are not completely done yet. Our final step is to set up the local Wi-Fi chip on the Raspberry Pi. We will now set up the Wi-Fi on the Raspberry Pi. Unless you want your Raspberry Pi connected with a Network cable you can skip this section and head over to the Set fixed IP section: To set up the Wi-Fi  click on the Network icon which is shown on top of the screen between the Bluetooth and Speaker Volume icon. When you click this button The Raspberry Pi will start to scan for available wireless networks. Give it a couple of seconds if your Network does not appear immediately. When you see you network appearing click on itandifyou network is secured you will be asked to supply the credentials to be able to connect to your wireless network. If there are any troubles with connecting to your wireless network without any message log in to your router and change the Wi-Fi channel to a channel lower then channel 11. When you have entered your credentials and pressed the OK button you will see the icon changing from the two network computers to the wireless icon trying to connect to the wireless network. Now that the Raspberry Pi has rebooted we have configured the wireless network to make sure the wireless network will keep it’s connection. As the Raspberry Pi is an embedded device targeting low power consumption the Wi-Fi  connection is possible set to sleep mode after a specific time there is no network usage. To make sure the Wi-Fi  is not going into power sleep mode we will be changing a setting through the command line which will make sure this won’t happen. To open a command line interface we need to open a Terminal. A terminal is a window which will show the command prompt where we are able to provide commands. When you look at the graphical interface you will notice a small computer screen icon on the top in the menu bar. When we hover this icon it shows the text Terminal. Press this icon to open up a terminal. A popup will open with a large blackscreenandshowing the command prompt like shown in the screenshot: Do you notice the hostname we have set earlier? This is the same prompt as we will see when we log in remotely. Now that we have a command line open we need to enter a command to make sure the wireless network will not go to sleep after a period of no network activity. Enter the following in the terminal: sudo iw dev wlan0 set power_save off Press Enter. This command sets the power save mode to off so the wlan0 (wireless device) won’t enter power save mode and stays connected to the network. We are almost done with setting up the Raspberry Pi. To be able to connect to the Raspberry Pi from a remote location we need to know the IP address of the Raspberry Pi. This final configuration step involves setting a fixed IP address into the Raspberry Pi settings. To open the settings for a fixed IP configuration we are going to open up the settings by pressing the wireless network icon with the right mouse button and press the option Wi-Fi  Networks (dhcpcdui) Settings. A popup will appear providing settings we can change. As we will will only change the settings of the Wi-Fi  connection we select interface next to the Configure option. When interface is selected we are able to select the wlan0 option in the drop down menu next to the interface selection. If you have chosen to use a wired instead of the wireless connection you can select the eth0 option next to the interface option. We now have a couple of options available to enter IP address related information. Please refer to the documentation of your router to find out which IP address is available to you which you can use. My advice is to only enter the IP address in the available fields whichleaves the other options automatically configured like in the screenshot below. Notice that the entered IP address is the correct one; this only applies to my configuration which could differ from yours: After you have entered the IP address you can click Apply and Close. It is now time to restart our Raspberry Pi and have it boot to the CLI. While rebooting you will see a lot of text scrolling which shows the services starting and at the end instead of starting the graphical interface we are now shown the text based command line interface as shown in the screenshot: If you want to return to the graphical interface just type in: startx Press Enter and wait a couple of seconds for the graphical user interface appear again. We are now ready to install the Oracle JDK which we will be using to run our Java applications. Summary In this article we have learned how to start with with the Raspberry Pi and how to install Raspbian. Resources for Article: Further resources on this subject: The Raspberry Pi and Raspbian The Raspberry Pi and Raspbian Raspberry Pi Gaming Operating Systems Raspberry Pi Gaming Operating Systems Sending Notifications using Raspberry Pi Zero Sending Notifications using Raspberry Pi Zero
Read more
  • 0
  • 0
  • 5180

article-image-run-and-configure-iot-gateway
Gebin George
26 Apr 2018
9 min read
Save for later

How to run and configure an IoT Gateway

Gebin George
26 Apr 2018
9 min read
What is an IoT gateway? An IoT gateway is the protocol or software that's used to connect Internet of Things servers to the cloud. The IoT Gateway can be run as a standalone application, without any modification. There are different encapsulations of the IoT Gateway already prepared. They are built using the same code, but have different properties and are aimed at different operating systems. In today's tutorial, we will explore how to run and configure the IoT gateway. Since all libraries used are based on .NET Standard, they are portable across platforms and operating systems. The encapsulations are then compiled into .NET Core 2 applications. These are the ones being executed. Since both .NET Standard and .NET Core 2 are portable, the gateway can, therefore, be encapsulated for more operating systems than currently supported. Check out this link for a list of operating systems supported by .NET Core 2. Available encapsulations such as installers or app package bundles are listed in the following table. For each one is listed the start project that can be used if you build the project and want to start or debug the application from the development environment: Platform Executable project Windows console Waher.IoTGateway.Console Windows service Waher.IoTGateway.Svc Universal Windows Platform app Waher.IoTGateway.App The IoT Gateway encapsulations can be downloaded from the GitHub project page: All gateways use the library Waher.IoTGateway, which defines the executing environment of the gateway and interacts with all pluggable modules and services. They also use the Waher.IoTGateway.Resources library, which contains resource files common among all encapsulations. The Waher.IoTGateway library is also available as a NuGet: Running the console version The console version of the IoT Gateway (Waher.IoTGateway.Console) is the simplest encapsulation. It can be run from the command line. It requires some basic configuration to run properly. This configuration can be provided manually (see following sections), or by using the installer. The installer asks the user for some basic information and generates the configuration files necessary to execute the application. The console version is the simplest encapsulation, with a minimum of operating system dependencies. It's the easiest to port to other environments. It's also simple to run from the development environment. When run, it outputs any events directly to the terminal window. If sniffers are enabled, the corresponding communication is also output to the terminal window. This provides a simple means to test and debug encrypted communication: Running the gateway as a Windows service The IoT Gateway can also be run as a Windows service (Waher.IoTGateway.Svc). This requires the application be executed on a Windows operating system. The application is a .NET Core 2 console application that has command-line switches allowing it to be registered and executed in the background as a Windows service. Since it supports a command-line interface, it can be used to run the gateway from the console as well. The following table lists recognized command-line switches: Switch Description -? Shows help information. -console Runs the service as a console application. -install Installs the application as a Window Service in the underlying operating system. -displayname Name Sets a custom display name for the Windows service. The default name if omitted is IoT Gateway Service. -description Desc Sets a custom textual description for the Windows service. The default description if omitted is Windows Service hosting the Waher IoT Gateway. -immediate If the service should be started immediately. -localsystem Installed service will run using the Local System account. -localservice Installed service will run using the Local Service account (default). -networkservice Installed service will run using the Network Service account. -start Mode Sets the default starting mode of the Windows service. The default is Disabled. Available options are StartOnBoot, StartOnSystemStart, AutoStart, StartOnDemand and Disabled -uninstall Uninstalls the application as a Windows service from the operating system.   Running the gateway as an app It is possible to run the IoT Gateway as a Universal Windows Platform (UWP) app (Waher.IoTGateway.App). This allows it to be run on Windows phones or embedded devices such as the Raspberry Pi running Windows 10 IoT Core (16299 and later). It can also be used as a template for creating custom apps based on the IoT Gateway: Configuring the IoT Gateway All application data files are separated from the executable files. Application data files are files that can be potentially changed by the user. Executable files are files potentially changed by installers. For the Console and Service applications, application data files are stored in the IoT Gateway subfolder to the operating system's Program Data folder. Example: C:ProgramDataIoT Gateway. For the UWP app, a link to the program data folder is provided at the top of the window. The application data folder contains files you might have to configure to get it to work as you want. Configuring the XMPP interface All IoT Gateways connect to the XMPP network. This connection is used to provide a secure and interoperable interface to your gateway and its underlying devices. You can also administer the gateway through this XMPP connection. The XMPP connection is defined in different manners, depending on the encapsulation. The app lets the user configure the connection via a dialog window. The credentials are then persisted in the object database. The Console and Service versions of the IoT Gateway let the user define the connection using an xmpp.config file in the application data folder. The following is an example configuration file: <?xml version='1.0' encoding='utf-8'?> <SimpleXmppConfiguration xmlns='http://waher.se/Schema/SimpleXmppConfiguration.xsd'> <Host>waher.se</Host> <Port>5222</Port> <Account>USERNAME</Account> <Password>PASSWORD</Password> <ThingRegistry>waher.se</ThingRegistry> <Provisioning>waher.se</Provisioning> <Events></Events> <Sniffer>true</Sniffer> <TrustServer>false</TrustServer> <AllowCramMD5>true</AllowCramMD5> <AllowDigestMD5>true</AllowDigestMD5> <AllowPlain>false</AllowPlain> <AllowScramSHA1>true</AllowScramSHA1> <AllowEncryption>true</AllowEncryption> <RequestRosterOnStartup>true</RequestRosterOnStartup> </SimpleXmppConfiguration> The following is a short recapture: Element Type Description Host String Host name of the XMPP broker to use. Port 1-65535 Port number to connect to. Account String Name of XMPP account. Password String Password to use (or password hash). ThingRegistry String Thing registry to use, or empty if not. Provisioning String Provisioning server to use, or empty if not. Events String Event long to use, or empty if not. Sniffer Boolean If network communication is to be sniffed or not. TrustServer Boolean If the XMPP broker is to be trusted. AllowCramMD5 Boolean If the CRAM-MD5 authentication mechanism is allowed. AllowDigestMD5 Boolean If the DIGEST-MD5 authentication mechanism is allowed. AllowPlain Boolean If the PLAIN authentication mechanism is allowed. AllowScramSHA1 Boolean If the SCRAM-SHA-1 authentication mechanism is allowed. AllowEncryption Boolean If encryption is allowed. RequestRosterOnStartup Boolean If the roster is required, it should be requested on start up. Securing the password Instead of writing the password in clear text in the configuration file, it is recommended that the password hash is used instead of the authentication mechanism supports hashes. When the installer sets up the gateway, it authenticates the credentials during startup and writes the hash value in the file instead. When the hash value is used, the mechanism used to create the hash must be written as well. In the following example, new-line characters are added for readability: <Password type="SCRAM-SHA-1"> rAeAYLvAa6QoP8QWyTGRLgKO/J4= </Password> Setting basic properties of the gateway The basic properties of the IoT Gateway are defined in the Gateway.config file in the program data folder. For example: <?xml version="1.0" encoding="utf-8" ?> <GatewayConfiguration xmlns="http://waher.se/Schema/GatewayConfiguration.xsd"> <Domain>example.com</Domain> <Certificate configFileName="Certificate.config"/> <XmppClient configFileName="xmpp.config"/> <DefaultPage>/Index.md</DefaultPage> <Database folder="Data" defaultCollectionName="Default" blockSize="8192" blocksInCache="10000" blobBlockSize="8192" timeoutMs="10000" encrypted="true"/> <Ports> <Port protocol="HTTP">80</Port> <Port protocol="HTTP">8080</Port> <Port protocol="HTTP">8081</Port> <Port protocol="HTTP">8082</Port> <Port protocol="HTTPS">443</Port> <Port protocol="HTTPS">8088</Port> <Port protocol="XMPP.C2S">5222</Port> <Port protocol="XMPP.S2S">5269</Port> <Port protocol="SOCKS5">1080</Port> </Ports> <FileFolders> <FileFolder webFolder="/Folder1" folderPath="ServerPath1"/> <FileFolder webFolder="/Folder2" folderPath="ServerPath2"/> <FileFolder webFolder="/Folder3" folderPath="ServerPath3"/> </FileFolders> </GatewayConfiguration> Element Type Description Domain String The name of the domain, if any, pointing to the machine running the IoT Gateway. Certificate String The configuration file name specifying details about the certificate to use. XmppClient String The configuration file name specifying details about the XMPP connection. DefaultPage String Relative URL to the page shown if no web page is specified when browsing the IoT Gateway. Database String How the local object database is configured. Typically, these settings do not need to be changed. All you need to know is that you can persist and search for your objects using the static Database defined in Waher.Persistence. Ports Port Which port numbers to use for different protocols supported by the IoT Gateway. FileFolders FileFolder Contains definitions of virtual web folders. Providing a certificate Different protocols (such as HTTPS) require a certificate to allow callers to validate the domain name claim. Such a certificate can be defined by providing a Certificate.config file in the application data folder and then restarting the gateway. If providing such a file, different from the default file, it will be loaded and processed, and then deleted. The information, together with the certificate, will be moved to the relative safety of the object database. For example: <?xml version="1.0" encoding="utf-8" ?> <CertificateConfiguration xmlns="http://waher.se/Schema/CertificateConfiguration.xsd"> <FileName>certificate.pfx</FileName> <Password>testexamplecom</Password> </CertificateConfiguration> Element Type Description FileName String Name of certificate file to import. Password String Password needed to access private part of certificate.   This tutorial was taken from Mastering Internet of Things. Read More IoT Forensics: Security in an always connected world where things talk How IoT is going to change tech teams 5 reasons to choose AWS IoT Core for your next IoT project  
Read more
  • 0
  • 0
  • 4870

article-image-programming-linux
Packt
02 Jan 2017
20 min read
Save for later

Programming with Linux

Packt
02 Jan 2017
20 min read
In this article by Edward Snajder, the author of Raspberry Pi Zero Cookbook, we pick up from having our operating system installed and our Raspberry Pi Zero on our home network. We can now dive into some basic Linux commands. You will find knowing these commands useful any time you are working on a Linux machine. In this article, we'll start prepping with some Linux recipes: (For more resources related to this topic, see here.) Navigating a filesystem and viewing and searching the contents of a directory Creating a new file, editing it in an editor, and changing ownership Renaming and copying/moving the file/folder into a new directory Installing and uninstalling a program Navigating a filesystem and viewing and searching the contents of a directory If you aren’t already a Linux or Mac user, getting around the filesystem can seem pretty alien at first. Truly, if you’ve only used Windows Explorer, this is going to seem like a strange, alien process. Once you start getting the hang of things, though, you’ll find that getting around the Linux filesystem is easy and fun. Getting ready The only thing you need to get started is a client connection to your Raspberry Pi Zero. I like to use SSH, but you can certainly connect using the serial connection or a terminal in X Windows. How to do it… If you want to find out where you are in the filesystem, use pwd: pi@rpz14101:~$ pwd /home/pi This tells me I’m in the /home/pi directory, which is the default home directory for the pi user. Generally, every user you create should get a /home/username directory to keep their own files in. This can be done automatically with user creation and the adduser command. To look at the contents of the directory you are in, use the ls command: pi@rpz14101:~$ ls Desktop Downloads Pictures python_games share Videos Documents Music Public Scratch Templates To look in another directory, simply specify the directory you want to list (you may need to use sudo depending on where you are looking): pi@rpz14101:~$ sudo ls /opt/ cookbook.share pigpio sonic-pi vc minecraft-pi share testsudo.deleteme Wolfram This is a nice quick summary of what files are in the directory, but you will usually want a little more information about the files and directories. The ls command has a ton of options, all of which can be displayed with ls –help and explained in more detail with man ls. Some of the best ones to know are as follows: -a show all files (regular and hidden) -l show long format (more file information, in columns) -h human readable (turns bytes into MB or GB as appropriate) -t or -tr order in time order, or reverse time order My typical command when I start looking in a directory is this one: ls -ltrh This produces all non-hidden files, with human-readable sizes, in column format, and the newest file at the bottom: pi@rpz14101:~$ ls -ltrh /opt/ total 513M drwxr-xr-x 7 root root 4.0K May 27 04:11 vc drwxr-xr-x 3 root root 4.0K May 27 04:32 Wolfram drwxr-xr-x 3 root root 4.0K May 27 04:34 pigpio drwxr-xr-x 4 root root 4.0K May 27 04:36 minecraft-pi drwxr-xr-x 5 root root 4.0K May 27 04:36 sonic-pi -rw-r--r-- 1 root root 0 Jul 4 13:41 testsudo.deleteme drwxr-xr-x 2 root root 4.0K Jul 9 13:05 share -rwxr-xr-x 1 root root 512M Jul 24 17:53 cookbook.share One last trick: if you need this format but there are a lot of files in the directory you are searching, you will see a ton of text scroll by. Maybe you just need the most recent or largest files? We can do this with a pipe (|) and the tail command. Let’s take a directory with a lot of files, such as /usr/lib/. To list the five most recently modified files, I can pipe ls -ltrh to the tail command: pi@rpz14101:~$ ls -ltrh /usr/lib/ | tail -5 lrwxrwxrwx 1 root root 22 May 27 04:40 libwiringPiDev.so -> libwiringPiDev.so.2.32 drwxr-xr-x 2 root root 4.0K Jun 5 10:38 samba drwxr-xr-x 3 root root 4.0K Jul 4 22:48 pppd drwxr-xr-x 65 root root 60K Jul 24 15:48 arm-linux-gnueabihf drwxr-xr-x 2 root root 4.0K Jul 24 15:48 tmpfiles.d What about the five largest files? Instead of the t in -ltrh, I can use S: pi@rpz14101:~$ ls -lSrh /usr/lib/ | tail -5 -rw-r--r-- 1 root root 2.8M Sep 17 2014 libmozjs185.so.1.0.0 -rw-r--r-- 1 root root 2.8M Sep 30 2014 libqscintilla2.so.11.3.0 -rw-r--r-- 1 root root 2.9M Jun 5 2014 libcmis-0.4.so.4.0.1 -rw-r--r-- 1 root root 3.4M Jun 12 2015 libv8.so.3.14.5 -rw-r--r-- 1 root root 5.1M Aug 18 2014 libmwaw-0.3.so.3.0.1 A little creative piping and you can find exactly the file you are looking for. If not, another great tool for exploring the filesystem is tree. This gives a pseudo-graphical tree that shows how the files are structured in the system. It produces a lot of text, especially if you have it print an entire directory tree. If just looking into directory structures, you can use tree with the -d flag for directories only. The -L flag will reduce how deep you dive into nested directories: pi@rpz14101:~$ tree -d -L 2 /opt/ /opt/ ├── minecraft-pi │ ├── api │ └── data ├── pigpio │ └── cgi ├── share ├── sonic-pi │ ├── app │ ├── bin │ └── etc ├── vc │ ├── bin │ ├── include │ ├── lib │ ├── sbin │ └── src └── Wolfram └── WolframEngine Last, we will look at a couple of searching utilities, find and grep. The find command is a powerful function that finds files in whatever directories you specify. It is great for trying to find that mystery piece of software that installed itself in an odd place or the needle-in-a-haystack file in a directory that contains hundreds of files. For example, if I were to run tree in the /opt/sonic-pi/ directory, it would run on for several seconds, and thousands of files would shoot by. I, however, am only interested in finding files with cowbell in the name. I can use the find command to look for it: pi@rpz14101:~$ find /opt/sonic-pi/ -name *cowbell* /opt/sonic-pi/etc/samples/drum_cowbell.flac When looking for anything with cowbell in the filename, the find command returns the exactly location of anything that matches. There are tons of options for using the find command; start with find –help, and then try man find when you want to get really deep. The grep command can be used in a couple different ways when searching for files, and it is one of those commands you will find yourself using constantly while both loving and hating its awesome power. Let’s say you need to find something inside of a file—grep is the tool for you. It can also find things like find can, but generally, find is more efficient at finding filename patterns than grep is. If I use grep to look for cowbells in my sonic-pi directory, I’ll get a different, and more colorful, output: We don’t see the file with cowbell in the name like we did using find, but we find every file that contains cowbell inside of it. The -r flag tells grep to delve into subdirectories, and -i tells it to ignore cases with cowbells (so Cowbell and cowbell are both found, as shown in the screenshot). As you use Linux more often, both find and grep become regularly used tools for administration and file management. This won’t be the last time you use them! Creating a new file, editing it in an editor, and changing ownership There are a lot of different text editors to use on a Linux system from the command line. The program vi is the Ubuntu default, and the program you will find installed on pretty much any Linux system. Emacs is another popular editor, and lots of Linux users get quite passionate about which one is better. My preference is vim, which is generally known as vi improved. The nano text editor is another one that is commonly installed on Linux distros, and it is one of the most lightweight editors available. Getting ready For this recipe, we will work with vi, since that’s definitely going to be installed on your system. If you want to try out vim, you can install it using this: sudo apt-get vim How to do it… First we will go to our share directory: cd /home/pi/share Then, we will create an empty file using the touch command: touch ch3_touchfile.txt If you use the ls command from the previous directory, you can see that the size of the file is 0. You can also display the contents of the file with the cat command, which will return nothing in this case. The touch command is a great way to test whether you have permissions to create files in a specific directory. You can also create a new file with the editor itself: vi ch3_vifile.txt This will open the vi editor with a blank file named ch3_vifile.txt: Using vi or vim (or Emacs) for the first time is completely different from using something like OpenOffice or Microsoft Word. Vi works in two modes: insert (or edit) and command. Once you learn how to use command mode, vi becomes a very efficient editor for working on scripts in bash or Python. Edit mode, more or less, is the mode where you can type and edit text like a regular WYSIWYG editor. There are books written on becoming a power user of vi, well beyond the scope of this book. Getting a handle on the basics is the best place to start: With the empty file, you can jump into edit mode by pressing the i or a keys. The editor will switch to insert mode, as shown by the -- INSERT -- in the bottom left of the screen. Then you can you start typing in your text: To get out of insert mode, press the Esc key. The :w command will save the file, and the :q command will quit. You can combine them, so :wq saves the file and quits. You can verify that the contents were saved with the cat command: pi@rpz14101:~$ cat ch3_vifile.txt Hello from the Raspberry Pi Zero Cookbook! Let’s take another look at the ls command and some of the information the -l format includes. We will take a look at the files we’ve created so far in this recipe: pi@rpz14101:~$ ls -ltrh *.txt -rw-r--r-- 1 pi pi 43 Jul 25 11:23 ch3_vifile.txt -rw-r--r-- 1 pi pi 0 Jul 25 11:24 ch3_touchfile.txt File Permissions Number of links Owner:Group Size Modification Date File Name -rw-r--r-- 1 pi:pi 43 Jul 25 11:23 ch3_vifile.txt We can see that since we made the files as the pi user, the owner of the file and the group owner are pi. By default, when a new user is created, a group container is created as well, so root has a root group, user rpz has an rpz group, and so on. We can change the ownership settings of a file with the chown command. Be careful, since you can take away your own access, though you can always sudo your way back. The chmod command will change who is allowed to do what with a file. Let’s look at ownership changes and what impact they will have with a few examples: pi@rpz14101:~ $ ls -ltrh *.txt -rw-r--r-- 1 pi pi 0 Jul 25 13:28 ch3_touchfile.txt -rwx------ 1 pi pi 43 Jul 25 13:28 ch3_vifile.txt pi@rpz14101:~ $ cat ch3_vifile.txt Hello from the Raspberry Pi Zero Cookbook! pi@rpz14101:~ $ sudo chown rpz:rpz ch3_vifile.txt pi@rpz14101:~ $ cat ch3_vifile.txt cat: ch3_vifile.txt: Permission denied pi@rpz14101:~ $ sudo cat ch3_vifile.txt Hello from the Raspberry Pi Zero Cookbook! pi@rpz14101:~ $ sudo chown rpz:pi ch3_vifile.txt pi@rpz14101:~ $ cat ch3_vifile.txt cat: ch3_vifile.txt: Permission denied pi@rpz14101:~ $ sudo chmod 750 ch3_vifile.txt pi@rpz14101:~ $ cat ch3_vifile.txt Hello from the Raspberry Pi Zero Cookbook! pi@rpz14101:~ $ sudo chown root:root ch3_vifile.txt pi@rpz14101:~ $ cat ch3_vifile.txt cat: ch3_vifile.txt: Permission denied pi@rpz14101:~ $ sudo chmod 755 ch3_vifile.txt pi@rpz14101:~ $ cat ch3_vifile.txt Hello from the Raspberry Pi Zero Cookbook! The chmod values are documented very well, and with a little practice, you can get your file permissions and ownership set up in a way that is both secure and easy to work with. Renaming and copying/moving the file/folder into a new directory A common activity on any filesystem is the practice of copying and moving files, and even directories, from one place to another. You might do it to make a backup copy of something, or you might decide that the contents should live in a more appropriate location. This recipe will explore how to manipulate files in the Raspbian system. Getting ready If you are still in your terminal from the last recipe, we are going to use the same files from the previous recipe. We should have the ownership back to pi:pi; if not, run the following: sudo chown pi:pi /home/pi/*.txt How to do it… First, let’s make a new directory. We’ll put it under the /home/pi/share/ folder so it is accessible to other computers on your home network. To make a directory, use the mkdir command: pi@rpz14101:~$ mkdir /home/pi/share/ch3 We can look at the new directory with the ls command: pi@rpz14101:~$ ls -ltrh /home/pi/share/ total 4.0K -rw-r--r-- 1 pi pi 0 Jul 24 15:56 helloNetwork.yes drwxr-xr-x 2 pi pi 4.0K Jul 25 13:06 ch3 A great flag to go with the mkdir command is -p. This will allow you to create directories and subdirectories in one command. Without it, if I try to create a subdirectory that doesn’t already exist, I’ll get an error: pi@rpz14101:~$ mkdir /home/pi/share/ch3/nested/folders mkdir: cannot create directory ‘/home/pi/share/ch3/nested/folders’: No such file or directory With the -p flag, it works without a problem: pi@rpz14101:~$ mkdir -p /home/pi/share/ch3/nested/folders The tree command shows the structure of our ch3 directory: pi@rpz14101:~$ tree /home/pi/share /home/pi/share ├── ch3 │ └── nested │ └── folders └── helloNetwork.yes 3 directories, 1 file Now, let’s move our files to our new ch3 directory. The copy and move commands—cp and mv, respectively—are the tools we will use. Copying a file from one place to another is as simple as indicating the file's source and destination. The following command will make a copy of vifile.txt and save it as vifile.txt.copy in the /home/pi/share/ch3/ directory: cp /home/pi/ch3_vifile.txt /home/pi/share/ch3/ch3_vifile.txt.copy We can copy files as well as directories and their contents as long as you have enough disk space. To move or rename a file, we use the mv command. This takes the file given in the source and moves it to the destination provided. As simple as the cp command, let’s move all of our files to the share directory: mv /home/pi/ch3_vifile.txt /home/pi/share/ch3/ch3_vifile.txt.moved mv /home/pi/ch3_touchfile.txt /home/pi/share/ch3/ch3_touchfile.txt If we look at the tree of our share directory, we will see everything nicely organized: pi@rpz14101:~$ tree /home/pi/share/ /home/pi/share/ ├── ch3 │ ├── ch3_touchfile.txt │ ├── ch3_vifile.txt.copy │ ├── ch3_vifile.txt.moved │ └── nested │ └── folders └── helloNetwork.yes 3 directories, 4 files Installing and uninstalling a program We’ve installed a few programs throughout the book so far, but have yet to delve into the apt-get command and the family of software-installation utilities. Now, we will learn how to install and uninstall any program available for Raspbian as well as how to search for new software and run updates. Getting ready Stay in your terminal window, and get ready to install some applications! How to do it… The apt-* commands are a suite of utilities that allow you to do various things with installed packages. To install a package, we use the apt-get tool, and the install command, like this: sudo apt-get install <packagename> Let’s install something cool—how about a Matrix screensaver? It is super easy and works great from the command line. To look for a package, we use the apt-cache search command. apt-cache is another tool in the apt-* family of utilities, and it checks the software database for matches. Running sudo apt-cache search matrix results tons of results! The word "matrix" is a little too popular for us computer and math nerds—we have matrixes everywhere! It would take forever to go through that list to find what we are looking for. Fortunately, we can take advantage of grep, which we touched on in an earlier recipe, to narrow down our results. One of the fun things about using Linux and the command line is the ways you can chain commands to do cool things: pi@rpz14101:~ $ sudo apt-cache search matrix | grep "The Matrix" cmatrix - simulates the display from "The Matrix" wmmatrix - View The Matrix in a Window Maker dock application That’s a bit more manageable! We could also have narrowed the list using this command: sudo apt-cache search “The Matrix” This returns fewer results than before, but a few more than the grep command. Whichever way you find it, we see that the cmatrix package is the one we are looking for. Installing is as simple as running this: pi@rpz14101:~ $ ` Reading package lists... Done Building dependency tree Reading state information... Done Suggested packages: cmatrix-xfont The following NEW packages will be installed: cmatrix 0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded. Need to get 16.2 kB of archives. After this operation, 27.6 kB of additional disk space will be used. Get:1 http://mirrordirector.raspbian.org/raspbian/ jessie/main cmatrix armhf 1.2a-5 [16.2 kB] Fetched 16.2 kB in 1s (15.3 kB/s) Selecting previously unselected package cmatrix. (Reading database ... 121906 files and directories currently installed.) Preparing to unpack .../cmatrix_1.2a-5_armhf.deb ... Unpacking cmatrix (1.2a-5) ... Processing triggers for man-db (2.7.0.2-5) ... Setting up cmatrix (1.2a-5) ... After that, we are ready to go! Channel your inner Neo and run this command: cmatrix -s -b You should be in the Matrix! Try it on your serial and SSH connections, and even in the terminal on VNC: you’ll notice differences in the rendering behavior. There are literally thousands of software packages available to install in the repositories of our awesome open source communities. Pretty much anything you think a computer should be able to do, someone, or a group of people, has worked on a solution and pushed it out to the repositories.  We will be using apt-get a lot throughout this cookbook; it is one of the commands you’ll find yourself using all the time as you get more interested in Raspberry Pis and the Linux operating system. Running sudo apt-get update will check all repositories to see whether there are any version updates available. Here, you can see all of the locations it checks to see whether there is anything new for Raspbian: pi@rpz14101:~ $ sudo apt-get update Get:1 http://archive.raspberrypi.org jessie InRelease [13.2 kB] Get:2 http://mirrordirector.raspbian.org jessie InRelease [14.9 kB] Get:3 http://archive.raspberrypi.org jessie/main armhf Packages [144 kB] Get:4 http://mirrordirector.raspbian.org jessie/main armhf Packages [8,981 kB] Hit http://archive.raspberrypi.org jessie/ui armhf Packages Ign http://archive.raspberrypi.org jessie/main Translation-en_GB Get:5 http://mirrordirector.raspbian.org jessie/contrib armhf Packages [37.5 kB] Ign http://archive.raspberrypi.org jessie/main Translation-en Get:6 http://mirrordirector.raspbian.org jessie/non-free armhf Packages [70.3 kB] Ign http://archive.raspberrypi.org jessie/ui Translation-en_GB Ign http://archive.raspberrypi.org jessie/ui Translation-en Get:7 http://mirrordirector.raspbian.org jessie/rpi armhf Packages [1,356 B] Ign http://mirrordirector.raspbian.org jessie/contrib Translation-en_GB Ign http://mirrordirector.raspbian.org jessie/contrib Translation-en Ign http://mirrordirector.raspbian.org jessie/main Translation-en_GB Ign http://mirrordirector.raspbian.org jessie/main Translation-en Ign http://mirrordirector.raspbian.org jessie/non-free Translation-en_GB Ign http://mirrordirector.raspbian.org jessie/non-free Translation-en Ign http://mirrordirector.raspbian.org jessie/rpi Translation-en_GB Ign http://mirrordirector.raspbian.org jessie/rpi Translation-en Fetched 9,263 kB in 34s (272 kB/s) Reading package lists... Done After updating, apt-get upgrade will look at the versions of everything you have installed and upgrade anything to the latest version if there is one available. Depending on how many updates you have, this can take quite a while: pi@rpz14101:~ $ sudo apt-get upgrade Reading package lists... Done Building dependency tree Reading state information... Done Calculating upgrade... Done The following packages will be upgraded: dpkg-dev gir1.2-gdkpixbuf-2.0 initramfs-tools libavcodec56 libavformat56 libavresample2 libavutil54 libdevmapper-event1.02.1 libdevmapper1.02.1 libdpkg-perl python-picamera python3-picamera raspberrypi-kernel raspberrypi-net-mods ssh tzdata xarchiver 40 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. Need to get 57.0 MB of archives. After this operation, 415 kB of additional disk space will be used. Do you want to continue? [Y/n] y Get:1 http://archive.raspberrypi.org/debian/ jessie/main nodered armhf 0.14.5 [5,578 kB] … Adding 'diversion of /boot/overlays/w1-gpio.dtbo to /usr/share/rpikernelhack/overlays/w1-gpio.dtbo by rpikernelhack' … run-parts: executing /etc/kernel/postrm.d/initramfs-tools 4.4.11-v7+ /boot/kernel7.img Preparing to unpack .../raspberrypi-net-mods_1.2.3_armhf.deb ... Unpacking raspberrypi-net-mods (1.2.3) over (1.2.2) ... Processing triggers for man-db (2.7.0.2-5) ... … Setting up libssl1.0.0:armhf (1.0.1t-1+deb8u2) ... Setting up libxml2:armhf (2.9.1+dfsg1-5+deb8u2) ... … Removing 'diversion of /boot/overlays/w1-gpio-pullup.dtbo to /usr/share/rpikernelhack/overlays/w1-gpio-pullup.dtbo by rpikernelhack' … Setting up raspberrypi-net-mods (1.2.3) ... Modified /etc/network/interfaces detected. Leaving unchanged and writing new file as interfaces.new. Processing triggers for libc-bin (2.19-18+deb8u4) ... Processing triggers for initramfs-tools (0.120+deb8u2) ... You don’t really have to understand the details of what’s going on during the upgrade, and it will let you know if there were any problems at the end (and often what to do to fix them). Regularly updating and upgrading will keep all of your software current with all of the latest bug fixes and security patches. There’s more… You can also add and remove software from the GUI. If you log on to your Pi, either directly to a monitor or over VNC Server (a recipe we covered earlier), you can find the Add / Remove Software option under Menu | Preferences: The PiPackages utility makes it very easy to find software when you only have a general idea of what you are looking for. While you can do the same things with the apt commands, if you are browsing, this is a little easier on the eyes. The utility provides categorizations so you don’t have to scroll through every package. Clicking on a package provides a detailed description: Simply check the box and click on Apply or OK, and the software will be installed. Now you can install software on your Raspberry Pi Zero from the command line or GUI. Summary In this article, we looked at the basic file manipulation functionalities of Linux on a Raspberry Pi. We saw how to navigate the filesystem and create, edit, rename, copy, and move files and folders. We also saw how to change ownership of a file and install and uninstall programs. Resources for Article: Further resources on this subject: Sending Notifications using Raspberry Pi Zero [Article] Raspberry Pi LED Blueprints [Article] Hacking a Raspberry Pi project? Understand electronics first! [Article]
Read more
  • 0
  • 0
  • 4407
Visually different images

article-image-python-driving-hardware
Packt
06 Oct 2016
7 min read
Save for later

Python for Driving Hardware

Packt
06 Oct 2016
7 min read
In this article by Tim Cox, author of the book Raspberry Pi Cookbook for Python Programmers - Second Edition, we will see how to control Raspberry Pi with the help of your own buttons and switches. (For more resources related to this topic, see here.) Responding to a button Many applications using the Raspberry Pi require that actions are activated without a keyboard and screen attached to it. The GPIO pins provide an excellent way for the Raspberry Pi to be controlled by your own buttons and switches without a mouse/keyboard and screen. Getting ready You will need the following equipment: 2 x DuPont female to male patch wires Mini breadboard (170 tie points) or a larger one Push button switch (momentary close) or a wire connection to make/break the circuit Breadboarding wire (solid core) 1k ohm resistor The switches are as seen in the following diagram: The push button switch and other types of switches The switches used in the following examples are single pole single throw (SPST) momentary close push button switches. Single pole (SP) means that there is one set of contacts that makes a connection. In the case of the push switch used here, the legs on each side are connected together with a single pole switch in the middle. A double pole (DP) switch acts just like a single pole switch, except that the two sides are separated electrically, allowing you to switch two separate components on/off at the same time. Single throw (ST) means the switch will make a connection with just one position; the other side will be left open. Double throw (DT) means both positions of the switch will connect to different parts. Momentary close means that the button will close the switch when pressed and automatically open it when released. A latched push button switch will remain closed until it is pressed again. The layout of the button circuit We will use sound in this example, so you will also need speakers or headphones attached to audio socket of the Raspberry Pi. You will need to install a program called flite using the following command, which will let us make the Raspberry Pi talk: sudo apt-get install flite After it has been installed, you can test it with the following command: sudo flite -t "hello I can talk" If it is a little too quiet (or too loud), you can adjust the volume (0-100 percent) using the following command: amixer set PCM 100% How to do it… Create the btntest.py script as follows: #!/usr/bin/python3 #btntest.py import time import os import RPi.GPIO as GPIO #HARDWARE SETUP # GPIO # 2[==X==1=======]26[=======]40 # 1[=============]25[=======]39 #Button Config BTN = 12 def gpio_setup(): #Setup the wiring GPIO.setmode(GPIO.BOARD) #Setup Ports GPIO.setup(BTN,GPIO.IN,pull_up_down=GPIO.PUD_UP) def main(): gpio_setup() count=0 btn_closed = True while True: btn_val = GPIO.input(BTN) if btn_val and btn_closed: print("OPEN") btn_closed=False elif btn_val==False and btn_closed==False: count+=1 print("CLOSE %s" % count) os.system("flite -t '%s'" % count) btn_closed=True time.sleep(0.1) try: main() finally: GPIO.cleanup() print("Closed Everything. END") #End How it works… We set up the GPIO pin as required, but this time as an input, and we also enable the internal pull-up resistor (refer to the Pull-up and pull-down resistor circuits subsection in the There's more… section of this recipe for more information) using the following code: GPIO.setup(BTN,GPIO.IN,pull_up_down=GPIO.PUD_UP) After the GPIO pin is set up, we create a loop that will continuously check the state of BTN using GPIO.input(). If the value returned is false, the pin has been connected to 0V (ground) through the switch, and we will use flite to count out loud for us each time the button is pressed. Since we have called the main function from within a try/finally condition, it will still call GPIO.cleanup() even if we close the program using Ctrl + Z. We use a short delay in the loop; this ensures that any noise from the contacts on the switch is ignored. This is because when we press the button, there isn't always perfect contact as we press or release it, and it may produce several triggers if we press it again too quickly. This is known as software debouncing; we ignore the bounce in the signal here. There's more… The Raspberry Pi GPIO pins must be used with care; voltages used for inputs should be within specific ranges, and any current drawn from them should be minimized using protective resistors. Safe voltages We must ensure that we only connect inputs that are between 0V (Ground) and 3.3V. Some processors use voltages between 0V and 5V, so extra components are required to interface safely with them. Never connect an input or component that uses 5V unless you are certain it is safe, or you will damage the GPIO ports of the Raspberry Pi. Pull-up and pull-down resistor circuits The previous code sets the GPIO pins to use an internal pull-up resistor. Without a pull-up resistor (or pull-down resistor) on the GPIO pin, the voltage is free to float somewhere between 3.3V and 0V, and the actual logical state remains undetermined (sometimes 1 and sometimes 0). Raspberry Pi's internal pull-up resistors are 50k ohm - 65k ohm and the pull-down resistors are 50k ohm - 65k ohm. External pull-up/pull-down resistors are often used in GPIO circuits (as shown in the following diagram), typically using 10k ohm or larger for similar reasons (giving a very small current draw when not active). A pull-up resistor allows a small amount of current to flow through the GPIO pin and will provide a high voltage when the switch isn't pressed. When the switch is pressed, the small current is replaced by the larger one flowing to 0V, so we get a low voltage on the GPIO pin instead. The switch is active low and logic 0 when pressed. It works as shown in the following diagram: A pull-up resistor circuit Pull-down resistors work in the same way, except the switch is active high (the GPIO pin is logic 1 when pressed). It works as shown in the following diagram: A pull-down resistor circuit Protection resistors In addition to the switch, the circuit includes a resistor in series with the switch to protect the GPIO pin as shown in the following diagram: A GPIO protective current-limiting resistor The purpose of the protection resistor is to protect the GPIO pin if it is accidentally set as an output rather than an input. Imagine, for instance, that we have our switch connected between the GPIO and ground. Now the GPIO pin is set as an output and switched on (driving it to 3.3V) as soon as we press the switch; without a resistor present, the GPIO pin will directly be connected to 0V. The GPIO will still try to drive it to 3.3V; this would cause the GPIO pin to burn out (since it would use too much current to drive the pin to the high state). If we use a 1k ohm resistor here, the pin is able to be driven high using an acceptable amount of current (I = V/R = 3.3/1k = 3.3mA). Resources for Article: Further resources on this subject: Raspberry Pi LED Blueprints [article] Raspberry Pi and 1-Wire [article] Learning BeagleBone Python Programming [article]
Read more
  • 0
  • 0
  • 4293

article-image-building-voice-technology-iot-projects
Packt
08 Nov 2016
10 min read
Save for later

Building Voice Technology on IoT Projects

Packt
08 Nov 2016
10 min read
In this article by Agus Kurniawan, authors of Smart Internet of Things Projects, we will explore how to make your IoT board speak something. Various sound and speech modules will be explored as project journey. (For more resources related to this topic, see here.) We explore the following topics Introduce a speech technology Introduce sound sensor and actuator Introduce pattern recognition for speech technology Review speech and sound modules Build your own voice commands for IoT projects Make your IoT board speak Make Raspberry Pi speak Introduce a speech technology Speech is the primary means of communication among people. A speech technology is a technology which is built by speech recognition research. A machine such as a computer can understand what human said even the machine can recognize each speech model so the machine can differentiate each human's speech. A speech technology covers speech-to-text and text-to-speech topics. Some researchers already define several speech model for some languages, for instance, English, German, China, French. A general of speech research topics can be seen in the following figure: To convert speech to text, we should understand about speech recognition. Otherwise, if we want to generate speech sounds from text, we should learn about speech synthesis. This article doesn't cover about speech recognition and speech synthesis in heavy mathematics and statistics approach. I recommend you read textbook related to those topics. In this article, we will learn how to work sound and speech processing on IoT platform environment. Introduce sound sensors and actuators Sound sources can come from human, animal, car, and etc. To process sound data, we should capture the sound source from physical to digital form. This happens if we use sensor devices which capture the physical sound source. A simple sound sensor is microphone. This sensor can record any source via microphone. We use a microphone module which is connected to your IoT board, for instance, Arduino and Raspberry Pi. One of them is Electret Microphone Breakout, https://www.sparkfun.com/products/12758. This is a breakout module which exposes three pin outs: AUD, GND, and VCC. You can see it in the following figure. Furthermore, we can generate sound using an actuator. A simple sound actuator is passive buzzer. This component can generate simple sounds with limited frequency. You can generate sound by sending on signal pin through analog output or PWM pin. Some manufacturers also provide a breakout module for buzzer. Buzzer actuator form is shown in the following figure. Buzzer usually is passive actuator. If you want to work with active sound actuator, you can use a speaker. This component is easy to find on your local or online store. I also found it on Sparkfun, https://www.sparkfun.com/products/11089 which you can see it in the following figure. To get experiences how to work sound sensor/actuator, we build a demo to capture sound source by getting sound intensity. In this demo, I show how to detect a sound intensity level using sound sensor, an Electret microphone. The sound source can come from sounds of voice, claps, door knocks or any sounds loud enough to be picked up by a sensor device. The output of sensor device is analog value so MCU should convert it via a microcontroller's analog-to-digital converter. The following is a list of peripheral for our demo. Arduino board. Resistor 330 Ohm. Electret Microphone Breakout, https://www.sparkfun.com/products/12758. 10 Segment LED Bar Graph - Red, https://www.sparkfun.com/products/9935. You can use any color for LED bar. You can also use Adafruit Electret Microphone Breakout to be attached into Arduino board. You can review it on https://www.adafruit.com/product/1063. To build our demo, you wire those components as follows Connect Electret Microphone AUD pin to Arduino A0 pin Connect Electret Microphone GND pin to Arduino GND pin Connect Electret Microphone VCC pin to Arduino 3.3V pin Connect 10 Segment LED Bar Graph pins to Arduino digital pins: 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 which already connected to resistor 330 Ohm You can see the final wiring of our demo in the following figure: 10 segment led bar graph module is used to represent of sound intensity level. In Arduino we can use analogRead() to read analog input from external sensor. Output of analogRead() returns value 0 - 1023. Total output in voltage is 3.3V because we connect Electret Microphone Breakout with 3.3V on VCC. From this situation, we can set 3.3/10 = 0.33 voltage for each segment led bar. The first segment led bar is connected to Arduino digital pin 3. Now we can implement to build our sketch program to read sound intensity and then convert measurement value into 10 segment led bar graph. To obtain a sound intensity, we try to read sound input from analog input pin. We read it during a certain time, called sample window time, for instance, 250 ms. During that time, we should get the peak value or maximum value of analog input. The peak value will be set as sound intensity value. Let's start to implement our program. Open Arduino IDE and write the following sketch program. // Sample window width in mS (250 mS = 4Hz) const int sampleWindow = 250; unsigned int sound; int led = 13; void setup() { Serial.begin(9600); pinMode(led, OUTPUT); pinMode(3, OUTPUT); pinMode(4, OUTPUT); pinMode(5, OUTPUT); pinMode(6, OUTPUT); pinMode(7, OUTPUT); pinMode(8, OUTPUT); pinMode(9, OUTPUT); pinMode(10, OUTPUT); pinMode(11, OUTPUT); pinMode(12, OUTPUT); } void loop() { unsigned long start= millis(); unsigned int peakToPeak = 0; unsigned int signalMax = 0; unsigned int signalMin = 1024; // collect data for 250 milliseconds while (millis() - start < sampleWindow) { sound = analogRead(0); if (sound < 1024) { if (sound > signalMax) { signalMax = sound; } else if (sound < signalMin) { signalMin = sound; } } } peakToPeak = signalMax - signalMin; double volts = (peakToPeak * 3.3) / 1024; Serial.println(volts); display_bar_led(volts); } void display_bar_led(double volts) { display_bar_led_off(); int index = round(volts/0.33); switch(index){ case 1: digitalWrite(3, HIGH); break; case 2: digitalWrite(3, HIGH); digitalWrite(3, HIGH); break; case 3: digitalWrite(3, HIGH); digitalWrite(4, HIGH); digitalWrite(5, HIGH); break; case 4: digitalWrite(3, HIGH); digitalWrite(4, HIGH); digitalWrite(5, HIGH); digitalWrite(6, HIGH); break; case 5: digitalWrite(3, HIGH); digitalWrite(4, HIGH); digitalWrite(5, HIGH); digitalWrite(6, HIGH); digitalWrite(7, HIGH); break; case 6: digitalWrite(3, HIGH); digitalWrite(4, HIGH); digitalWrite(5, HIGH); digitalWrite(6, HIGH); digitalWrite(7, HIGH); digitalWrite(8, HIGH); break; case 7: digitalWrite(3, HIGH); digitalWrite(4, HIGH); digitalWrite(5, HIGH); digitalWrite(6, HIGH); digitalWrite(7, HIGH); digitalWrite(8, HIGH); digitalWrite(9, HIGH); break; case 8: digitalWrite(3, HIGH); digitalWrite(4, HIGH); digitalWrite(5, HIGH); digitalWrite(6, HIGH); digitalWrite(7, HIGH); digitalWrite(8, HIGH); digitalWrite(9, HIGH); digitalWrite(10, HIGH); break; case 9: digitalWrite(3, HIGH); digitalWrite(4, HIGH); digitalWrite(5, HIGH); digitalWrite(6, HIGH); digitalWrite(7, HIGH); digitalWrite(8, HIGH); digitalWrite(9, HIGH); digitalWrite(10, HIGH); digitalWrite(11, HIGH); break; case 10: digitalWrite(3, HIGH); digitalWrite(4, HIGH); digitalWrite(5, HIGH); digitalWrite(6, HIGH); digitalWrite(7, HIGH); digitalWrite(8, HIGH); digitalWrite(9, HIGH); digitalWrite(10, HIGH); digitalWrite(11, HIGH); digitalWrite(12, HIGH); break; } } void display_bar_led_off() { digitalWrite(3, LOW); digitalWrite(4, LOW); digitalWrite(5, LOW); digitalWrite(6, LOW); digitalWrite(7, LOW); digitalWrite(8, LOW); digitalWrite(9, LOW); digitalWrite(10, LOW); digitalWrite(11, LOW); digitalWrite(12, LOW); } Save this sketch program as ch05_01. Compile and deploy this program into Arduino board. After deployed the program, you can open Serial Plotter tool. You can find this tool from Arduino menu Tools -| Serial Plotter. Set the baud rate as 9600 baud on the Serial Plotter tool. Try to make noise on a sound sensor device. You can see changing values on graphs from Serial Plotter tool. A sample of Serial Plotter can be seen in the following figure: How to work? The idea to obtain a sound intensity is easy. We get a value among sound signal peaks. Firstly, we define a sample width, for instance, 250 ms for 4Hz. // Sample window width in mS (250 mS = 4Hz) const int sampleWindow = 250; unsigned int sound; int led = 13; On the setup() function, we initialize serial port and our 10 segment led bar graph. void setup() { Serial.begin(9600); pinMode(led, OUTPUT); pinMode(3, OUTPUT); pinMode(4, OUTPUT); pinMode(5, OUTPUT); pinMode(6, OUTPUT); pinMode(7, OUTPUT); pinMode(8, OUTPUT); pinMode(9, OUTPUT); pinMode(10, OUTPUT); pinMode(11, OUTPUT); pinMode(12, OUTPUT); } On the loop() function, we perform to calculate a sound intensity related to a sample width. After obtained a peak-to-peak value, we convert it into voltage form. unsigned long start= millis(); unsigned int peakToPeak = 0; unsigned int signalMax = 0; unsigned int signalMin = 1024; // collect data for 250 milliseconds while (millis() - start < sampleWindow) { sound = analogRead(0); if (sound < 1024) { if (sound > signalMax) { signalMax = sound; } else if (sound < signalMin) { signalMin = sound; } } } peakToPeak = signalMax - signalMin; double volts = (peakToPeak * 3.3) / 1024; Then, we show a sound intensity in volt form in serial port and 10 segment led by calling display_bar_led(). Serial.println(volts); display_bar_led(volts); Inside the display_bar_led() function, we turn off all LEDs on 10 segment led bar graph by calling display_bar_led_off() which sends LOW on all LEDs using digitalWrite(). After that, we calculate a range value from volts. This value will be converted as total showing LEDs. display_bar_led_off(); int index = round(volts/0.33); Introduce pattern recognition for speech technology Pattern recognition is one of topic in machine learning and as baseline for speech recognition. In general, we can construct speech recognition system in the following figure: From human speech, we should convert it into digital form, called discrete data. Some signal processing methods are applied to handle pre-processing such as removing noise from data. Now in pattern recognition we do perform speech recognition method. Researchers did some approaches such as computing using Hidden Markov Model (HMM) to identity sound related to word. Performing feature extraction in speech digital data is a part of pattern recognition activities. The output will be used as input in pattern recognition input. The output of pattern recognition can be applied as Speech-to-Text and Speech command on our IoT projects. Reviewing speech and sound modules for IoT devices In this section, we review various speech and sound modules which can be integrated into our MCU board. There are a lot of modules related to speech and sound processing. Each module has unique features which fits with your works. One of speech and sound modules is EasyVR 3 & EasyVR Shield 3 from VeeaR. You can review this module on http://www.veear.eu/introducing-easyvr-3-easyvr-shield-3/. Several languages already have been supported such as English (US), Italian, German, French, Spanish, and Japanese. You can see EasyVR 3 module in the following figure: EasyVR 3 board also is available as a shield for Arduino. If you buy an EasyVR Shield 3, you will obtain EasyVR board and its Arduino shield. You can see the form of EasyVR Shield 3 on the following figure: The second module is Emic 2. It was designed by Parallax in conjunction with Grand Idea Studio, http:// www.grandideastudio.com/, to make voice synthesis a total no-brainer. You can send texts to the module to generate human speech through serial protocol. This module is useful if you want to make boards speak. Further information about this module, you can visit and buy this module on https://www.parallax.com/product/30016. The following is a form of Emic-2 module: Summary We have learned some basic sound and voice processing. We also explore several sound and speech modules to integrate into your IoT project. We built a program to read sound intensity level at the first. Resources for Article: Further resources on this subject: Introducing IoT with Particle's Photon and Electron [article] Web Typography [article] WebRTC in FreeSWITCH [article]
Read more
  • 0
  • 0
  • 4246

article-image-raspberry-pi-led-blueprints
Packt
16 Sep 2015
5 min read
Save for later

Raspberry Pi LED Blueprints

Packt
16 Sep 2015
5 min read
Blinking LEDs is a popular application in the field of embedded development. In Raspberry Pi LED Blueprints by Agus Kurniawan, we are going to design, build, and test LED-based projects using the Raspberry Pi. To Implement real LED-based projects for Raspberry Pi, we need to learn how to interface various LED modules, such as LEDs, 7-segment, 4-digit 7-segment, and dot matrix to Raspberry Pi. We will get hands-on experience by exploring real-time LEDs with this project-based book. (For more resources related to this topic, see here.) Why Raspberry Pi? The Raspberry Pi was designed by the Raspberry Pi Foundation in the UK initially to help schoolkids learn basic computer science knowledge. The Raspberry Pi uses Linux as a basic programming language, and they attempt to come up with their own language that fits this technology better sometime in the future. Although Raspberry Pi is as small as the size of a credit card, it works like a normal computer at a relatively low price. A Raspberry Pi can easily control an LED, which is a simple actuator device that displays lighting. This book will provide you with the ability to control LEDs using Raspberry Pi. What this article covers? This article covers introduction of Raspberry Pi GPIO. In this, we will learn how to use different libraries to access Raspberry Pi GPIO. The step-by-step procedure to install it is also provided along with the Python command. Introducing Raspberry Pi GPIO General-purpose input/output (GPIO) is a generic pin on the Raspberry Pi, which can be used to interact with external devices, for instance, sensor and actuator devices. In general, you can see Raspberry Pi GPIO pinouts in the following figure: To access Raspberry Pi GPIO, we can use several GPIO libraries. If you are working with Python, Raspbian has already installed the RPi.GPIO library to access Raspberry Pi GPIO. You can read more about RPi.GPIO at https://pypi.python.org/pypi/RPi.GPIO. You can verify the RPi.GPIO library from a Python terminal by importing the RPi.GPIO module. If you don’t find this library on Python at runtime or get the error message ImportError: No module named RPi.GPIO, you can install it by compiling from the source code. For instance, if we want to install RPi.GPIO 0.5.11, type the following commands: wget https://pypi.python.org/packages/source/R/RPi.GPIO/RPi.GPIO-0.5.11.tar.gz tar -xvzf RPi.GPIO-0.5.11.tar.gz cd RPi.GPIO-0.5.11/ sudo python setup.py install To install and update through the apt command, your Raspberry Pi must be connected to the Internet. Another way to access Raspberry Pi GPIO is to use WiringPi. It is a library written in C for Raspberry Pi to access GPIO pins. You can read more about WiringPi at http://wiringpi.com/. To install WiringPi, you can type the following commands: sudo apt-get update sudo apt-get install git-core git clone git://git.drogon.net/wiringPi cd wiringPi sudo ./build Please make sure that your Pi network does not block the git protocol for git://git.dragon.net/wiringPi. You can browsed https://git.drogon.net/?p=wiringPi;a=summary for this code. The next step is to install the WiringPi interface for Python, so you can access Raspberry Pi GPIO from the Python program. Type the following commands: sudo apt-get install python-dev python-setuptools git clone https://github.com/Gadgetoid/WiringPi2-Python.git cd WiringPi2-Python sudo python setup.py install When finished, you can verify it by showing GPIO map from the Raspberry Pi board using the following gpio tool: gpio readall You should see the GPIO map from the Raspberry Pi board on the terminal. You can also see values in the wPi column, which will be used in the WirinPi program as GPIO value parameters. In this book, you can find more information about how to use it on the WiringPi library. What you need for this book? We are going to use Raspberry Pi 2 board Model B. To make Raspberry Pi work, we need OS that acts as a bridge between the hardware and the user. There are many OS options that you can use for Raspberry Pi. This book uses Raspbian for the OS platform for Raspberry Pi. To deploy Raspbian on Raspberry Pi 2 Model B, we need microSD card of at least 4 GB size. Who this book is written for? This book is for those who want to learn how to build Raspberry Pi projects using LEDs, 7-segment, 4-digit 7-segment, and dot matrix modules. You will also learn to implement those modules in real applications, including interfacing with wireless modules and the Android mobile app. However, you don't need to have any previous experience with the Raspberry Pi or Android platforms. Summary In this article, we learned different techniques to install Raspberry Pi GPIO. Read Raspberry Pi LED Blueprints to start designing and implementing several projects based on LEDs, such as 7-segments, 4-digit 7-segment, and dot matrix displays. Other related titles are: Raspberry Pi Blueprints Raspberry Pi Super Cluster Learning Raspberry Pi Raspberry Pi Robotic Projects Resources for Article: Further resources on this subject: Color and motion finding [article] Basic Image Processing [article] Develop a Digital Clock [article]
Read more
  • 0
  • 0
  • 4209
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at ₹800/month. Cancel anytime
article-image-avoiding-obstacles-using-sensors
Packt
14 Aug 2014
8 min read
Save for later

Avoiding Obstacles Using Sensors

Packt
14 Aug 2014
8 min read
In this article by Richard Grimmett, the author of Arduino Robotic Projects, we'll learn the following topics: How to add sensors to your projects How to add a servo to your sensor (For more resources related to this topic, see here.) An overview of the sensors Before you begin, you'll need to decide which sensors to use. You require basic sensors that will return information about the distance to an object, and there are two choices—sonar and infrared. Let's look at each. Sonar sensors The sonar sensor uses ultrasonic sound to calculate the distance to an object. The sensor consists of a transmitter and receiver. The transmitter creates a sound wave that travels out from the sensor, as illustrated in the following diagram: The device sends out a sound wave 10 times a second. If an object is in the path of these waves, the waves reflect off the object. This then returns sound waves to the sensor. The sensor measures the returning sound waves. It uses the time difference between when the sound wave was sent out and when it returns to measure the distance to the object. Infrared sensors Another type of sensor is a sensor that uses infrared (IR) signals to detect distance. An IR sensor also uses both a transmitter and a receiver. The transmitter transmits a narrow beam of light and the sensor receives this beam of light. The difference in transit ends up as an angle measurement at the sensor, as shown in the following diagram: The different angles give you an indication of the distance to the object. Unfortunately, the relationship between the output of the sensor and the distance is not linear, so you'll need to do some calibration to predict the actual distance and its relationship to the output of the sensor. Connecting a sonar sensor to Arduino Here is an image of a sonar sensor, HC-SR04, which works well with Arduino: These sonar sensors are available at most places that sell Arduino products, including amazon.com. In order to connect this sonar sensor to your Arduino, you'll need some of those female-to-male jumper cables. You'll notice that there are four pins to connect the sonar sensor. Two of these supply the voltage and current to the sensor. One pin, the Trig pin, triggers the sensor to send out a sound wave. The Echo pin then senses the return from the echo. To access the sensor with Arduino, make the following connections using the male-to-female jumper wires: Arduino pin Sensor pin 5V Vcc GND GND 12 Trig 11 Echo Accessing the sonar sensor from the Arduino IDE Now that the HW is connected, you'll want to download a library that supports this sensor. One of the better libraries for this sensor is available at https://code.google.com/p/arduino-new-ping/. Download the NewPing library and then open the Arduino IDE. You can include the library in the IDE by navigating to Sketch | Import Library | Add Library | Downloads and selecting the NewPing ZIP file. Once you have the library installed, you can access the example program by navigating to File | Examples | NewPing | NewPingExample as shown in the following screenshot: You will then see the following code in the IDE: Now, upload the code to Arduino and open a serial terminal by navigating to Tools | Serial Monitor in the IDE. Initially, you will see characters that make no sense; you need to change the serial port baud rate to 115200 baud by selecting this field in the lower-right corner of Serial Monitor, as shown in the following screenshot: Now, you should begin to see results that make sense. If you place your hand in front of the sensor and then move it, you should see the distance results change, as shown in the following screenshot: You can now measure the distance to an object using your sonar sensor. Connecting an IR sensor to Arduino One popular choice is the Sharp series of IR sensors. Here is an image of one of the models, Sharp 2Y0A02, which is a unit that provides sensing to a distance of 150 cm: To connect this unit, you'll need to connect the three pins that are available on the bottom of the sensor. Here is the connection list: Arduino pin Sensor pin 5V Vcc GND GND A3 Vo Unfortunately, there are no labels on the unit, but there is a data sheet that you can download from www.phidgets.com/documentation/Phidgets/3522_0_Datasheet.pdf. The following image shows the pins you'll need to connect: One of the challenges of making this connection is that the female-to-male connection jumpers are too big to connect directly to the sensor. You'll want to order the three-wire cable with connectors with the sensor, and then you can make the connections between this cable and your Arduino device using the male-to-male jumper wires. Once the pins are connected, you are ready to access the sensor via the Arduino IDE. Accessing the IR sensor from the Arduino IDE Now, bring up the Arduino IDE. Here is a simple sketch that provides access to the sensor and returns the distance to the object via the serial link: The sketch is quite simple. The three global variables at the top set the input pin to A3 and provide a storage location for the input value and distance. The setup() function simply sets the serial port baud rate to 9600 and prints out a single line to the serial port. In the loop() function, you first get the value from the A3 input port. The next step is to convert it to a distance based on the voltage. To do this, you need to use the voltage to distance chart for the device; in this case, it is similar to the following diagram: There are two parts to the curve. The first is the distance up to about 15 centimeters and then the distance from 15 centimeters to 150 centimeters. This simple example ignores distances closer than 15 centimeters, and models the distance from 15 centimeters and out as a decaying exponential with the following form: Thanks to teaching.ericforman.com/how-to-make-a-sharp-ir-sensor-linear/, the values that work quite well for a cm conversion in distance are 30431 for the constant and -1.169 as the exponential for this curve. If you open the Serial Monitor tab and place an object in front of the sensor, you'll see the readings for the distance to the object, as shown in the following screenshot: By the way, when you place the object closer than 15 cm, you should begin to see distances that seem much larger than should be indicated. This is due to the voltage to distance curve at these much shorter distances. If you truly need very short distances, you'll need a much more complex calculation. Creating a scanning sensor platform While knowing the distance in front of your robotic project is normally important, you might want to know other distances around the robot as well. One solution is to hook up multiple sensors, which is quite simple. However, there is another solution that may be a bit more cost effective. To create a scanning sensor of this type, take a sensor of your choice (in this case, I'll use the IR sensor) and mount it on a servo. I like to use a servo L bracket for this, which is mounted on the servo Pas follows: You'll need to connect both the IR sensor as well as the servo to Arduino. Now, you will need some Arduino code that will move the servo and also take the sensor readings. The following screenshot illustrates the code: The preceding code simply moves the servo to an angle and then prints out the distance value reported by the IR sensor. The specific statements that may be of interest are as follows: servo.attach(servoPin);: This statement attaches the servo control to the pin defined servo.write(angle);: This statement sends the servo to this angle inValue = analogRead(inputPin);: This statement reads the analog input value from this pin distance = 30431 * pow(inValue, -1.169);: This statement translates the reading to distance in centimeters If you upload the sketch, open Serial Monitor , and enter different angle values, the servo should move and you should see something like the following screenshot: Summary Now that you know how to use sensors to understand the environment, you can create even more complex programs that will sense these barriers and then change the direction of your robot to avoid them or collide with them. You learned how to find distance using sonar sensors and how to connect them to Arduino. You also learned about IR sensors and how they can be used with Arduino. Resources for Article: Further resources on this subject: Clusters, Parallel Computing, and Raspberry Pi – A Brief Background [article] Using PVR with Raspbmc [article] Home Security by BeagleBone [article]
Read more
  • 0
  • 0
  • 4046

article-image-build-actuator-application-with-raspberry-pi-3
Gebin George
28 Jun 2018
10 min read
Save for later

Build an Actuator app for controlling Illumination with Raspberry Pi 3

Gebin George
28 Jun 2018
10 min read
In this article, we will look at how to build an actuator application for controlling illuminations. This article is an excerpt from the book, Mastering Internet of Things, written by Peter Waher. This book will help you design and implement IoT solutions with single board computers. Preparing our project Let's create a new Universal Windows Platform application project. This time, we'll call it Actuator. We can also use the Raspberry Pi 3, even though we will only use the relay in this project. To make the persistence of application states even easier, we'll also include the latest version of the NuGet package Waher.Runtime.Settings in the project. It uses the underlying object database defined by Waher.Persistence to persist application settings. Defining control parameters Actuators come in all sorts, types, and sizes, from the very complex to the very simple. While it would be possible to create a proprietary format that configures the actuator in a bulk operation, such a method is doomed to fail if you aim for any type of interoperable communication. Since the internet is based on interoperability as a core principle, we should consider this from the start, during the design phase. Interoperability means devices can learn to operate together, even if they are from different manufacturers. To achieve this, devices must be able to describe what they can do, in a way that each participant understands. To be able to do this, we need a way to break down (divide and conquer) a complex actuator into parts that are easily described and understood. One way is to see an actuator as a collection of control parameters. Each control parameter is a named parameter with a simple and recognizable data type. (In the same way, we can see a sensor as a collection of sensor data fields.): For our example, we will only need one control parameter: A Boolean control parameter controlling the state of our relay. We'll just call it Output, for simplicity. Understanding relays Relays, simply put, are electric switches that we can control using a small output signal. They're perfect for small controllers, like Raspberry Pi, to switch other circuits with higher voltages on and off. The simplest example is to use a relay to switch a lamp on and off. We can't light the lamp using the voltage available to us in Raspberry Pi, but we can use a relay as a switch to control the lamp. The principal part of a normal relay is a coil. When electricity runs through it, it magnetizes an iron core, which in turn moves a lever from the Normally Closed (NC) connector to the Normally Open (NO) connector. When electricity is cut, a spring returns the lever from the NO connector to the NC connector. This movement of the lever from one connector to the other causes a characteristic clicking sound. This tells you that the relay works. The lever in turn is connected to the Common Ground (COM) connector. The following figure illustrates how a simple relay is constructed. We control the flow of the current through the coil (L1) using our output SIGNAL (D1 in our case). Internally, in the relay, a resistor (R1) is placed before the base pin of the transistor (T1), to adapt the signal voltage to an appropriate level. When we connect or cut the current through the coil, it will induce a reverse current. This may be harmful for the transistor when the current is being cut. For that reason, a fly-back diode (D1) is added, allowing excess current to be fed back, avoiding harm to the transistor: Connecting our lamp Now that we know how a relay works, it's relatively easy to connect our lamp to it. Since we want the lamp to be illuminated when we turn the relay on (set D1to HIGH), we will use the NO and COM connectors, and let the NC connector be. If the lamp has a normal two-wire AC cable, we can insert the relay into the AC circuit by simply cutting one of the wires, inserting one end into the NO connector and the other into the COM connector, as is illustrated in the following figure: Be sure to follow appropriate safety regulations when working with electricity. Connecting an LED An alternative to working with the alternating current (AC) is to use a low-power direct current (DC) source and an LED to simulate a lamp. You can connect the COM connector to a resistor and an LED, and then to ground (GND) on one end, and the NO directly to the 5V or 3.3V source on the Raspberry Pi on the other end. The size of the resistor is determined by how much current the LED needs to light up, and the voltage source you choose. If the LED needs 20 mA, and you connect it to a 5V source, Ohms Law tells us we need an R = U/I = 5V/0.02A = 250 Ω resistor. The following figure illustrates this: Controlling the output The relay is connected to our digital output pin 9 on the Arduino board. As such, controlling it is a simple call to the digitalWrite() method on our arduino object. Since we will need to perform this control action from various locations in code in later chapters, we'll create a method for it: internal async Task SetOutput(bool On, string Actor) { if (this.arduino != null) { this.arduino.digitalWrite(9, On ? PinState.HIGH : PinState.LOW); The first parameter simply states the new value of the control parameter. We'll add a second parameter that describes who is making the requested change. This will come in handy later, when we allow online users to change control parameters. Persisting control parameter states If the device reboots for some reason, for instance after a power outage, it's normally desirable that it returns to the state it was in before it shut down. For this, we need to persist the output value. We can use the object database defined in Waher.Persistence and Waher.Persistence.Files for this. But for simple control states, we don't need to create our own data-bearing classes. That has already been done by Waher.Runtime.Settings. To use it, we first include the NuGet, as described earlier. We must also include its assembly when we initialize the runtime inventory, which is used by the object database: Types.Initialize( typeof(FilesProvider).GetTypeInfo().Assembly, typeof(App).GetTypeInfo().Assembly, typeof(RuntimeSettings).GetTypeInfo().Assembly); Depending on the build version selected when creating your UWP application, different versions of .NET Standard will be supported. Build 10586 for instance, only supports .NET Standard up to v1.4. Build 16299, however, supports .NET Standard up to v2.0. The Waher.Runtime.Inventory.Loader library, available as a NuGet package, provides the capability to loop through existing assemblies in a simple manner, but it requires support for .NET Standard 1.5. You can call its TypesLoader.Initialize() method to initialize Waher.Runtime.Inventory with all assemblies available in the runtime. It also dynamically loads all permitted assemblies available in the application folder that have not been loaded. Saving the current control state is then simply a matter of calling the Set() or SetAsync() methods on the static RuntimeSettings class, defined in the Waher.Runtime.Settings namespace: await RuntimeSettings.SetAsync("Actuator.Output", On); During the initialization of the device, we then call the Get() or GetAsync() methods to get the last value, if it exists. If it does not exist, a default value we define is returned: bool LastOn = await RuntimeSettings.GetAsync("Actuator.Output", false); this.arduino.digitalWrite(1, LastOn ? PinState.HIGH : PinState.LOW); Logging important control events In distributed IoT control applications, it's vitally important to make sure unauthorized access to the system is avoided. While we will dive deeper into this subject in later chapters, one important tool we can start using it to log everything of a security interest in the event log. We can decide what to do with the event log later, whether we want to analyze or store it locally or distribute it in the network for analysis somewhere else. But unless we start logging events of security interest directly when we develop, we risk forgetting logging certain events later. So, let's log an event every time the output is set: Log.Informational("Setting Control Parameter.", string.Empty, Actor ?? "Windows user", new KeyValuePair<string, object>("Output", On)); If the Actor parameter is null, we assume the control parameter has been set from the Windows GUI. We use this fact, to update the window if the change has been requested from somewhere else: if (Actor != null) await MainPage.Instance.OutputSet(On); Using Raspberry Pi GPIO pins directly The Raspberry Pi can also perform input and output without an Arduino board. But the General-Purpose Input/Output (GPIO) pins available only supports digital input and output. Since the relay module is controlled through a digital output, we can connect it directly to the Raspberry Pi, if we want. That way, we don't need the Arduino board. (We wouldn't be able to test-run the application on the local machine either, though.) Checking whether GPIO is available GPIO pins are accessed through the GpioController class defined in the Windows.Devices.Gpio namespace. First, we must check that GPIO is available on the machine. We do this by getting the default controller, and checking whether it's available: gpio = GpioController.GetDefault(); if (gpio != null) { ... } else Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString()); Initializing the GPIO output pin Once we have access to the controller, we can try to open exclusive access to the GPIO pin we've connected the relay to: if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) && Status == GpioOpenStatus.PinOpened) { ... } else Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString()); Through the GpioPin object gpioPin, we can now control the pin. The first step is to set the operating mode for the pin. This is done by calling the SetDriveMode() method. There are many different modes a pin can be set to, not all necessarily supported by the underlying firmware and hardware. To check that a mode is supported, call the IsDriveModeSupported() method first: if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output)) { This.gpioPin.SetDriveMode(GpioPinDriveMode.Output); ... } else Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString()); There are various output modes available: Output, OutputOpenDrain, OutputOpenDrainPullUp, OutputOpenSource, and OutputOpenSourcePullDown. The code documentation for each flag describes the particulars of each option. Setting the GPIO pin output To set the actual output value, we call the Write() method on the pin object: bool LastOn = await RuntimeSettings.GetAsync("Actuator.Output", false); this.gpioPin.Write(LastOn ? GpioPinValue.High : GpioPinValue.Low); We need to make a similar change in the SetOutput() method. The Actuator project in the MIOT repository uses the Arduino use case by default. The GPIO code is also available through conditional compiling. It is activated by uncommenting the GPIO switch definition on the first row of the App.xaml.cs file. You can also perform Digital Input using principles similar to the preceding ones, with some differences. First, you select an input drive mode: Input, InputPullUp or InputPullDown. You then use the Read() method to read the current state of the pin. You can also use the ValueChanged event to get a notification whenever the input pin changes value. We saw how to create a simple actuator app for the Raspberry Pi using C#. If you found our post useful, do check out this title Mastering Internet of Things, to build complex projects using motions detectors, controllers, sensors, and Raspberry Pi 3. Should you go with Arduino Uno or Raspberry Pi 3 for your next IoT project? Build your first Raspberry Pi project Meet the Coolest Raspberry Pi Family Member: Raspberry Pi Zero W Wireless
Read more
  • 0
  • 0
  • 3939

article-image-introducing-iot-particles-photon-and-electron
Packt
07 Sep 2016
14 min read
Save for later

Introducing IoT with Particle's Photon and Electron

Packt
07 Sep 2016
14 min read
In this article by Rashid Khan, Kajari Ghoshdastidar, and Ajith Vasudevan, authors of the book Learning IoT with Particle Photon and Electron, we will have a brief walkthrough of the evolution of Internet of Things (IoT) followed by an overview of the basics of IoT-related software and hardware, which every IoT enthusiast should know. The discussion then moves on to introduce Particle, an IoT company (https://www.particle.io/), followed by a description of Particle's popular IoT products—Core, Photon and Electron. This article will cover following topics: Evolution of IoT Hardware and software in the IoT ecosystem Market survey of IoT development boards and cloud services What is Particle? Summary (For more resources related to this topic, see here.) Evolution of IoT It is not very clear exactly who coined the term IoT. Kevin Ashton (https://en.wikipedia.org/wiki/Kevin_Ashton) supposedly coined the phrase IoT while working for Procter & Gamble (P&G) in 1999. Kevin was then working on an RFID (https://en.wikipedia.org/wiki/Radio-frequency_identification) initiative by P&G, and proposed taking the system online to the Internet. In 2005, UN's International Telecommunications Union (ITU) - http://www.itu.int/, published its first report on IoT. In 2008, the global non-profit organization IPSO Alliance (http://www.ipso-alliance.org/) was launched to serve the various communities seeking to establish IoT by providing coordinated marketing efforts available to the general public. IPSO currently has more than 50 member companies including Google, Cisco, Intel, Texas Instruments, Bosch, Atmel. In 2012, IoT Consortium (IoTC) - http://iofthings.org/, was founded to educate technology firms, retailers, insurance companies, marketers, media companies, and the wider business community about the value of IoT. IoTC has more than 60 member companies in the area of hardware, software, and analytics, a few of them being Logitech, Node, and SigFox. A 2014 Forbes article by Gil Press mentions: "Gartner estimates that IoT product and service suppliers will generate incremental revenue exceeding $300 billion in 2020. IDC forecasts that the worldwide market for IoT solutions will grow from $1.9 trillion in 2013 to $7.1 trillion in 2020". Why IoT has become a household word now IoT has, in recent years, become quite popular and an everyday phenomenon primarily due to IoT-related hardware, software, accessories, sensors, and the Internet connection becoming very affordable and user friendly. An explosion in the availability of free Integrated Development Environments (IDEs) and Software Development Kits (SDKs) have made programming and deployment of IoT really simple and easy. Thus, IoT enthusiasts range from school kids, hobbyists, and non-programmers to embedded software engineers specialized in this area. Hardware and software in the IoT ecosystem Advancement in technology and affordability has made acquisition and usage of IoT devices very simple. However, in order to decide which IoT package (boards, accessories, sensors, software) to choose for a particular application, and actually building projects, it is essential to have knowledge of IoT terminology, hardware, and software. In this section, we will introduce the reader to the essential terminology used when dealing with IoT. This will also help the reader understand and appreciate the features of the Particle IoT products—Core, Photon, and Electron. Essential terminology Let's learn about a few terms that we're going to be hearing all throughout this article, and whenever we work with IoT hardware and software components: Term Definition IoT Development Board A development board is essentially a programmable circuit board which wraps an IoT device. The IoT device's processor/microcontroller, memory, communications ports, input-output pins, sensors, Wi-Fi module, and so on are exposed by the development board, in a convenient way, to the user. A board manufacturer usually provides an IDE with it to write and deploy code to the physical board. A development board with the IDE enables rapid prototyping of IoT projects. Microcontroller A microcontroller is a highly compact single Integrated Circuit (IC) with a processor and limited Random Access Memory (RAM) and Read Only Memory (ROM) embedded in it with programmable peripherals. Microcontrollers are "computer on a single chip". Because of its limited memory and architecture constraints, usually, only one specific program is deployable and runnable on a microcontroller at one time. Preprogrammed microcontrollers are used in electrical machinery such as washing machines, dish-washers, microwave, and so on. Microprocessor A microprocessor is a single integrated chip which in itself is a Central Processing Unit (CPU). The microprocessor has separate RAM and ROM modules, and digital inputs and outputs. The Microprocessor CPU is usually more powerful than that of a microcontroller, and there is provision to add larger amounts of memory externally. This makes microprocessors suitable for general-purpose programming, and are used in desktop computers, Laptops, and the like. Flash Memory Flash memory is an electronic non-volatile storage device, for example, USB pen-drives, memory cards, and so on. Data in Flash memory can be erased and rewritten. Unlike RAM, access speed is lower for flash memories, and also unlike RAM, the data stored in flash memory is not erased when power is switched off. Flash memories are generally used as reusable extra storage. RTOS RTOS as the name suggests, RTOS responds to events in real time. This means, as soon as an event occurs, a response is guaranteed within an acceptable and calculable amount of time. RTOS can be hard, firm, or soft depending on the amount of flexibility allowed in missing a task deadline. RTOS is essential in embedded systems, where real-time response is necessary. M2M Machine-to-Machine (M2M) communication encompasses communication between two or more machines (devices, computers, sensors, and so on) over a network (wireless/wired). Basically, a variant of IoT, where things are machines. Cloud Technology Cloud refers to computing resources available for use over a network (usually, the Internet). An end user can use such a resource on demand without having to install anything more than a lightweight client in the local machine. The major resources relevant to IoT include data storage, data analytics, data streaming, and communication with other devices. mBaaS Mobile Backend as a Service (mBaaS) is a infrastructure that provides cloud storage, data streaming, push notifications, and other related services for mobile application developers (web, native, IoT app development). The services are exposed via web-based APIs. BaaS is usually provided as a pay-per-use service. GPIO General Purpose Input Output (GPIO), these are electrical terminals or 'pins' exposed from ICs and IoT devices/boards that can be used to either send a signal to the device from the outside (input mode), or get a signal out from the inside of the device (output mode). Input or Output mode can be configured by the user at runtime. Module Unit of electronics, sometimes a single IC and at other times a group of components that may include ICs, providing a logical function to the device/board. For example, a Wi-Fi module provides Wi-Fi functionality to a board. Other examples are Bluetooth, Ethernet, USB, and so on, Port An electrical or Radio-Frequency-based interface available on a board through which external components can communicate with the board. For example, HDMI, USB, Ethernet, 3.5mm jack, UART (https://en.wikipedia.org/wiki/Universal_asynchronous_receiver/transmitter). Table 1: Terminology Network Protocols Connected smart devices need to communicate with each other, and exchange large volumes of messages between themselves and the cloud. To ensure near real-time response, smart bandwidth usage, and energy savings on the resource-constrained IoT devices, new protocols have been added to the traditional seven-layer network model (OSI model: https://en.wikipedia.org/wiki/OSI_model). The following table shows the major OSI network protocols and the IoT network protocols suitable for various smart, connected devices. Layer Examples of Traditional Network Protocols (OSI) Examples of IoT Network Protocols Application, Presentation, Session HTTP, FTP, SMTP, TLS, RPC, JSON, CSS, GIF, XML CoAP, MQTT, DDS, M2M service layer Transport TCP, UDP UDP, DTLS Network ICMP, IPsec, IPv4, IPv6 6LoWPAN, RPL (Zigbee) Data Link IEEE 802.2, L2TP, LLDP, MAC, PPP IEEE 802.15.4, BLE4.0, RFID, NFC, Cellular Physical DSL, Ethernet physical layer, RS-232, any physical transmission medium (for example, Cables) Wires, Sensor drivers to read from sensor devices Table 2: Layerwise Network Protocols – OSI vs IoT Market survey of IoT development boards and cloud services Here we list some of the most popular IoT boards and cloud services, available in the market at the time of writing this article, with some of their important specifications and features. These tables should help the reader get an idea as to where Particle products fit in on the IoT map. IoT development boards The next table lists the main specifications of popular IoT boards. These specs are the basic details one has to consider while selecting a board—its specifications in terms of processor and speed, memory, available communication modules and ports, and IO Pins. Also, while selecting a board, one has to analyze and match the project's requirements with the available boards, so that the right board is selected for the application in terms of fitment and performance. Board Name Microcontroller Microprocessor Memory Modules Ports IO Pins Raspberry Pi 1/2/3 Broadcom SoC BCM2835/6/7 Single/Quad-core ARM 11/Cortex-A7/A53 CPU, VideoCore IV GPU 256MB/512MB/1 GB RAM Ethernet, Wi-Fi, Serial UART, I2C HDMI, USB, Ethernet (RJ45), GPIO 26/40/40 Arduino Mini ATmega328 NA 32 KB Flash 2 KB SRAM NA NA 14 Arduino Yun ATmega32u4 Atheros AR9331 32 KB Flash 2.5 KB SRAM, 16 MB Flash, 64 MB RAM Wi-Fi, Ethernet USB, Ethernet (RJ45) 20 Intel Edison MCU at 100 MHz ( Intel Atom Soc) Dual-core CPU at 500 MHz (Intel Atom Soc) 4 GB Flash, 1 GB RAM Wi-Fi, Bluetooth 4.0 USB, UART, SPI, GPIO 28 Libelium Waspmote ATmega1281 NA 128 KB Flash, 8 KB SRAM Temp, Humidity, Light Sensors, (optional) GPS UART, I2C, SPI, USB 19 NodeMCU ESP8266 ESP 8266 SoC ESP-12 module 4 MB Flash Wi-Fi, Serial UART, ADC UART, GPIO, SPI 14 BeagleBone Black Sitara SoC AM3358/9 AM335x 1 GHz ARM Cortex-A8 512 MB RAM, 2/4 GB flash storage Ethernet, Serial UART, ADC, I2C Ethernet (RJ45), HDMI, USB, GPIO 24 CubieBoard ARM Cortex-A8 CPU AllWinner A10 SoC 512 MB/ 1 GB RAM, 4 GB flash memory Ethernet, Serial UART, ADC, I2C Ethernet (RJ45) , USB, SATA 96 Table 3: IoT development Boards Cloud services (PaaS, BaaS, M2M) It is important to know what kind of cloud service we will be dealing with, and whether our board has open standards and allows us to use our own personal service easily, or whether the board-provided service needs some manipulation to use in the current project. Cloud Service Name Salient Features Amazon Web Services (https://aws.amazon.com/) Microsoft Azure (https://azure.microsoft.com/) Cloud Foundry (https://www.cloudfoundry.org/) IBM Bluemix (http://www.ibm.com/cloud-computing/bluemix/) Platform as a Service (PaaS) Infrastructure (VM, Storage), Big Data Analytics, Application Services, Deployment and Management, Mobile and Device Services Parse (http://www.parse.com/) Kinvey (http://www.kinvey.com/) AnyPresence (http://www.anypresence.com/) Appcelerator (http://www.appcelerator.com/) mBaaS ThingWorx (https://www.thingworx.com/) M2M offering from PTC (http://www.ptc.com/) Table 4: Cloud services What is Particle? Particle (https://www.particle.io), formerly known as Spark, is a company started by Zach Supalla. It provides hardware and software for development of IoT projects. Journey of Particle The first company started by Zach Supalla in 2011 was known as Hex Goods, and it sold designer products online. In early 2012, Hex Goods was shut down, and Zach started a second company called Switch Devices, which dealt with connected lighting. Switch Devices was then renamed Spark Devices. The name Spark was used as it provided a double meaning to the founders. Spark stood for spark of light and also sparks of inspiration. In early 2013, Spark transformed to an IoT platform for engineers and developers. The name Spark also did not last long as the founders felt Spark created confusion for a lot of users. There exist 681 live trademarks that include the word Spark. Apart from the number of trademarks, there are some other great, unrelated software and hardware products employing the name Spark in them—some of them being Apache Spark, SparkFun, and Spark NZ. It has been reported that a lot of people logged on to Zach's #spark IRC channel and asked doubts about big data. The name Particle was finally chosen, as it gave plenty of room to grow in terms of products and offerings. Particle, in scientific terms, is a single discreet unit within a larger system. The name draws a parallel with the mission of Particle—the company which provides development kits and devices as single units used to build the greater whole of IoT. We'll cover Particle IoT products in depth, and see how and when they perform better than other IoT development boards. Why Particle? Today, the most recurring problem with all existing IoT prototyping boards is that of connectivity. In order to connect the existing boards to the Internet, additional components such as Wi-Fi or GSM modules have to be attached in the development environment as well as in production. Attaching external devices for communication is cumbersome, and adds another point of failure with frequent issues such as Internet unavailability, intermittent network connectivity, and so on. This leads to a bad experience for the developer. Developers have to frequently (re)write code, deploy it onto the device(s), test, debug, fix any bugs, rinse, and repeat. The problem with code deployment with existing boards is that the boards need to be connected to a computer, which means for even the smallest code update, the device/board needs to be connected to the developer's computer, either by moving the computer to the device (which may be located at a not-so-easily accessible location) or vice versa. This poses a problem when the device, after an update at the developer's site, has to be placed back in its original production environment for testing and debugging the new changes. This means large turnaround times to load new code into production. Particle provides products that have built-in Wi-Fi modules or GSM modules, which help in easy connection to a network or the internet, with support for OTA (Over-The-Air) code deployment. This removes the hassle of adding extra modules on the prototyping boards for connectivity, and it also allows for pushing code or testing/debugging on site. As previously mentioned, one of the important features which differentiates Particle products from other devices is the Particle device's ability of deployment of code over the air. New code can be deployed onto the device or burnt, as the process is called in embedded systems' parlance, via REST API calls, which makes it very convenient to provide updates. This feature of Particle products helps in faster code release cycle and testing/debugging. What does Particle offer? Particle offers a suite of hardware and software tools to help prototype, scale, and manage the IoT products. It also provides the ability to build cloud-connected IoT prototypes quickly. If you're satisfied with your prototype and want to productize your IoT design, no problem there. It helps us to go from a single prototype to millions of units with a cloud platform that can scale as the number of devices grow. The popular Particle hardware devices are listed as follows: Core: A tiny Wi-Fi development kit for prototyping and scaling your IoT product. Reprogrammable and connected to the cloud, this has now been superseded by the Photon. Photon: A tiny Wi-Fi development kit for prototyping and scaling your IoT product. Reprogrammable and connected to the cloud. Electron: A tiny development kit for creating 2G/3G cellular connected products. The Photon and the Core are bundled with Wi-Fi modules, which help them connect to a network or the Internet without adding any extra modules. The Electron has a 3G/2G GSM module, which can be used to send or receive messages directly or connect to the Internet. The firmware for the Photon, Electron, and Core can be written in a web-based IDE provided by Particle, and the deployment of the firmware code to the device is done over-the-air. Particle also offers SDKs for mobile and web to extend the IoT experience from the devices/sensors to the phone and web. Summary In this article, we learnt about IoT, and how it all began. We briefly touched upon major organizations involved in IoT, common terminology used, and we looked at different hardware products and cloud services we have available for building IoT projects.  Resources for Article: Further resources on this subject: Identity and Access-Management Solutions for the IoT [article] Internet of Things with BeagleBone [article] The Internet of Things [article]
Read more
  • 0
  • 0
  • 3914

article-image-proportional-line-follower-advanced
Packt
26 Sep 2013
6 min read
Save for later

Proportional line follower (Advanced)

Packt
26 Sep 2013
6 min read
(For more resources related to this topic, see here.) Getting ready First, you will need to build an attachment to hold the color sensor onto the robot. Insert an axle that is five modules long into the color sensor. Place bushings onto the axle on either side of the sensor. This is illustrated in the following figure: Attach the two-pin one-axle cross blocks onto the axle outside the bushings. This is illustrated in the following figure: Insert 3-module pins into the cross blocks as shown in the following figure: The pins will attach to the robot just in front of the castor. The bottom of the color sensor should be approximately leveled with the plastic part of the castor holder. If you are on a flat hard surface, your light sensor will be half a centimeter above the ground. If you are on a soft surface, you may need to add a spacer to raise up the sensor. This is illustrated in the following figure: How to do it... We are going to write a proportional line following code similar to the code used for the ultrasonic motion sensor. We will write the following code: This program contains a loop so the robot will track a line for 30 seconds. The base speed of the robot is controlled by a constant value which in this case, is 15. You will need to determine a desired light sensor value for the robot to track on. You can either read the light sensor reading directly on your EV3 brick, or look at the panel on the lower-right hand corner of your screen. You should see all of the motors and sensors that are currently plugged into your brick. In the following screenshot, the current light sensor reading is 16. When tracking a line, you actually want to track on the edge of a line. Our code is designed to track on the right edge of a black line on a white surface. The line doesn't have to be black (or a white surface), but the stronger the contrast the better. One way to determine the desired light sensor value would be to place the light sensor on the edge of the line. Alternatively, you could take two separate readings on the bright surface and the dark surface and take the average value. In the code we discussed, the average value is 40, but you will have to determine the values which work in your own environment. Not only will the surfaces affect the value, but ambient room light can alter this value. The code next finds the difference between the desired value and the sensor reading. This difference is multiplied by a gain factor, which for the optical proportional line follower will probably be between 0 and 1. In this program, I chose a gain of 0.7. The result is added to the base speed of one motor and subtracted from the based speed of the other motor: MotorBPower = Speed - Gain * (LightSensor - DesiredValue) MotorCPower = Speed + Gain * (LightSensor - DesiredValue) After taking the light sensor readings, practice with several numbers to figure out the best speeds and proportionality constants to make your robot follow a line. How it works... This algorithm will make corrections to the path of the robot based on how far off from the line the robot is. It determines this by calculating the difference between the light sensor reading and the value of the light sensor reading on the edge. Each wheel of the robot rotates at a different speed proportional to how far from the line it is. There is a base speed for each wheel and then they will go either slower or faster for a smooth turning. You will find that a large gain value will be needed for sharp turns, but the robot will tend to overcorrect and wobble when it is following a straight line. A smaller gain and higher speed can work effectively when the line is relatively straight or follows a gradual curve. The most important factor to determine is the desired light sensor value. Although your color sensor can detect several colors, we will not be using that feature in this program. The color sensor included in your kit emits red light and we are measuring the reflection of that reflected light. The height of the sensor above the floor is critical, and there is a sweet spot for line tracking at about half a centimetre above the floor. The light comes out of the sensor in a cone. You want the light reflected into the sensor to be as bright as possible, so if your sensor is too high, the reflected intensity will be weaker. Assuming your color sensor is pointing straight down at the floor (as it is in our robot design), then you will see a circular red spot on the floor. Because the distance between the detector and the light emitter is about 5 to 6 mm, the diameter of this circle should be about 11 mm across. If the circle is large, then your color sensor is too high and the intensity will weaken. If the circle is smaller than this, then the sensor will not pick up the emitted light. The color sensor in the LEGO MINDSTORMS EV3 kit is different from the optical sensors included in the earlier LEGO NXT kits. Depending on your application, you might want to pick up some of the older NXT lights and color sensors. The light sensor in the NXT 1.0 kit could not detect color and only measured reflected intensity of a red LED. What is good about this sensor is that it will actually work flush against the surface and saves the need to calibrate changes due to the ambient lighting conditions. The color sensor in the NXT 2.0 kit actually emitted colored lights and contained a general photo detector. However, it did not directly measure color, but measured the reflection of colored light, which it would emit. This actually allowed you to track along different colored lines, but it was also slower. The new EV3 sensor detects colors directly, works quickly, and emits only red light. Summary This article taught us to alter our robot, so it can track a line using an optical sensor. We used a proportional algorithm and adjusted the parameters for optimum tracking. Finally, we also wrote a program allowing the robot to be calibrated without the use of a computer. Resources for Article : Further resources on this subject: Playing with Max 6 Framework [Article] Panda3D Game Development: Scene Effects and Shaders [Article] Our First Project – A Basic Thermometer [Article]
Read more
  • 0
  • 1
  • 3869
article-image-using-pvr-raspbmc
Packt
18 Feb 2013
9 min read
Save for later

Using PVR with Raspbmc

Packt
18 Feb 2013
9 min read
(For more resources related to this topic, see here.) What is PVR? Personal Video Recording (PVR), with a TV tuner, allows you to record as well as watch Live TV. Recordings can be scheduled manually based on a time, or with the help of the TV guide, which can be downloaded from the TV provider (by satellite/aerial or cable), or from a content information provider, such as Radio Times via the Internet. Not only does PVR allow you to watch Live TV, but on capable backends (we'll look at what a backend is in a moment), it allows you to rewind and pause live TV. A single tuner allows you to tune into one channel at once, while two tuners would allow you to tune into two. As such, it's important to note that the capabilities listed earlier are not mutually exclusive, that is, with enough tuners it is possible to record one channel while watching another. This may, depending on the software you use as a backend, be possible on one tuner, if the two channels are on the same multiplexer. Raspbmc's role in PVR Raspbmc can function as both a PVR backend and a frontend. For PVR support in XBMC, it is necessary to have both a backend and one or more frontends. Let's see what a backend and frontend is: Backend: A backend is the part that tunes the channel, records your scheduled programs, and serves those channels and recorded television to the frontends. One backend can serve multiple frontends, if it is sufficiently powerful enough and there are enough tuners available. Frontend: A frontend is the part that receives content from the backend and plays back live television and recorded programs to the user. In the case of Raspbmc, XBMC serves as the frontend and allows us to play back the content. Multiple frontends can connect to one or more backends. This means that we can have several installations of Raspbmc play broadcast content from even a single tuner. As we've now learned, Raspbmc has a built-in PVR frontend in the form of XBMC. However, it also has a built-in backend. This backend is TVHeadend, and we'll look at getting that up and running shortly. Standalone backend versus built-in backend There are cases when it is more favorable to use an external, or standalone, backend rather than the one that ships with Raspbmc itself. Outlined as follows is a comparison: Standalone backend Raspbmc backend (TVHeadend) A better choice if you do not find TVHeadend feature-rich or prefer another backend. If you only intend to have one frontend, it makes sense to run everything off the same device, rather than relying on an external system. If you have a pre-existing backend, it is easier to configure Raspbmc to use that, rather than reconfiguring it completely. The process may be simplified for you as, generally, one can just connect their device and it will be detected in TVHeadend. If you are planning on having multiple frontends, it is more sensible to have a standalone backend. This is to ensure that the computer has enough horsepower, and also, you can serve from the same computer you are serving files from, and thus, only need one device on, rather than two (the streaming machine and the Pi). Raspbmc's auto-update system covers the backend that is included as well. This means you will always have a reliable and stable version of TVHeadend bundled with Raspbmc and you need not worry about having to update it to get new features. If you need to use a PCI or PCI expressbased tuner, you will need to use an external backend due to limitations of the Pi's connectivity. Better for wireless media centers. If you have low bandwidth throughput, then running the tuner locally on the Raspberry Pi makes more sense as it does not rely on any transfers between the network (unless using HDHomeRun). Setting up PVR We will now look at how to set up a PVR. This will include configuring the backend as well as getting it running in XBMC. An external backend The purpose of this title is to focus on the Raspberry Pi, and as there is a great variety of PVR software available, it would be implausible to cover the many options. If you are planning on using an external backend, it is recommended that you thoroughly search for information on the Internet. There are even books for popular and comprehensive PVR packages, such as MythTV. TVHeadend was chosen for Raspbmc because it is lightweight and easy to manage. Raspbmc's XBMC build will support the following backends at the time of writing: MythTV TVHeadend ForTheRecord/Argus TV MediaPortal Njoy N7 NextPVR VU+/Enigma DVBViewer VDR Setting up TVHeadend in Raspbmc It should be noted that not all TV tuners will work on your device. Due to the fact that the list changes frequently, it is not possible to list here the devices that work on the Raspberry Pi. However, the most popular tuners used with Raspbmc are AF90015 based. HDHomerun tuners by SilliconDust are supported as well (note that these tuners do not connect to your Pi directly, but are accessed through the network). With the right kernel modules, TVHeadend can support DVB-T (digital terrestrial), DVB-S (satellite), and DVB-C (cable) based tuners. By default, the TVHeadend service is disabled in Raspbmc. We'll need to enable it as follows: Go to Raspbmc Settings—we did this before by selecting it from the Programs menu. Under the System Configuration tab, check the TVHeadend server radio button found under the Service Management category. Click on OK to save your settings. Now that the TVHeadend is running, we can now access its management page by going to http://192.168.1.5:9981. You should substitute the preceding IP address, 192.168.1.5, with the actual IP address of the Raspberry Pi. You will be greeted with an interface much akin to the following screenshot: In the preceding screenshot we see that there are three main tabs available. They are as follows: Electronic Program Guide: This shows us what is being broadcast on each channel. It is empty in the preceding screenshot because we've not scanned and added any channels. Digital Video Recorder: This will allow you to schedule recordings of TV channels as well as use the Automatic recorder functionality, which can allow you to create powerful rules for automatic recording. You can also schedule recordings in XBMC; however, doing so via the web interface is probably more flexible. Configuration: This is where you can configure the EPG source, choose where recordings are saved, manage access to the backend, and manage tuners. The Electronic Program Guide and Digital Video Recorder tabs are intuitive and simple so we will instead look at the Configuration section. Our first step in configuring a tuner is to head over to TV Adapters: As shown in the preceding screenshot, TV tuners should automatically be detected and selectable in the drop-down menu (highlighted here). On the right, a box entitled Adapter Configuration can be used for adjusting the tuner's parameters. Now, we need to select the Add DVB Network by location option. The following dialog box will appear: Once we have defined the region we are in, TVHeadend will automatically begin scanning for new services on the correct frequencies. These services can be mapped to channels by selecting the Map DVB services to channels button as shown earlier. We are now ready to connect to the backend in XBMC. Connecting to our backend in XBMC Regardless of whether we have used Raspbmc's built-in backend or an external one, the process for connecting to it in XBMC is very much the same. We need to do the following: In XBMC, go to System | Settings | Add-ons | Disabled Add-ons | PVR clients. You will now see the following screenshot: Select the type of backend that you would like to connect to. You will then see a dialog allowing you to configure or enable the add-on. Select Configure and fill out the necessary connection details. Note that if you are connecting to the Raspbmc built-in backend, select the TVHeadend client to configure. The default settings will suffice: Click on OK to save these settings and select Enable. Note that the add-on is now located in System | Settings | Add-ons | Enabled add-ons | PVR clients rather than Disabled add-ons | PVR clients. Now, we need to go into Settings | System | Live TV. This allows you to configure a host of options related to Live TV. The most important one is the Enable Live TV option—be sure to check this box! Now, if we go back to the main menu, we'll see a Live TV option. Your channel information will be there already, although, like the instance shown as follows, it may need a bit of renaming: The following screenshot shows us a sample electronic program guide: Simply select a channel and press Play! The functionality that PVR offers is controlled in a similar manner to XBMC, so this won't be covered in this article. If you have got this far, you've done the hard part already. Summary We've now covered what PVR can do for us, the differences between a frontend and backend, and where a remote backend may be more suitable than the one Raspbmc has built in. We then covered how to connect to that backend in XBMC and play back content from it. Resources for Article : Further resources on this subject: Adding Pages, Image Gallery, and Plugins to a WordPress Blog [Article] Building a CRUD Application with the ZK Framework [Article] Playback Audio with Video and Create a Media Playback Component Using JavaFX [Article]
Read more
  • 0
  • 0
  • 3627

article-image-creating-3d-world-roam
Packt
11 Apr 2014
5 min read
Save for later

Creating a 3D world to roam in

Packt
11 Apr 2014
5 min read
(For more resources related to this topic, see here.) We may be able to create models and objects within our 3D space, as well as generate backgrounds, but we may also want to create a more interesting environment within which to place them. 3D terrain maps provide an elegant way to define very complex landscapes. The terrain is defined using a grayscale image to set the elevation of the land. The following example shows how we can define our own landscape and simulate flying over it, or even walk on its surface: A 3D landscape generated from a terrain map Getting ready You will need to place the Map.png file in the pi3d/textures directory of the Pi3D library. Alternatively, you can use one of the elevation maps already present—replace the reference to Map.png for another one of the elevation maps, such as testislands.jpg. How to do it… Create the following 3dWorld.py script: #!/usr/bin/python3 from __future__ import absolute_import, division from __future__ import print_function, unicode_literals """ An example of generating a 3D environment using a elevation map """ from math import sin, cos, radians import demo import pi3d DISPLAY = pi3d.Display.create(x=50, y=50) #capture mouse and key presses inputs=pi3d.InputEvents() def limit(value,min,max): if (value < min): value = min elif (value > max): value = max return value def main(): CAMERA = pi3d.Camera.instance() tex = pi3d.Texture("textures/grass.jpg") flatsh = pi3d.Shader("uv_flat") # Create elevation map mapwidth,mapdepth,mapheight=200.0,200.0,50.0 mymap = pi3d.ElevationMap("textures/Map.png", width=mapwidth, depth=mapdepth, height=mapheight, divx=128, divy=128, ntiles=20) mymap.set_draw_details(flatsh, [tex], 1.0, 1.0) rot = 0.0 # rotation of camera tilt = 0.0 # tilt of camera height = 20 viewhight = 4 sky = 200 xm,ym,zm = 0.0,height,0.0 onGround = False # main display loop while DISPLAY.loop_running() and not inputs.key_state("KEY_ESC"): inputs.do_input_events() #Note:Some mice devices will be located on #get_mouse_movement(1) or (2) etc. mx,my,mv,mh,md=inputs.get_mouse_movement() rot -= (mx)*0.2 tilt -= (my)*0.2 CAMERA.reset() CAMERA.rotate(-tilt, rot, 0) CAMERA.position((xm,ym,zm)) mymap.draw() if inputs.key_state("KEY_W"): xm -= sin(radians(rot)) zm += cos(radians(rot)) elif inputs.key_state("KEY_S"): xm += sin(radians(rot)) zm -= cos(radians(rot)) elif inputs.key_state("KEY_R"): ym += 2 onGround = False elif inputs.key_state("KEY_T"): ym -= 2 ym-=0.1 #Float down! #Limit the movement xm=limit(xm,-(mapwidth/2),mapwidth/2) zm=limit(zm,-(mapdepth/2),mapdepth/2) if ym >= sky: ym = sky #Check onGround ground = mymap.calcHeight(xm, zm) + viewhight if (onGround == True) or (ym <= ground): ym = mymap.calcHeight(xm, zm) + viewhight onGround = True try: main() finally: inputs.release() DISPLAY.destroy() print("Closed Everything. END") #End How it works… Once we have defined the display, camera, textures, and shaders that we are going to use, we can define the ElevationMap object. It works by assigning a height to the terrain image based on the pixel value of selected points of the image. For example, a single line of an image will provide a slice of the ElevationMap object and a row of elevation points on the 3D surface. Mapping the map.png pixel shade to the terrain height We create an ElevationMap object by providing the filename of the image we will use for the gradient information (textures/Map.png), and we also create the dimensions of the map (width, depth, and height—which is how high the white spaces will be compared to the black spaces). The light parts of the map will create high points and the dark ones will create low points. The Map.png texture provides an example terrain map, which is converted into a three-dimensional surface. We also specify divx and divy, which determines how much detail of the terrain map is used (how many points from the terrain map are used to create the elevation surface). Finally, ntiles specifies that the texture used will be scaled to fit 20 times across the surface. Within the main DISPLAY.loop_running() section, we will control the camera, draw ElevationMap, respond to inputs, and limit movements in our space. As before, we use an InputEvents object to capture mouse movements and translate them to control the camera. We will also use inputs.key_state() to determine if W, S, R, and T have been pressed, which allow us to move forward, backwards, as well as rise up and down. To ensure that we do not fall through the ElevationMap object when we move over it, we can use mymap.calcHeight() to provide us with the height of the terrain at a specific location (x,y,z). We can either follow the ground by ensuring the camera is set to equal this, or fly through the air by just ensuring that we never go below it. When we detect that we are on the ground, we ensure that we remain on the ground until we press R to rise again. Summary In this article, we created a 3D world by covering how to define landscapes, the use of elevation maps, and the script required to respond to particular inputs and control movements in a space. Resources for Article: Further resources on this subject: Testing Your Speed [Article] Pulse width modulator [Article] Web Scraping with Python [Article]
Read more
  • 0
  • 0
  • 3620

article-image-introduction-iot
Packt
17 Jul 2017
11 min read
Save for later

Introduction to IOT

Packt
17 Jul 2017
11 min read
In this article by Kallol Bosu Roy Choudhuri, the author of the book Learn Arduino Prototyping in 10 days, we will learn about IoT. (For more resources related to this topic, see here.) As per Gartner, the number of connected devices around the world is going to reach 50 billion by the year 2020. Just imagine the magnitude and scale of the hyper-connectedness that is being forged every moment, as we read through this exciting article. Figure 1: A typical IoT scenario (automobile example) As we can see in the preceding figure, a typical IoT-based scenario is composed of the following fundamental building blocks: IoT edge device IoT cloud platform An IoT device is used to serve as a bridge between existing machines on the ground and an IoT cloud platform. The IoT cloud platform provides a cloud-based infrastructure backbone for data acquisition, data storage, and computing power for data analytics and reporting. The Arduino platform can be effectively used for prototyping IoT devices for almost any IoT solution very rapidly. Building the edge device In this section, we will learn how to use the ESP8266 Wi-Fi chip with the Arduino Uno for connecting to the Internet and posting data to an IoT cloud. There are numerous IoT cloud players in the market today, including Microsoft Azure and Amazon IoT. In this article, we will use the ThingSpeak IoT platform that is very simple to use with the Arduino platform. The following parts will be required for this prototype: 1 Arduino Uno R3 1 USB Cable 1 ESP8266-01 Wi-Fi Transceiver module 1 Breadboard 1 pc. 1K Ohms resistor 1 pc. 2k ohms resistor Some jumper wires Once all the parts have been assembled, follow the breadboard circuit shown in the following figure and build the edge device: Figure 2: ESP8266 with Arduino Uno Wiring The important facts to remember in the preceding setup are: The RXD pin of the ESP8266 chip should receive a 3.3V input signal. We have ensured this by employing the voltage division method. For test purposes, the preceding setup should work fine. However, the ESP8266 chip is demanding when it comes to power (read current) consumption, especially during transmission cycles. Just in case the ESP8266 chip does not respond to the Arduino sketch or AT commands properly, then the power supply may not be enough. Try using a separate battery for the setup. When using a separate battery, remember to use a voltage regulator that steps down the voltage to 3.3 volts before supplying the ESP8266 chip. For prolonged usage, a separate battery based power supply is recommended. Smart retail project inspiration In the previous sections, we looked at the basics of achieving IoT prototyping with the Arduino platform and an IoT cloud platform. With this basic knowledge, you are encouraged to start exploring more advanced IoT scenarios. As a future inspiration, the following smart retail project idea is being provided for you to try by applying the basic principles that you have learned in this article. After all, the goal of this article has been to show you the light and make you self-reliant with the Arduino platform. Imagine a large retail store where products are displayed in hundreds of aisles and thousands of racks. Such large warehouse-type retail layouts are common in some countries, usually with furniture sellers. One of the time-consuming tasks that these retail shops face is to keep the price of their displayed inventory matched with the ever changing competitive market rates. For example, the price of a sofa set could be marked at 350 dollars on aisle number 47 rack number 1. Now let's think from a customer’s perspective. Imagine being a potential customer, standing in front of the sofa set we would naturally search for the prices of that sofa set on the Internet. It would not be very surprising to find a similar sofa set that is priced a little lower, maybe at 325 dollars at another store. That is exactly how and when a potential customer would change her mind. The story after this is simple. The customer leaves store A, goes to store B and purchases the sofa set at 325 dollars. In order to address these types of lost sale opportunities, the furniture company management decides to lower the prices of the sofa set to 325 dollars, in order to match the competition. Thereafter, all that needs to be done is for someone to change the price label for the sofa set in aisle number 47 rack number 1, which is a 5–10 minute walk (considering the size of the shop floor) from the shop back office. In a localized store, it is still achievable without further loss of customers. Now, let's appreciate the problem by thinking hyperscale. The furniture seller’s management is located centrally, say in Sweden and they want to dynamically change the product prices for specific price-sensitive products that are displayed across more than 350 stores, in more than 40 countries. The price change should be automatic, near real time, and simultaneous across all company stores. Given the preceding problem statement, it seems a daunting task that could leave hundreds for shop floor staff scampering all day long, just to keep changing price tags for hundreds of products. An elegant solution to this problem lies in the Internet-of-Things. Figure 3: Smart retail with IoT Referring to the preceding figure, it depicts a basic IoT solution for addressing the furniture seller’s problem to matching product prices dynamically on the fly. Remember, since this is an Arduino prototyping article, the stress is on edge device prototyping. However, IoT as a whole; encompasses many areas that include edge devices and cloud platform capabilities. Our focus in this section is to be able to comprehend and build the edge device prototype that supports this smart retail IoT solution. In the preceding solution, the cloud platform takes care of running intelligent program batches to continuously analyze market rates for price-sensitive products. Once a new price has been determined by the cloud job/program, the new product prices are updated in the cloud-hosted database. Immediately after a new price change, all the IoT edge devices attached to the price tag of specific products in the company stores are notified of the new price. We can build a smart LCD panel for displaying product prices. For Internet connectivity, we can reuse the ESP8266 Wi-Fi chip that we learned in this article. Standalone Devices We are already familiar with the basic parts required for building a prototype. The two new aspects to consider when building a standalone project are an independent power source and a project container. Figure 4 - Typical parts of a Standalone Prototype As shown above, typically a standalone device prototype will contain the following parts: The device prototype (Arduino board + Peripherals + all the required Connections) An independent power source A project container/box After the basic prototype has been built the next consideration is to make it operable on its own, like an island. This is because in real world situations, you will often have to make a device that is not directly be connected to and powered from a computer. Therefore we will need to understand the various options that are available for powering our device prototypes and also understand when to choose which option. The second aspect to consider is an appropriate physical container to house the various parts of a project. A container is a physical device container will ensure that all parts of a project are nicely packaged in a safe and aesthetic manner. A distance measurement device Let's build an exciting project by combining an Ultrasonic Sensor with a 16x2 LCD character display to build an electronic distance measurement device. We will use one of the most easily available 9-volt batteries for powering this standalone device prototype. For building the distance measurement device, the following parts will be required. Arduino Uno R3 USB connector 1 pc. 9 volt battery 1 full sized bread board 1 HC-SR04 ultrasonic sensor 1 pc. 16x2 LCD character display 1 pc. 10K potentiometer 2 pcs. 220 ohms resistor 1 pc. 150 ohms resistor Some jumper wires Before we start building the device, let's understand what the device will do and the various parts involved in the device. The purpose of the device will be to be able to measure the distance of an object from the device. The following diagram depicts the overview of the device: Figure 5 - A standalone distance measurement device overview First, let's quickly understand each of the components involved in the preceding setup. Then, we will jump into hands-on prototyping and coding. The ultrasonic sensor model used in this example is known as HC-SR04. HC-SR04 is a standard commercially available ultrasonic transceiver. A transceiver is a device that is capable of transmitting as well as receiving signals. The HC-SR04 transceiver transmits ultrasonic signals. Once the signals hit an object/obstacle, the signals echo back to the HC-SR04 transceiver. The HC-SR04 ultrasonic module is shown below for reference. Figure 6 - The HC-SR04 Ultrasonic module The HC-SR-04 has four pins. The usage of the pins is explained below for easy understanding: Vcc: This pin is connected to a 5 volt power supply. Trig: This pin receives digital signals from the attached microcontroller unit in order to send out an ultrasonic burst. Echo: This pin sends the measured time duration proportional to the distance travelled by the ultrasonic burst. Gnd: This pin is connected to the ground terminal. The total time taken for the ultrasonic signals to echo back from an obstacle can be divided by 2 and then based on the speed of sound in air, the distance between the object and the HC-SR04 can be calculated. We will see how to calculate the distance in the sketch for this device prototype. As per the HC-SR04 data sheet, it is a 5-volt tolerant device, operating at 15 mA, and has a measurement range starting from 2 centimeters to a maximum of 4 meters. The HC-SR04 can be directly connected to the Arduino board pins. The 16x2 LCD character display is also a standard commercially available device, it has 16 columns and 2 rows. The LCD is controlled by its 4 data pins/lines. We will also see how to send string outputs to the LCD from the Arduino sketch. The power supply being used in today's example is a standard 9-volt battery plugged in Arduino's DC IN Jack. Alternatively, another option is to use 6 pieces of either AA-sized or AAA-sized batteries in series and plug them into the VIN pin of the Arduino board. Distance measurement device circuit Follow the bread board diagram shown next to build the distance measurement device. The diagram shown on the next page is quite complex. Take your time as you unravel through it. All the components (including the Arduino board) in this prototype are powered from the 9 volt battery. Sometimes the LCD procured online might not ship with soldered header pins. In such a case, you will have to solder 16 header pins. It is very important to note that unless the header pins are soldered properly into the LCD board, the LCD screen will not work correctly. This is a very challenging prototype to get it working at one go. Make sure there are no loose jumper wires. Notice how the positive and negative terminals of the power source are plugged into the VIN and GND pins of the Arduino board respectively. The 10K potentiometer has three legs. If you look straight at the breadboard diagram, the left hand side leg of the potentiometer is connected to the 5V power supply rail of the breadboard. Figure 7 - Typical potentiometersr The right hand-side leg is connected to the common ground rail of the breadboard. The leg in the middle is the regulated (via the potentiometer's 10K resistance dial) output that controls the LCD's V0/VEE pin. Basically, this pin controls the contrast of the display. You will also have to adjust (a simple screw driver may be used) the 10K potentiometer dial (to around halfway at 5K) to make the characters visible on the LCD screen. Initially, you may not see anything on the LCD, until the potentiometer is adjusted properly. Figure 8 - Distance measurement device prototype When the 'Trig' pin receives a signal (via pin D8 in this example) and results in sending out ultrasonic waves to the surroundings. As soon as the ultrasonic waves collide with an obstacle, they get reflected. The reflected ultrasonic waves are received by the HC-SR04 sensor. The Echo pin is used to read the output of the ultrasonic sensor (via pin D7 in this example). The output read from the 'Echo' pin is processed by the Arduino sketch to calculate the distance. Summary Thus an IoT device is used to serve as a bridge between existing machines on the ground and an IoT cloud platform. Resources for Article: Further resources on this subject: Introducing IoT with Particle's Photon and Electron [article] IoT and Decision Science [article] IoT Analytics for the Cloud [article]
Read more
  • 0
  • 0
  • 3566
article-image-conditional-statements-functions-and-lists
Packt
05 Apr 2017
14 min read
Save for later

Conditional Statements, Functions, and Lists

Packt
05 Apr 2017
14 min read
In this article, by Sai Yamanoor and Srihari Yamanoor, author of the book Python Programming with Raspberry Pi Zero, you will learn about conditional statements and how to make use of logical operators to check conditions using conditional statements. Next, youwill learn to write simple functions in Python and discuss interfacing inputs to the Raspberry Pi's GPIO header using a tactile switch (momentary push button). We will also discuss motor control (this is a run-up to the final project) using the Raspberry Pi Zero and control the motors using the switch inputs. Let's get to it! In this article, we will discuss the following topics: Conditional statements in Python Using conditional inputs to take actions based on GPIO pin states Breaking out of loops using conditional statement Functions in Python GPIO callback functions Motor control in Python (For more resources related to this topic, see here.) Conditional statements In Python, conditional statements are used to determine if a specific condition is met by testing whether a condition is True or False. Conditional statements are used to determine how a program is executed. For example,conditional statements could be used to determine whether it is time to turn on the lights. The syntax is as follows: if condition_is_true: do_something() The condition is usually tested using a logical operator, and the set of tasks under the indented block is executed. Let's consider the example,check_address_if_statement.py where the user input to a program needs to be verified using a yesor no question: check_address = input("Is your address correct(yes/no)? ") if check_address == "yes": print("Thanks. Your address has been saved") if check_address == "no": del(address) print("Your address has been deleted. Try again")check_address = input("Is your address correct(yes/no)? ") In this example, the program expects a yes or no input. If the user provides the input yes, the condition if check_address == "yes"is true, the message Your address has been savedis printed on the screen. Likewise, if the user input is no, the program executes the indented code block under the logical test condition if check_address == "no" and deletes the variable address. An if-else statement In the precedingexample, we used an ifstatement to test each condition. In Python, there is an alternative option named the if-else statement. The if-else statement enables testing an alternative condition if the main condition is not true: check_address = input("Is your address correct(yes/no)? ") if check_address == "yes": print("Thanks. Your address has been saved") else: del(address) print("Your address has been deleted. Try again") In this example, if the user input is yes, the indented code block under if is executed. Otherwise, the code block under else is executed. An if-elif-else statement In the precedingexample, the program executes any piece of code under the else block for any user input other than yesthat is if the user pressed the return key without providing any input or provided random characters instead of no, the if-elif-else statement works as follows: check_address = input("Is your address correct(yes/no)? ") if check_address == "yes": print("Thanks. Your address has been saved") elifcheck_address == "no": del(address) print("Your address has been deleted. Try again") else: print("Invalid input. Try again") If the user input is yes, the indented code block under the ifstatement is executed. If the user input is no, the indented code block under elif (else-if) is executed. If the user input is something else, the program prints the message: Invalid input. Try again. It is important to note that the code block indentation determines the block of code that needs to be executed when a specific condition is met. We recommend modifying the indentation of the conditional statement block and find out what happens to the program execution. This will help understand the importance of indentation in python. In the three examples that we discussed so far, it could be noted that an if-statement does not need to be complemented by an else statement. The else and elif statements need to have a preceding if statement or the program execution would result in an error. Breaking out of loops Conditional statements can be used to break out of a loop execution (for loop and while loop). When a specific condition is met, an if statement can be used to break out of a loop: i = 0 while True: print("The value of i is ", i) i += 1 if i > 100: break In the precedingexample, the while loop is executed in an infinite loop. The value of i is incremented and printed onthe screen. The program breaks out of the while loop when the value of i is greater than 100 and the value of i is printed from 1 to 100. The applications of conditional statements: executing tasks using GPIO Let's discuss an example where a simple push button is pressed. A button press is detected by reading the GPIO pin state. We are going to make use of conditional statements to execute a task based on the GPIO pin state. Let us connect a button to the Raspberry Pi's GPIO. All you need to get started are a button, pull-up resistor, and a few jumper wires. The figure given latershows an illustration on connecting the push button to the Raspberry Pi Zero. One of the push button's terminals is connected to the ground pin of the Raspberry Pi Zero's GPIO pin. The schematic of the button's interface is shown here: Raspberry Pi GPIO schematic The other terminal of the push button is pulled up to 3.3V using a 10K resistor.The junction of the push button terminal and the 10K resistor is connected to the GPIO pin 2. Interfacing the push button to the Raspberry Pi Zero's GPIO—an image generated using Fritzing Let's review the code required to review the button state. We make use of loops and conditional statements to read the button inputs using the Raspberry Pi Zero. We will be making use of the gpiozero. For now, let’s briefly discuss the concept of classes for this example. A class in Python is a blueprint that contains all the attributes that define an object. For example, the Button class of the gpiozero library contains all attributes required to interface a button to the Raspberry Pi Zero’s GPIO interface.These attributes include button states and functions required to check the button states and so on. In order to interface a button and read its states, we need to make use of this blueprint. The process of creating a copy of this blueprint is called instantiation. Let's get started with importing the gpiozero library and instantiate the Button class of the gpiozero. The button is interfaced to GPIO pin 2. We need to pass the pin number as an argument during instantiation: from gpiozero import Button #button is interfaced to GPIO 2 button = Button(2) The gpiozero library's documentation is available athttp://gpiozero.readthedocs.io/en/v1.2.0/api_input.html.According to the documentation, there is a variable named is_pressed in the Button class that could be tested using a conditional statement to determine if the button is pressed: if button.is_pressed: print("Button pressed") Whenever the button is pressed, the message Button pressed is printed on the screen. Let's stick this code snippet inside an infinite loop: from gpiozero import Button #button is interfaced to GPIO 2 button = Button(2) while True: if button.is_pressed: print("Button pressed") In an infinite while loop, the program constantly checks for a button press and prints the message as long as the button is being pressed. Once the button is released, it goes back to checking whether the button is pressed. Breaking out a loop by counting button presses Let's review another example where we would like to count the number of button presses and break out of the infinite loop when the button has received a predetermined number of presses: i = 0 while True: if button.is_pressed: button.wait_for_release() i += 1 print("Button pressed") if i >= 10: break In this example, the program checks for the state of the is_pressed variable. On receiving a button press, the program can be paused until the button is released using the method wait_for_release.When the button is released, the variable used to store the number of presses is incremented by 1. The program breaks out of the infinite loop, when the button has received 10 presses. A red momentary push button interfaced to Raspberry Pi Zero GPIO pin 2 Functions in Python We briefly discussed functions in Python. Functions execute a predefined set of task. print is one example of a function in Python. It enables printing something to the screen. Let's discuss writing our own functions in Python. A function can be declared in Python using the def keyword. A function could be defined as follows: defmy_func(): print("This is a simple function") In this function my_func, the print statement is written under an indented code block. Any block of code that is indented under the function definition is executed when the function is called during the code execution. The function could be executed as my_func(). Passing arguments to a function: A function is always defined with parentheses. The parentheses are used to pass any requisite arguments to a function. Arguments are parameters required to execute a function. In the earlierexample, there are no arguments passed to the function. Let's review an example where we pass an argument to a function: defadd_function(a, b): c = a + b print("The sum of a and b is ", c) In this example, a and b are arguments to the function. The function adds a and b and prints the sum onthe screen. When the function add_function is called by passing the arguments 3 and 2 as add_function(3,2) where a=3 and b=2, respectively. Hence, the arguments a and b are required to execute function, or calling the function without the arguments would result in an error. Errors related to missing arguments could be avoided by setting default values to the arguments: defadd_function(a=0, b=0): c = a + b print("The sum of a and b is ", c) The preceding function expects two arguments. If we pass only one argument to thisfunction, the other defaults to zero. For example,add_function(a=3), b defaults to 0, or add_function(b=2), a defaults to 0. When an argument is not furnished while calling a function, it defaults to zero (declared in the function). Similarly,the print function prints any variable passed as an argument. If the print function is called without any arguments, a blank line is printed. Returning values from a function Functions can perform a set of defined operations and finally return a value at the end. Let's consider the following example: def square(a): return a**2 In this example, the function returns a square of the argument. In Python, the return keyword is used to return a value requested upon completion of execution. The scope of variables in a function There are two types of variables in a Python program:local and global variables. Local variables are local to a function,that is, it is a variable declared within a function is accessible within that function.Theexample is as follows: defadd_function(): a = 3 b = 2 c = a + b print("The sum of a and b is ", c) In this example, the variables a and b are local to the function add_function. Let's consider an example of a global variable: a = 3 b = 2 defadd_function(): c = a + b print("The sum of a and b is ", c) add_function() In this case, the variables a and b are declared in the main body of the Python script. They are accessible across the entire program. Now, let's consider this example: a = 3 defmy_function(): a = 5 print("The value of a is ", a) my_function() print("The value of a is ", a) In this case, when my_function is called, the value of a is5 and the value of a is 3 in the print statement of the main body of the script. In Python, it is not possible to explicitly modify the value of global variables inside functions. In order to modify the value of a global variable, we need to make use of the global keyword: a = 3 defmy_function(): global a a = 5 print("The value of a is ", a) my_function() print("The value of a is ", a) In general, it is not recommended to modify variables inside functions as it is not a very safe practice of modifying variables. The best practice would be passing variables as arguments and returning the modified value. Consider the following example: a = 3 defmy_function(a): a = 5 print("The value of a is ", a) return a a = my_function(a) print("The value of a is ", a) In the preceding program, the value of a is 3. It is passed as an argument to my_function. The function returns 5, which is saved to a. We were able to safely modify the value of a. GPIO callback functions Let's review some uses of functions with the GPIO example. Functions can be used in order tohandle specific events related to the GPIO pins of the Raspberry Pi. For example,the gpiozero library provides the capability of calling a function either when a button is pressed or released: from gpiozero import Button defbutton_pressed(): print("button pressed") defbutton_released(): print("button released") #button is interfaced to GPIO 2 button = Button(2) button.when_pressed = button_pressed button.when_released = button_released while True: pass In this example, we make use of the attributeswhen_pressed and when_releasedof the library's GPIO class. When the button is pressed, the function button_pressed is executed. Likewise, when the button is released, the function button_released is executed. We make use of the while loop to avoid exiting the program and keep listening for button events. The pass keyword is used to avoid an error and nothing happens when a pass keyword is executed. This capability of being able to execute different functions for different events is useful in applications like Home Automation. For example, it could be used to turn on lights when it is dark and vice versa. DC motor control in Python In this section, we will discuss motor control using the Raspberry Pi Zero. Why discuss motor control? In order to control a motor, we need an H Bridge motor driver (Discussing H bridge is beyond our scope. There are several resources for H bridge motor drivers: http://www.mcmanis.com/chuck/robotics/tutorial/h-bridge/). There are several motor driver kits designed for the Raspberry Pi. In this section, we will make use of the following kit: https://www.pololu.com/product/2753. The Pololu product page also provides instructions on how to connect the motor. Let's get to writing some Python code tooperate the motor: from gpiozero import Motor from gpiozero import OutputDevice import time motor_1_direction = OutputDevice(13) motor_2_direction = OutputDevice(12) motor = Motor(5, 6) motor_1_direction.on() motor_2_direction.on() motor.forward() time.sleep(10) motor.stop() motor_1_direction.off() motor_2_direction.off() Raspberry Pi based motor control In order to control the motor, let's declare the pins, the motor's speed pins and direction pins. As per the motor driver's documentation, the motors are controlled by GPIO pins 12,13 and 5,6, respectively. from gpiozero import Motor from gpiozero import OutputDevice import time motor_1_direction = OutputDevice(13) motor_2_direction = OutputDevice(12) motor = Motor(5, 6) Controlling the motor is as simple as turning on the motor using the on() method and moving the motor in the forward direction using the forward() method: motor.forward() Similarly, reversing the motor direction could be done by calling the method reverse(). Stopping the motor could be done by: motor.stop() Some mini-project challenges for the reader: In this article, we discussed interfacing inputs for the Raspberry Pi and controlling motors. Think about a project where we could drive a mobile robot that reads inputs from whisker switches and operate a mobile robot. Is it possible to build a wall following robot in combination with the limit switches and motors? We discussed controlling a DC motor in this article. How do we control a stepper motor using a Raspberry Pi? How can we interface a motion sensor to control the lights at home using a Raspberry Pi Zero. Summary In this article, we discussed conditional statements and the applications of conditional statements in Python. We also discussed functions in Python, passing arguments to a function, returning values from a function and scope of variables in a Python program. We discussed callback functions and motor control in Python. Resources for Article: Further resources on this subject: Sending Notifications using Raspberry Pi Zero [article] Raspberry Pi Gaming Operating Systems [article] Raspberry Pi LED Blueprints [article]
Read more
  • 0
  • 0
  • 3535

article-image-building-beowulf-cluster
Packt
17 Nov 2014
19 min read
Save for later

Building a Beowulf Cluster

Packt
17 Nov 2014
19 min read
A Beowulf cluster is nothing more than a bunch of computers interconnected by Ethernet and running with a Linux or BSD operating system. A key feature is the communication over IP (Internet Protocol) that distributes problems among the boards. The entity of the boards or computers is called a cluster and each board or computer is called a node. In this article, written by Andreas Joseph Reichel, the author of Building a BeagleBone Black Super Cluster, we will first see what is really required for each board to run inside a cluster environment. You will see examples of how to build a cheap and scalable cluster housing and how to modify an ATX power supply in order to use it as a power source. I will then explain the network interconnection of the Beowulf cluster and have a look at its network topology. The article concludes with an introduction to the microSD card usage for installation images and additional swap space as well as external network storage. The following topics will be covered: Describing the minimally required equipment Building a scalable housing Modifying an ATX power source Introducing the Beowulf network topology Managing microSD cards Using external network storage We will first start with a closer look at the utilization of a single BBB and explain the minimal hardware configuration required. (For more resources related to this topic, see here.) Minimal configuration and optional equipment BBB is a single-board computer that has all the components needed to run Linux distributions that support ARMhf platforms. Due to the very powerful network utilities that come with Linux operating systems, it is not necessary to install a mouse or keyboard. Even a monitor is not required in order to install and configure a new BBB. First, we will have a look at the minimal configuration required to use a single board over a network. Minimal configuration A very powerful interface of Linux operating systems is its standard support for SSH. SSH is the abbreviation of Secure Shell, and it enables users to establish an authenticated and encrypted network connection to a remote PC that provides a Shell. Its command line can then be utilized to make use of the PC without any local monitor or keyboard. SSH is the secure replacement for the telnet service. The following diagram shows you the typical configuration of a local area network using SSH for the remote control of a BBB board: The minimal configuration for the SSH control SSH is a key feature of Linux and comes preinstalled on most distributions. If you use Microsoft ® Windows™ as your host operating system, you will require additional software such as putty, which is an SSH client that is available at http://www.putty.org. On Linux and Mac OS, there is usually an SSH client already installed, which can be started using the ssh command. Using a USB keyboard It is practical for several boards to be configured using the same network computer and an SSH client. However, if a system does not boot up, it can be hard for a beginner to figure out the reason. If you get stuck with such a problem and don't find a solution using SSH, or the SSH login is not possible for some reason anymore, it might be helpful to use a local keyboard and a local monitor to control the problematic board such as a usual PC. Installing a keyboard is possible with the onboard USB host port. A very practical way is to use a wireless keyboard and mouse combination. In this case, you only need to plug the wireless control adapter into the USB host port. Using the HDMI adapter and monitor The BBB board supports high definition graphics and, therefore, uses a mini HDMI port for the video output. In order to use a monitor, you need an adapter for mini HDMI to HDMI, DVI, or VGA, respectively. Building a scalable board-mounting system The following image shows you the finished board housing with its key components as well as some installed BBBs. Here, a indicates the threaded rod with the straw as the spacer, b indicates BeagleBone Black, c indicates the Ethernet cable, d indicates 3.5" hard disc cooling fans, e indicates the 5 V power cable, and f indicates the plate with drilled holes. The finished casing with installed BBBs One of the most important things that you have to consider before building a super computer is the space you require. It is not only important to provide stable and practical housing for some BBB boards, but also to keep in mind that you might want to upgrade the system to more boards in the future. This means that you require a scalable system that is easy to upgrade. Also, you need to keep in mind that every single board requires its own power and has to be accessible by hand (reset, boot-selection, and the power button as well as the memory card, and so on). The networking cables also need some place depending on their lengths. There are also flat Ethernet cables that need less space. The tidier the system is built, the easier it will be to track down errors or exchange faulty boards, cables, or memory cards. However, there is a more important point. Although the BBB boards are very power-efficient, they get quite warm depending on their utilization. If you have 20 boards stacked onto each other and do not provide sufficient space for air flow, your system will overheat and suffer from data loss or malfunctions. Insufficient air flow can result in the burning of devices and other permanent hardware damage. Please remember that I'm is not liable for any damages resulting from an insufficient cooling system. Depending on your taste, you can spend a lot of money on your server housing and put some lights inside and make it glow like a Christmas tree. However, I will show you very cheap housing, which is easy and fast to build and still robust enough, scalable, and practical to use. Board-holding rods The key idea of my board installation is to use the existing corner holes of the BBB boards and attach the boards on four rods in order to build a horizontal stack. This stack is then held by two side plates and a base plate. Usually, when I experiment and want to build a prototype, it is helpful not to predefine every single measurement, and then invest money into the sawing and cutting of these parts. Instead, I look around in some hobby markets and see what they have and think about whether I can use these parts. However, drilling some holes is not unavoidable. When you get to drilling holes and using screws and threads, you might know or not know that there are two different systems. One is the metric system and the other is the English system. The BBB board has four holes and their size fits to 1/8" in the English or M3 in the metric system. According to the international standard, this article will only name metric dimensions. For easy and quick installation of the boards, I used four M3 threaded rods that are obtainable at model making or hobby shops. I got mine at Conrad Electronic. For the base plates, I went to a local raw material store. The following diagram shows you the mounting hole positions for the side walls with the dimensions of BBB (dashed line). The measurements are given for the English and metric system. The mounting hole's positions Board spacers As mentioned earlier, it is important to leave enough space between the boards in order to provide finger access to the buttons and, of course, for airflow. First, I mounted each board with eight nuts. However, when you have 16 boards installed and want to uninstall the eighth board from the left, then it will take you a lot of time and nerves to get the nuts along the threaded rods. A simple solution with enough stability is to use short parts of straws. You can buy some thick drinking straws and cut them into equally long parts, each of two or three centimeters in length. Then, you can put them between the boards onto the threaded rods in order to use them as spacers. Of course, this is not the most stable way, but it is sufficient, cheap, and widely available. Cooling system One nice possibility I found for cooling the system is to use hard disk fans. They are not so cheap but I had some lying around for years. Usually, they are mounted to the lower side of 3.5" hard discs, and their width is approximately the length of one BBB. So, they are suitable for the base plate of our casing and can provide enough air flow to cool the whole system. I installed two with two fans each for eight boards and a third one for future upgrades. The following image shows you my system with eight boards installed: A board housing with BBBs and cooling system Once you have built housing with a cooling system, you can install your boards. The next step will be the connection of each board to a power source as well as the network interconnection. Both are described in the following sections. Using a low-cost power source I have seen a picture on the Web where somebody powered a dozen older Beagle Boards with a lot of single DC adapters and built everything into a portable case. The result was a huge mess of cables. You should always try to keep your cables well organized in order to save space and improve the cooling performance. Using an ATX power supply with a cable tree can save you a lot of money compared to buying several standalone power supplies. They are stable and can also provide some protection for hardware, which cheap DC adapters don't always do. In the following section, I will explain the power requirements and how to modify an ATX power supply to fit our needs. Power requirements If you do not use an additional keyboard and mouse and only onboard flash memory, one board needs around 500 mA at 5 V voltage, which gives you a total power of 2.5 Watts for one board. Depending on the installed memory card or other additional hardware, you might need more. Please note that using the Linux distribution described in this article is not compatible with the USB-client port power supply. You have to use the 5 V power jack. Power cables If you want to use an ATX power supply, then you need to build an adapter from the standard PATA or SATA power plugs to a low voltage plug that fits the 5 V jack of the board. You need a 5.5/2.1 mm low voltage plug and they are obtainable from VOLTCRAFT with cables already attached. I got mine from Conrad Electronics (item number 710344). Once you have got your power cables, you can build a small distribution box. Modifying the ATX power supply ATX power supplies are widely available and power-efficient. They cost around 60 dollars, providing more than 500 Watts of output power. For our purpose, we will only need most power on the 5 V rail and some for fans on the 12 V rail. It is not difficult to modify an ATX supply. The trick is to provide the soft-on signal, because ATX supplies are turned on from the mainboard via a soft-on signal on the green wire. If this green wire is connected to the ground, it turns on. If the connection is lost, it turns off. The following image shows you which wires of the ATX mainboard plug have to be cut and attached to a manual switch in order to build a manual on/off switch: The ATX power plug with a green and black wire, as indicated by the red circle, cut and soldered to a switch As we are using the 5 V and most probably the 12 V rail (for the cooling fans) of the power supply, it is not necessary to add resistors. If the output voltage of the supply is far too low, this means that not enough current is flowing for its internal regulation circuitry. If this happens, you can just add a 1/4 Watt 200 Ohms resistor between any +5 V (red) and GND (neighboring black) pin to drain a current of 25 mA. This should never happen when driving the BBB boards, as their power requirements are much higher and the supply should regulate well. The following image shows you the power cable distribution box. I soldered the power cables together with the cut ends of a PATA connector to a PCB board. The power cable distribution box What could happen is that the resistance of one PATA wire is too high and the voltage drop leads to a supply voltage of below 4.5 Volts. If that happens, some of the BBB boards will not power up. Either you need to retry booting these boards separately by their power button later when all others are booted up, or you need to use two PATA wires instead of one to decrease the resistance. Please have a look if this is possible with your power supply and if the two 5 V lines you want to connect do not belong to different regulation circuitries. Setting up the network backbone To interconnect BBB boards via Ethernet, we need a switch or a hub. There is a difference in the functionality between a switch and a hub: With hubs, computers can communicate with each other. Every computer is connected to the hub with a separate Ethernet cable. The hub is nothing more than a multiport repeater. This means that it just repeats all the information it receives for all other ports, and every connected PC has to decide whether the data is for it or not. This produces a lot of network traffic and can slow down the speed. Switches in comparison can control the flow of network traffic based on the address information in each packet. It learns which traffic packets are received by which PC and then forwards them only to the proper port. This allows simultaneous communication across the switch and improves the bandwidth. This is the reason why switches are the preferred choice of network interconnection for our BBB Beowulf cluster. The following table summarizes the main differences between a hub and a switch:   hub Switch Traffic control no yes Bandwidth low high I bought a 24-port Ethernet switch on eBay with 100 Megabit/s ports. This is enough for the BBB boards. The total bandwidth of the switch is 2.4 Gigabit/s. The network topology The typical network topology is a star configuration. This means that every BBB board has its own connection to the switch, and the switch itself is connected to the local area network (LAN). On most Beowulf clusters, there is one special board called the master node. This master node is used to provide the bridge between the cluster and the rest of the LAN. All users (if there are more persons that use the cluster) log in to the master node, and it is only responsible for user management and starting the correct programs on specified nodes. It usually doesn't contribute to any calculation tasks. However, as BBB only has one network connector, it is not possible to use it as a bridge, because a bridge requires two network ports: One connected to the LAN. The other connected to the switch of the cluster. Because of this, we only define one node as the master node, providing some special software features but also contributing to the calculations of the cluster. This way, all BBBs contribute to the overall calculation power, and we do not need any special hardware to build a network bridge. Regarding security, we can manage everything with SSH login rules and the kernel firewall, if required. The following diagram shows you the network topology used in this article. Every BBB has its own IP address, and you have to reserve the required amount of IP addresses in your LAN. They do not have to be successive; however, it makes it easier if you note down every IP for every board. You can give the boards hostnames such as node1, node2, node3, and so on to make them easier to follow. The network topology The RJ45 network cables There is only one thing you have to keep in mind regarding RJ45 Ethernet cables and 100 Megabit/s transmission speed. There are crossover cables and normal ones. The crossover cables have crossed lines regarding data transmission and receiving. This means that one cable can be used to connect two PCs without a hub or switch. Most modern switches can detect when data packets collide, which means when they are received on the transmitting ports and then automatically switch over the lines again. This feature is called auto MDI-X or auto-uplink. If you have a newer switch, you don't need to pay attention to which sort of cable you buy. Usually, normal RJ45 cables without crossover are the preferred choice. The Ethernet multiport switch As described earlier, we use an Ethernet switch rather than a hub. When buying a switch, you have to decide how many ports you want. For future upgrades, you can also buy an 8-port switch, for example, and later, if you want to go from seven boards (one port for the uplink) to 14 boards, you can upgrade with a second 8-port switch and connect both to the LAN. If you want to build a big system from the beginning, you might want to buy a 24-port switch or an even bigger one. The following image shows you my 24-port Ethernet switch with some connected RJ45 cables below the board housing: A 24-port cluster switch The storage memory One thing you might want to think of in the beginning is the amount of space you require for applications and data. The standard version of BBB has 2 GB flash memory onboard and newer ones have 4 GB. A critical feature of computational nodes is the amount of RAM they have installed. On BBB, this is only 512 MB. If you are of the opinion that this is not enough for your tasks, then you can extend the RAM by installing Linux on an external SD card and create a swap partition on it. However, you have to keep in mind that the external swap space is much slower than the DDR3 memory (MB/s compared to GB/s). If the software is nicely programmed, data can always be sufficiently distributed on the nodes, and each node does not need much RAM. However, with more complicated libraries and tasks, you might want to upgrade some day. Installing images on microSD cards For the installation of Linux, we will need Linux Root File System Images on the microSD card. It is always a good idea to keep these cards for future repair or extension purposes. I keep one installation SD for the master node and one for all slave nodes. When I upgrade the system to more slave nodes, I can just insert the installation SD and easily incorporate the new system with a few commands. The swap space on an SD card Usually, it should be possible to boot Linux from the internal memory and utilize the external microSD card solely as the swap space. However, I had problems utilizing the additional space as it was not properly recognized by the system. I obtained best results when booting from the same card I want the swap partition on. The external network storage To reduce the size of the used software, it is always a good idea to compile it dynamically. Each node you want to use for computations has to start the same program. Programs have to be accessible by each node, which means that you would have to install every program on every node. This is a lot of work when adding additional boards and is a waste of memory in general. To circumvent this problem, I use external network storage on the basis of Samba. The master node can then access the Samba share and create a share for all the client nodes by itself. This way, each node has access to the same software and data, and upgrades can be performed easily. Also, the need for local storage memory is reduced. Important libraries that have to be present on each local filesystem can be introduced by hard links pointing to the network storage location. The following image shows you the storage system of my BBB cluster: The storage topology Some of you might worry when I chose Samba over NFS and think that a 100 Megabit networking is too slow for cluster computations. First of all, I chose Samba because I was used to it and it is well known to most hobbyists. It is very easy to install, and I have used it for over 10 years. Only thing you have to keep in mind is that using Samba will cause your filesystem to treat capital and small letters equally. So, your Linux filenames (ext2, ext3, ext4, and so on) will behave like FAT/NTFS filenames. Regarding the network bandwidth, a double value will require 8 bytes of memory and thus, you can transfer a maximum of 2.4 billion double values per second on a hub with 24 ports and 100 Megabit/s. Additionally, libraries are optimized to keep the network talk as low as possible and solve as much as possible on the local CPU memory system. Thus, for most applications, the construction as described earlier will be sufficient. Summary In this article, you were introduced to the whole cluster concept regarding its hardware and interconnection. You were shown a working system configuration using only the minimally required amount of equipment and also some optional possibilities. A description of very basic housing including a cooling system was given as an example for a cheap yet nicely scalable possibility to mount the boards. You also learned how to build a cost-efficient power supply using a widely available ATX supply, and you were shown how to modify it to power several BBBs. Finally, you were introduced to the network topology and the purpose of network switches. A short description about the used storage system ended this article. If you interconnect everything as described in this article, it means that you have created the hardware basis of a super computer cluster. Resources for Article: Further resources on this subject: Protecting GPG Keys in BeagleBone [article] Making the Unit Very Mobile - Controlling Legged Movement [article] Pulse width modulator [article]
Read more
  • 0
  • 0
  • 3489