Jumpstarting the Onion

An Introduction to a New Low-Cost Internet of Things Computer

WOLFRAM DONAT

JUMPSTARTING the Onion Omega2 AN INTRODUCTION TO A NEW LOW-COST INTERNET OF THINGS COMPUTER

Wolfram Donat

Maker Media, Inc. San Francisco Copyright © 2018 Wolfram Donat. All rights reserved. Published by Maker Media, Inc. 1700 Montgomery Street, Suite 240 San Francisco, CA 94111 Maker Media books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari- booksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or [email protected]. Editorial Director: Roger Stewart Editor: Patrick DiJusto Copy Editor: Elizabeth Welch, Happenstance Type-O-Rama Proofreader: Scout Festa, Happenstance Type-O-Rama Cover and Interior Designer: Maureen Forys, Happenstance Type-O-Rama All the circuit and component diagrams in this book are created using Fritz- ing (http://fritzing.org/home). June 2018: First Edition Revision History for the First Edition 2018-06-18 First Release

See oreilly.com/catalog/errata.csp?isbn=9781680455229 for release details. Make:, Maker Shed, and Maker Faire are registered trademarks of Maker Media, Inc. The Maker Media logo is a trademark of Maker Media, Inc. Jumpstarting the Onion Omega2 and related trade dress are trademarks of Maker Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Maker Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omis- sions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other tech- nology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-680-45522-9 Safari® Books Online Safari Books Online is an on-demand digital library that delivers expert content in both book and video form from the world’s leading authors in technology and business. Technology professionals, software developers, web designers, and business and creative professionals use Safari Books Online as their primary resource for research, problem solving, learning, and certification training. Safari Books Online offers a range of plans and pricing for enterprise, government, education, and individuals. Members have access to thousands of books, training videos, and prepublication manuscripts in one fully searchable database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technology, and hundreds more. For more information about Safari Books Online, please visit us online.

How to Contact Us Please address comments and questions to the publisher: Maker Media, Inc. 1700 Montgomery Street, Suite 240 San Francisco, CA 94111 You can send comments and questions to us by email at [email protected]. Maker Media unites, inspires, informs, and entertains a growing community of resourceful people who undertake amazing projects in their backyards, basements, and garages. Maker Media celebrates your right to tweak, hack, and bend any Technology to your will. The Maker Media audience continues to be a growing culture and community that believes in bettering ourselves, our environment, our educational system—our entire world. This is much more than an audience, it’s a worldwide movement that Maker Media is leading. We call it the Maker Movement.

To learn more about Make: visit us at makezine.com. You can learn more about the company at the following websites:

Maker Media: makermedia.com Maker Faire: makerfaire.com Maker Shed: makershed.com Maker Share: makershare.com

CONTENTS

Introduction vii

1 Setting Up Everything 1 Graphical Setup 3 Trouble Connecting? 5 Connecting via the Command Line 6 Upgrading Firmware and Installing the Console 7

2 Getting to Know the Console 11 GPIO Tool 12 OLED Control 13 Settings 15 The Terminal App 16 The Editor 16 The Webcam Application 18 Relay and PWM Control 19 OPKG and Python 22

3 The Tweetin’ Onion 25 The Temperature Tweet 25 Install Modules 26 The Twitter Side of Things 27 The Hardware 29 The Code 31

4 The Photovore 35 Parts 36 The Voltage Divider 37 Hardware Setup 39 Software and Code 43

v 

INTRODUCTION

In the proud tradition of computers named after fruit—the Apple, the , the Banana Pi, the Pine (okay, maybe not that last one)—comes a new entry into the small, single-board computer (SBC) market: the Onion Omega2. Let’s ignore the fact that an onion is a vegetable, not a fruit, and talk about the Onion Omega2’s origins for a moment. The Onion Omega2 (and its big brother, the Omega2+) are the second offering from a company called, appropriately enough, Onion. The original Omega cost about $18 and ran on a Qual- comm Atheros AR9331 . Onion ran a Kickstarter campaign in 2016 to replace the Omega with the Omega2, using a different , the MediaTek MT7688. They were ultimately successful, raising well over their goal of $440,000, and the Omega2 shipped late in 2016. A nice feature of the newer ver- sion was the price drop; the new board started at $5, though it was later increased to $7.50. The Omega2+ is only $9. The Omega2 is an SBC geared for the Internet of Things (IoT) market, billed as the “world’s smallest server.” It runs a vari- ant of Linux known as OpenWRT, which is most commonly found on embedded devices like routers. It’s low power and really tiny; at 43mm×26mm×10mm, it’s just a little larger than an Pro Mini. Don’t let that fool you into thinking it’s not a real computer, however. It’s surprisingly powerful for the size, with its MIPS pro- cessor running at 580MHz. It supports up to 256MB of RAM, and it can support SD card storage. It supports 802.11b/g/n 2.4GHz WiFi and 10/100M Ethernet, as well as a multitude of other pro- tocols like UART, I2S, I2C, and SPI. It operates at 3.3V, but its

vii  docks and expansion boards come with a convenient onboard voltage regulator, which means you can power it with a variety of power supplies without having to worry about blowing it up. There are just a few differences between the Omega2 and the Omega2+, since they have the same processor. The O2 has 64MB of DDR2 DRAM memory, whereas the O2+ has 128. The O2 has 16MB of onboard flash storage, and the O2+ has 32. Finally, the O2+ has a microSD card slot, which gives you signifi- cantly more room for programs. Given the small difference in price, I suggest you pick up the O2+, but all of the projects in this book will work on either model, so if you’ve already purchased the O2, not to worry. I would like to interject a small observation here. If you really go back and look at those specs, it is insane how far we’ve come when it comes to putting computing power into small packages. My first computer was a Commodore VIC-20, which had a whop- ping 5KB of RAM. That’s less than the size of a standard image thumbnail on the web today, and almost thirteen thousand times smaller than the Omega2’s DRAM package. Quite a few expansion boards and docks are available; you’re going to need at least one right off the bat, as the Onion’s head- ers are at a 2mm pitch instead of the more common 0.1g pitch, which means you can’t just plug it into your breadboard. You’ll have to use either a dock or a breadboard expansion piece, so my suggestion is to purchase the power dock (Figure I-1). It allows you to power the board and whatever add-ons you happen to have using not just a microUSB cable, but also a 2-pin JST-PH connector—the standard connector on many lithium-ion (Li-ion) batteries. None of the expansion boards are very expensive, so it’s worth the time to look around and see what’s available when you’re shopping for your Onion.

viii Jumpstarting the Onion Omega2 FIGURE I-1: The power dock

Ordinarily this is where I’d walk you through the board and show you what’s on it, but these devices are covered by a metal cover so you can’t really see anything. I can, however, tell you what pins are made available to you when you plug it into a dock. The number of pins depends on the board; the power dock gives you 30 (you lose a power-in pin and a few GPIOs and gain a 5V and a few GNDs), and the breadboard dock gives you all 32. These include the standard 3.3V and GND pins, as well as I2C, Serial, and even Ethernet pins. In this book I’ll be using the Omega2+, the power dock, the relay expansion board, and the OLED expansion board, so if you still have some shopping to do you’ll know what you need. I’m also assuming that you have at least a basic familiarity with Linux, because we’ll be doing some work in the command line. Other- wise, read on and we’ll get your Onion started up!

Introduction ix

1 Setting Up Everything

Okay, so you’ve got your Onion Omega2 or Omega2+ in front of you. Let’s see how we go about setting it up so we can inter- face with it and program it. There are two ways to set it up for the first time: either the GUI way using a browser or via the command line. Onion sug- gests using the browser for simplicity’s sake, so we’ll outline those steps first. As I mentioned in the introduction, I’m going to assume not only that you have an Omega2 or 2+ board, but also that you purchased a dock to make things easier. Start by plugging your Onion into the dock, making sure not to bend any of the header pins. First, place the board over the dock and align all the pins with the holes. Make sure the board is level and not at an angle. Then, gently but firmly push down on the center of the Omega2 board so that both rows of pins have the same pressure on them. You don’t want one side to get more pressure than the other— that’s how pins get bent. Make sure that you don’t plug it in backward, either—in the case of the power dock, the side of the O2 with the mounting holes should sit atop the JST power connector. In the case of the breadboard expansion dock, that side should be opposite the microUSB port. In both cases, the shape of the Onion, with its diagonal cutouts at two corners, sort of matches the board it’s plugged into (Figure 1-1).

FIGURE 1-1: Matching corners on the Omega2

Now connect some power to your board, via either the microUSB cable or lithium-ion (Li-ion) battery, and turn on the power switch (if the dock you’re using has one). The switch isn’t labeled, so if the tiny orange LED on your O2 lights immedi- ately, it’s (obviously) powered on. It should start blinking in a few seconds; after about a minute, it should have finished booting. The orange LED will stop blinking on most O2s when the boot sequence is complete; mine continued to blink for about 5 min- utes on first boot, though it was finished booting. (On subse- quent power cycles, it stopped blinking after about a minute.) When the light is solid or it’s been about 60 seconds (which- ever comes first), you’ll be able to access your Onion through

2 Jumpstarting the Onion Omega2 a browser window and a wireless connection. If you’re using a Windows machine, you’ll need to install Apple’s Bonjour Print Services (https://support.apple.com/kb/DL999), which allows Windowscomputers to discover and connect to Bonjour- ­enabled printers. If you’re using a Mac, you should be set to go, and the same with a Linux box. The screenshots you’ll see here are on a Mac. Go to your WiFi menu and look for your Omega2’s wireless network. It will be named “Omega-XXXX,” where the last four characters are the last four characters of the MAC address on the sticker on your Onion’s metal shield. So if your sticker reads MAC: 40A36BC1BCD3, the wireless network you’re looking for will be Omega-BDC3 (Figure 1-2). Connect to that network with the default password 12345678.

FIGURE 1-2: The Omega2’s network

GRAPHICAL SETUP Now open up a browser and in the address bar type http://­ omega-XXXX.local, where XXXX are the same characters as from the network name. You can also use 192.168.3.1 if you have trou- ble reaching the .local page. Figure 1-3 shows the Omega2 Setup Wizard page.

Setting Up Everything 3 FIGURE 1-3: The Setup Wizard page

Click Start and log in with the username root and the pass- word onioneer. You’ll then be asked to identify and connect to your wireless network, which is a necessary step to continue. Find your network, enter your information, and click Configure Wi-Fi. The O2 will attempt to connect to your network, which may take a few minutes. Once your board is done configuring itself, you’ll be asked if you want to register it on the cloud. This is up to you, but if you like you can skip that step and do it later. Registering your O2 on Omega’s cloud not only lets you access your O2 from anywhere, but also allows you to install apps, create API keys, and even compile and load projects from a web browser. If you choose to do it later, waiting won’t affect the setup steps here. Finally, click the Upgrade Firmware And Install Console but- ton. This will update your O2 to the latest firmware and install it, as well as installing the console application. When it’s fin- ished, you should see a Success! screen, and your board should reboot. (If it doesn’t come back online, switch it off and on again

4 Jumpstarting the Onion Omega2 or disconnect/reconnect the power, and it should power up suc- cessfully.) You are now all set up!

TROUBLE CONNECTING? It may happen that the Setup wizard fails; try as I might, I could not get my O2+ to connect to my home network via the wizard— it either rejected the password (which I knew was correct) or sim- ply hung on the Configuring step. If your board simply won’t con- nect, and you know the password is correct, first make sure that your home network IP addresses aren’t colliding with the Onion. In other words, if your home IP is on a network with the same address prefix 192.168.3.0/24( ), your board will be confused and won’t know what data to send where. If that’s the case, you can change the O2’s network prefix and solve the problem. If you need to do that, follow the directions in the following section to use Secure Shell (SSH) to connect to your Omega2, and then we’ll use the uci command to edit its IP address. Once you’re logged in, enter the following in your terminal application: uci set network.wlan.ipaddr= where IP ADDRESS should be 192.168.5.1 or something similar— just something different from your home network’s prefix. Once you’ve set it, you’ll need to save your changes with uci commit network and then restart your Omega2’s network with

/etc/init.d/network restart

Now you can try connecting again via your browser. If you still have problems, read on.

Setting Up Everything 5 CONNECTING VIA THE COMMAND LINE If the GUI setup has failed for you, fear not! This is what the command-line setup is for! To connect via the command line, you’ll need to SSH into your board. Follow the previous steps to connect your computer to the O2’s wireless network, but then open a terminal (Mac/Linux) or your SSH client, such as PuTTy (Windows). In your terminal, type

ssh [email protected]

where again the XXXX is your O2’s ID. The password is onioneer, and you should almost immediately see something like Figure 1-4.

FIGURE 1-4: SSH login to the Omega2

You may get a warning about connecting to the Omega2 for the first time; you can accept the warning and connect. Once you’re logged in, you can connect to your network

using the wifisetup command. Enter that in your terminal and you’ll be greeted with the screen you see in Figure 1-5.

6 Jumpstarting the Onion Omega2 FIGURE 1-5: The wifisetup command sequence

When you see this screen, choose 1 to scan for networks. Choose your home WiFi network from the resulting list and enter the password. (A nice feature of this particular tool is that you can see the password you’re typing, so you can make sure it’s correct.) Once you press Enter, the Onion will restart its network adapter and connect to your network.

UPGRADING FIRMWARE AND INSTALLING THE CONSOLE Now that you’re connected, you’ll need to upgrade the firmware and install the console to make working with the O2 a bit easier. In your terminal, type oupgrade

The Onion will compare your firmware and version against what’s available online and download and install

Setting Up Everything 7 the newer version if necessary. This can take a few minutes, so don’t be too impatient. Per the Onion website: Do NOT dis- connect your board from power or WiFi during the upgrade process, as it may corrupt the OS! When the upgrade is fin- ished, your board will reboot and the blinking LED will again stop blinking. When it has rebooted, SSH into your O2 again, using the same username and password, and install the console by typing the following commands into your terminal:

uci set onion.console.setup=1 uci set onion.console.install=2 uci commit onion

The console will then be installed the next time you boot your board. You can enter

reboot now

in your terminal to reboot your board immediately. To make sure everything worked the way it should, open your browser again and enter http://omega-XXXX.local/ into the address bar,

substituting your O2’s name for XXXX. You should be greeted with the console login page (Figure 1-6).

FIGURE 1-6: The console login page

8 Jumpstarting the Onion Omega2 The username is root and the password is onioneer. Enter those credentials and you should now see the console (Figure 1-7).

FIGURE 1-7: The Omega2 console

Congratulations! You’ve now set up and connected to your Omega2 board. In the next chapter we’ll go through the different console areas and write a small introductory application.

Setting Up Everything 9

2 Getting to Know the Console

Now that we’ve got your Omega2 set up, let’s walk through the different parts of the console application and see what each one does before we play around with programming the board itself. Once you’ve logged into your console, you should see a screen like the one in Figure 2-1.

FIGURE 2-1: The Omega2 console GPIO TOOL Starting at the upper left, you see the first item on the screen is the GPIO tool, which lets you play around with the general-­ purpose input/output (GPIO) pins on the O2 in real time, turning them off and on with no programming involved. To try it out, grab an LED from your toolkit and plug it into the headers on your dock, with the longer (positive) leg in the header for pin 1 and the shorter anode in the GND position (Figure 2-2).

FIGURE 2-2: An LED connected to pin 0 and GND

Now click the GPIO Tool icon on your console and you’ll see a sketch of the Onion’s dock (Figure 2-3). Leave the default GPIO 0 selected, and choose Output from the Direction drop- down menu and 0 from the Value dropdown menu. The LED you

12 Jumpstarting the Onion Omega2 plugged in should light up. Choose 0 from the Value dropdown menu to turn it off again.

FIGURE 2-3: The GPIO tool

As you can see, you can play with input and output values for several of the GPIO pins with this tool. For instance, connect a jumper wire between the 3.3V pin (not the 5V—the Omega’s pins can’t handle more than 3.3V inputs) and pin 6. Click pin 6 on the GPIO sketch, select Input from the Direction dropdown, and click the Sync button. The entry in the Value box should switch to 1. If you then move the jumper wire to the GND header and click Sync again, the value will switch to 0. I think it’s a good way of making sure that your GPIO pins are acting the way you expect them to.

OLED CONTROL Next, let’s look at the organic light-emitting diode (OLED) tool (I’m assuming you purchased an OLED expansion to go with your Onion). Choosing this tool from the home console screen takes you to the OLED Expansion Control screen (Figure 2-4).

Getting to Know the Console 13 FIGURE 2-4: The OLED Expansion Control screen

There are a few handy tools here, but before any of them will work on your screen, you’ll need to initialize the screen from the command line. SSH into your O2 again if you’ve disconnected, and at the prompt, type

oled-exp -i

This “turns on” the board and allows it to respond to commands. Back in your OLED control console, in the Text tab (the default), type some words on the display by clicking in the text box and then click the Display On OLED button. Your text should appear on the screen. If you choose a setting from the Scroll dropdown menu at the top right of the screen, the words should move smoothly in the direction you chose. The Toggle Invert and Toggle Dim buttons are self-explanatory, and when you’re done playing with the text, click Clear Screen to move on. The Image tab allows you to upload an image to the O2’s internal memory that can then be displayed on the screen. The screen has a resolution of 128×4, so it’s surprisingly good at dis- playing rather detailed images (Figure 2-5).

14 Jumpstarting the Onion Omega2 FIGURE 2-5: The OLED tool displaying a car

SETTINGS The Settings application is pretty comprehensive; it allows you to do everything from setting up your O2 as a WiFi access point to setting your time zone to changing your security settings. A handy tool on this page is the Firmware Upgrade tab, which will check the Onion servers and see whether your board needs an upgrade. The Factory Restore tool may come in handy if you manage to brick your board (somehow I’ve managed to avoid that so far). The Cloud Settings tab allows you to register your O2 on the Omega Cloud, which allows you to remotely interact with it and even compile code online. If you skipped this step during your board setup process, here’s where you can remedy that, should you choose to. Clicking the Register button walks you through the process of registering on Onion’s servers and then

Getting to Know the Console 15 registering your device. Once successful, you’ll receive a device ID, which you might want to jot down for future reference.

THE TERMINAL APP In order to save space on the device, the folks at Onion decided to leave the Terminal, Editor, and Webcam tools out of the default console installation. If you would like to play with them, you’ll need to install each one. Luckily, it’s a simple click. There doesn’t seem to be much to the Terminal app (it’s the same interface as an SSH interface), so if you don’t want to bother installing it, you won’t be missing much.

THE EDITOR Next up in the available applications is the Editor, possibly the most useful of them all. The Editor allows you to write and save shell scripts to your board (think of it as a sort of text editor like vim or nano that goes with the Omega2’s Linux distro). You can also upload files and scripts from your local machine. After installing the Editor, you’ll see the screen in Figure 2-6.

FIGURE 2-6: The Editor application

16 Jumpstarting the Onion Omega2 Along the left side of the screen is your board’s directory structure, and along the top are tools to interact with files and folders. Let’s write a simple shell script that will change the O2’s solid LED to a heartbeat pattern. In your editor, navigate to the

/root folder by clicking it, and then click New File. Name the file heartbeat.sh. When it’s been created and saved, click the name of the file on the left, and then enter the following lines into your file:

#!/bin/sh # Get the name of the board # Either omega2 or omega2p . /lib/ramips.sh board=$(ramips_board_name) # Define the function _Heartbeat () { echo heartbeat > /sys/class/leds/$board\:amber\:system/trigger } ## Main program ## _Heartbeat $* exit

If you’re familiar with shell scripts in Linux, this should be pretty easy to understand. We’re simply getting the name of the board from the /lib/ramips.sh script, and then using that name in the filename/directory structure that we echo heartbeat into. Save the file (the button at the very top right) and then open your SSH connection (or your Terminal app—either one will work) and enter the following at the prompt: sh /root/heartbeat.sh

The LED on your Onion should start beating like a heartbeat, showing that you created and saved the script correctly.

Getting to Know the Console 17 THE WEBCAM APPLICATION The next app in the list that may be worth trying out is the Web- cam app, which does need to be installed. After installing it, you should see the screen in Figure 2-7.

FIGURE 2-7: The Webcam app

If you have an expansion dock with a USB port, plug a stan- dard USB webcam into the port and click Start Stream at the top of the screen. If all is working, your camera should show up in the middle of the screen, as shown in Figure 2-8.

FIGURE 2-8: The working webcam

18 Jumpstarting the Onion Omega2 Try playing with the resolution and FPS settings in the Web- cam tool. It’s worth noting here that not all USB webcams will work with the Omega2, because not all webcams can work with the Onion’s ARM chipset, and some require more power than the O2 can provide. Also note that you may have to restart your board after plugging in the webcam in order for it to be recognized.

RELAY AND PWM CONTROL The last two sections of the console deal with expansion boards that you may or may not have purchased: the relay board and the PWM (pulse-width modulation) board. The first of these (which we’ll use in Chapter 4) allows you to control two other external, independent circuits, such as motors, that are isolated from your O2 and use a separate power source. You can use some pretty beefy power supplies here; the relays are rated for 220VDC or 250VAC switching voltage, with up to 2A current and 60W of power. That’s enough to easily handle turning on a lamp, a ther- mostat, or even your garage door. If you have the board, plug it into your expansion dock—you don’t even have to hook anything up to it to experiment with it.

NOTE Make it a habit to switch off or cut the power to your Omega2 before adding or removing expansion boards like the relay board or the OLED board. Although these boards and the O2 are pretty sturdy, it is possible for a stray power spike to damage either piece of equipment when you’re connecting or disconnecting.

Getting to Know the Console 19 When it’s connected and your board is powered on again, log into your console and click the Relay Control icon. You’ll see a screen like the one in Figure 2-9.

FIGURE 2-9: Relay Control screen

There are five clickable objects on this screen: the two relays, R1 and R2, and the three toggle switches. The switches control the I2C address of the board (which is useful for when you have more than one relay expansion board connected), and R1 and R2 actually control the relays. To test the board, move all of the toggle switch icons to the right by clicking them so that the Relay

I2C Address shown is 0x27. Now click the R1 relay, and you should hear the physical relay on your expansion board click. R2 should do the same when you click on its representation. You can stack up to 8 relay expansion boards, which means you can control up to 16 external devices with these boards! Finally, the PWM control tool allows you to send pulse-width modulated signals to up to 16 different devices such as servos, DC motors, and LEDs. Those devices can be powered either through your dock or with the attached DC barrel jack, which allows you to source up to 6V to power your external devices.

20 Jumpstarting the Onion Omega2 The Onion will source only enough power for one or two servos, so you’re going to want to use an external source for anything more than that. Also, unlike the relay expansion board, you can attach only one PWM expansion board to your O2 at any given time. However, that still allows you to control up to 16 devices. The board’s 16 channels come with male headers preattached, with the pins in order, from top to bottom:

Ground

5V

Signal

(The white/yellow pin is the signal pin.) If you have the board and a servo sitting around, plug it into the board and open the PWM control tool from your console. You’ll be greeted by the screen shown in Figure 2-10.

FIGURE 2-10: PWM Control screen

All 16 of the PWM channels are clickable; if none are selected, all are active. If you want to choose one channel in particular, simply click it. Unfortunately, you can’t simultaneously select two

Getting to Know the Console 21 channels, or three, or four—you can select only one channel or all of them. At the right you can choose the frequency, duty cycle, and delay. With your servo channel selected, play around with these values and see what effects they have on your servo’s motion.

OPKG AND PYTHON That concludes our tour of the Omega2 console. The last thing I’d like to discuss before we move on to our projects is the Onion’s package manager and using it to install packages—Python in particular. If you’re familiar with Linux, you know that most distributions have a package manager that handles software installation for you, from determining what package is necessary to finding and installing dependencies. The Onion’s WRT distro is no different,

and it uses the opkg package manager. I tend to use Python for most of my programming, and with the O2 it’s no different. We will, however, need to use the pack- age manager to install Python, because it doesn’t come prein- stalled on your board. To save space, we’re going to install the light version. SSH into your Onion (or use the Terminal application in your console) and at the prompt, enter

opkg update

to update opkg’s list of packages. Now, install python-light with

opkg install python-light

If you would like to use Python3, you can install it as well with

opkg install python3-light

22 Jumpstarting the Onion Omega2 Finally, we may need to install additional Python packages, and to do that we can use pip, Python’s package manager. We can install it with opkg install python-pip

We will, however, need to update the default setuptools mod- ule that comes with pip, and that can be done by entering pip install --upgrade setuptools

at the terminal prompt.

Now, if we need to use the module urllib3 (for example), we can install it by typing pip install urllib3 and it will be available in our Python scripts. That should do it for our setup and first scripts! In the next chapter, we’ll get started with our first project with the Omega2.

Getting to Know the Console 23

3 The Tweetin’ Onion

Now that we’ve had an introduction to how the Omega2 works and how to interface with it, let’s create a few projects.

THE TEMPERATURE TWEET For the first project, I’d like you to remember the O2’s roots as an interface to the Internet of Things (IoT). With that in mind, let’s use an external sensor to read the temperature in the room, and then create a Twitter account (or use our own) and use Twitter’s API to tweet the temperature results every so often. The temperature sensor I’m using here is the DS18B20 one-wire temperature sensor, available from both Jameco and Amazon. This one is useful because it’s small, cheap, and easy to interface with (note the one-wire in the name). Also, the kind folks at Onion have already done the hard work for us of writ- ing a library (in Python, even!) to interface with the DS18B20. We’ll reuse their code in our little application here. (Remember: Programmers are inherently lazy. Don’t reinvent the wheel if you don’t have to.)

INSTALL MODULES The first thing we’ll need to do is install the Python modules we’ll need, which will allow us to interact with the Onion’s GPIO pins. Connect to your O2 via either the console or an SSH session, and in your terminal, enter

opkg update

followed by

opkg install pyOnionGpio

If you’d like to write your code in a terminal session on your Onion, vi comes preinstalled. If you like, you can also install nano, the text editor:

opkg install nano

This is not a requirement; you are free to use the Editor tab in the console or even write your code on your local desktop/laptop

and upload it via the Editor or the scp command if you’d prefer. I just find it easier to do my development on the machine for which I’m developing. It’s pretty easy to switch back and forth between

nano main.py

and

python main.py

as your code develops.

26 Jumpstarting the Onion Omega2 THE TWITTER SIDE OF THINGS In order to interact easily with Twitter’s API, we’re going to down- load and use a great tool called Twython, developed by Ryan

McGrath and Mike Helmick. It’s available using pip, so if you’ve installed pip (as you should have if you were following along in Chapter 2) simply enter pip install twython in your terminal. Once it’s installed (which can take a little while— remember that the Onion doesn’t have a whole lot of processing power), it’s available to you in your Python program. If you want to test it, in your O2’s terminal enter python

and then type

>>> import twython at the prompt and make sure no errors are returned. Now that Twython is installed on your Omega2, go to http:// apps.twitter.com. Log into your account, or create a Twitter account if you don’t have one already. Then click the Create New App button on the right side of the page. Now you’ll need to fill in your application details, starting with the name of the app (Figure 3-1). It’s probably to your advan- tage to name it something memorable, like OnionTweetTemp, so you can find it easily. Then fill in the Description and Website fields, which are both required. (If you don’t have a website, you can use a placeholder such as http://www.example.com for this field.) Then check the Developer Agreement box and create your application.

The Tweetin’ Onion 27 FIGURE 3-1: Creating a Twitter app

Now you’ll be greeted by your app’s management page. Make sure that everything you see on the page is correct, and then go to the Keys And Access Tokens tab. You’ll need the Consumer Key and the Consumer Secret for your application, and you’ll also need an access token, which hasn’t been created yet. Scroll to the bottom and click Create My Access Token, which will allow your app to post status updates to your Twitter account. Finally, when that’s completed, make sure that your application has Read and Write access level permissions (Figure 3-2).

28 Jumpstarting the Onion Omega2 FIGURE 3-2: Twitter application permissions

Got all that? Good. Now, let’s go back to the Omega.

THE HARDWARE For this project, you’ll need your Omega2 and an expansion board, a DS18B20 sensor, a 5kΩ (or thereabouts) resistor, a small breadboard, and some jumper wires. Start by plugging the sensor into your breadboard. Looking at the sensor from the front (the flat side), the three pins are

GND, Data, and VDD (Figure 3-3).

The Tweetin’ Onion 29 FIGURE 3-3: The DS18B20 sensor

Next, connect the resistor between pins 2 and 3, which has the effect of pulling the input HIGH between data reads. Now, using your jumper wires, connect the GND pin to one of your

board’s ground pins, the VDD pin to a 3.3V pin, and the Data pin (DQ) to GPIO pin 19. Your final setup should look something like Figure 3-4.

30 Jumpstarting the Onion Omega2 FIGURE 3-4: Connected temperature sensor

THE CODE Now that Twitter’s been set up and your hardware is connected, it’s time to look at the code. As I stated earlier, I’m using some of the code written by the Onion’s coding group as a base template; we’ll download the three files we need and then modify them to do what we want.

Start by creating a folder on your O2 and cding into it: mkdir OnionTweetTemp cd OnionTweetTemp

Now download the files we need: wget https://raw.githubusercontent.com/OnionIoT/temperature-monitor/ master/temperatureSensor.py wget https://raw.githubusercontent.com/OnionIoT/temperature-monitor/ master/oneWire.py wget https://raw.githubusercontent.com/OnionIoT/temperature-monitor/ master/main.py

Each of those wget commands is one line. You can put them all in one command if you like; it just shows up better in print if I break it into three downloads.

The Tweetin’ Onion 31 We don’t need to change oneWire.py and temperatureSensor.py; they’re the code libraries necessary to communicate with the

DS18B20. oneWire.py does the actual communicating with the sensor, and temperatureSensor.py creates an object of the tem- peratureSensor class and returns the value read (in Celsius). Instead, let’s open main.py and change and delete a few things:

nano main.py

We don’t need to import os, json, ubidots, or oledHelper, so remove those lines. Nor do we need to import config, define a dirName, open the config file, or create a token or deviceName. So your main.py should contain only the following lines before def __main__():

import oneWire import temperatureSensor oneWireGpio = 19

What we do need, however, is some Twitter stuff. Add another

import statement:

from twython import Twython

and declare your app’s keys:

app_key = "" app_secret = "" oauth_token = "" oauth_secret = "" twitter = Twython(app_key, app_secret, oauth_token, oauth_secret)

and now your main function should look something like this:

def __main__(): if not oneWire.setupOneWire(str(oneWireGpio)): print "Kernel module could not be inserted. Please reboot and try again."

return -1 # get the address of the temperature sensor # it should be the only device connected in this experiment

32 Jumpstarting the Onion Omega2 sensorAddress = oneWire.scanOneAddress() # instantiate the temperature sensor object sensor = temperatureSensor.TemperatureSensor("oneWire", {"address": sensorAddress, "gpio": oneWireGpio }) if not sensor.ready: print "Sensor was not set up correctly. Please make sure that your sensor is firmly connected to the GPIO specified above and try again." return -1 # check and print the temperature temperature = sensor.readValue() dataPoint = {"temperature": temperature} # temperature is in deg C # To change to deg F, add following line: temperature = temperature * (9.0/5.0) + 32.0

# Post to Twitter twitter.update_status(status="Current Omega2 temperature: " + str(temperature))

Finish the program with

if __name__ == '__main__': __main__()

and we’re done. You can download this edited and shortened

version of main.py at

https://github.com/wdonat/jumpstarting_onion/blob/­ master/Chapter3/main.py

The other two files are hosted there as well. So what does this program do? As I said earlier, it uses the

oneWire and temperatureSensor files to communicate with the sen- sor and create an object that we can interact with and read. In that sense, think of those two files as if they were Arduino librar- ies you had to install. After we declare our Twitter keys and authorizations, Twy- thon has a simple update_status() function that takes a string (or strings) as an argument and posts to your Twitter feed. To test

The Tweetin’ Onion 33 it, make sure you’re in your OnionTweetTemp directory and that all three files are also there. Then just run

python main.py

Wait for a few moments and then check your Twitter dash- board. You should see something like Figure 3-5.

FIGURE 3-5: Success!

If it didn’t work, double-check your keys and authorization tokens. I’ve read about more than a few app developers who even had to regenerate these a few times before they could get their applications to authenticate and run correctly. Once that’s done, congratulations! Your Omega2 can now read from an external sensor and let you know about it via Twit- ter—the very essence of what the IoT is about! This is obviously a basic implementation of this functionality; to improve it, I suggest adding things like a loop, letting it tweet every hour, for instance. Or, even better, continuously monitor the temperature, and if it changes more than a set amount over a set period of time, tweet about it. In our last chapter, we’re going to put our Omega2 on a mobile robotic platform and allow it to roam free!

34 Jumpstarting the Onion Omega2 4 The Photovore

I’ve been interested in light-following robots, or photovores (“light-eaters”), as they’re called, ever since I saw my first BEAM robotic creations. BEAM robots use elements of biology, elec- tronics, art, and mechanics to make realistic mechanical crea- tures—a photovore would fit perfectly into the right ecosystem. At its simplest, a photovore uses photoresistors to “look” for the brightest light in the area and then moves in that direction. Many photovores are powered by solar cells, so it’s in their best interest to find the brightest spot around. Once they find it, they sit and recharge until the light moves, and then they follow it again, repeating the process. It’s possible to replicate this light-following behavior with your Omega2, using a few photoresistors, an analog-to-digital converter, and a small robotics platform. I think it’s a good proj- ect, because even if you don’t plan on making your Onion mobile, you’ll understand the process of reading and reacting to external sensors, which again harks back to the O2’s IoT origins. PARTS For this project you’ll need a few extra parts in addition to your Onion. You’ll be using the power dock and the relay expansion board we played with earlier. You’ll need four photoresistors (Figure 4-1), which we’ll use to measure light levels. You’re going to need an ADS1115 16-bit ADC breakout board, available from either Adafruit or Amazon (Figure 4-2). This board is necessary because the Onion does not have an onboard analog-to-digital converter chip, which means that without a little help, you won’t be able to read the values coming from the photoresistors. You’ll also need a few jumper wires, four 4.7KΩ resistors (or about that value), a breadboard (or several), and lastly, you’ll need some sort of mobile robotics platform.

FIGURE 4-1: Photoresistor

FIGURE 4-2: ADS1115 ADC board

36 Jumpstarting the Onion Omega2 If you’ve read my book on the micro:bit, you may be aware that I really like DFRobot’s Turtle platform (Figure 4-3) as an experimental base for small robots like this one. It’s not particu- larly expensive, and it’s easy to connect its motors to whatever platform—Arduino, Omega2, micro:bit—you may happen to be playing with at the time.

FIGURE 4-3: DFRobot’s Turtle platform

THE VOLTAGE DIVIDER Before we build the actual robot, let’s look at how we read the values from the photoresistors. A photoresistor is a semiconductor that changes its resis- tance depending on the amount of light falling on it. The easiest way to set it up is as part of a voltage divider, in series with a regular resistor (Figure 4-4).

FIGURE 4-4: Voltage divider

The Photovore 37 If you’d like to try this without your Onion, it’s an easy circuit to create and play with. On a breadboard, place a resistor and a photoresistor in series. Connect the positive leg of a voltage source, such as a 9V battery, to the outer leg of the photoresis- tor. Connect the negative leg of the power to the outer leg of the resistor. Finally, connect a wire to the junction between the photoresistor and the resistor. You should end up with a setup similar to the one shown in Figure 4-5.

FIGURE 4-5: Voltage divider setup

Now connect your multimeter to the two wires coming from the breadboard and set it to measure resistance. Wave your hand back and forth over the photoresistor, and you should be able to watch the value of the resistance change as you do. In our case, we’ll substitute our photoresistor for R1, and R2

will be our 4.7KΩ resistor. Vin will be 3.3 volts from the Omega2,

and Vout is what we’ll measure. As the resistance changes with

the light, the value of Vout will change, increasing as the light increases. If we were to put the photoresistor in the place of R2,

Vout would decrease as the light increased. That’s how our photovore will work: we’ll space four photoresis- tors around the perimeter of the bot’s body, and periodically measure

38 Jumpstarting the Onion Omega2 the light at each one. If one shows more light (has the highest value returned) than the others, we’ll move the bot in that direction.

HARDWARE SETUP Now that you know the theory behind it, let’s set up the photo­ vore. Again, I’ll be using the Turtle as the platform, but feel free to use another platform if you have one. First, you’ll want to set up your photoresistors, either on individ- ual breadboards spaced around the perimeter or spaced evenly at the corners of one large one. The idea is to space them as far apart as possible and facing in four different directions. I used a half-sized breadboard and stuck it on top of the batteries used to power the motors, and then I placed the resistors at the four corners of the board. Since they’re flexible, you can then aim them in any way you like. Try to aim them so each is pointing in a completely dif- ferent direction, but avoid facing them directly forward, back, and right and left. Rather, try to face them diagonally; if you think of the front of the bot as North, face the photoresistors toward Northeast, Northwest, Southeast, and Southwest (Figure 4-6). This placement will allow the bot to “track” the light, zeroing in on light sources.

FIGURE 4-6: Placement of photoresistors

The Photovore 39 Once the photoresistors are placed, add a series resistor to each one the way we did in the preceding section. Using the breadboard’s ground and power lines, connect the 3.3V pin on your Onion to the breadboard, and then connect that to each individual photoresistor. Connect the O2’s GND pin to the bread- board and then connect that ground to each individual resistor (Figure 4-7).

FIGURE 4-7: Connecting the photoresistors

Now plug your ADS1115 chip into your breadboard. You’re going to use eight jumper wires to connect it to your bot’s cir- cuitry—four going to the Omega2, and four to the four photore-

sistor assemblies. Using Figure 4-4 as your template, connect Vout from the left-rear photoresistor assembly to pin A0, connect

40 Jumpstarting the Onion Omega2 Vout from the right-rear assembly to pin A1, and connect Vout from the front-right and front-left assemblies to pins A2 and A3, respectively.

Now, using the other four jumper wires, connect the VDD and GND pins on the ADS1115 to the 3.3V and GND rails on your breadboard. Then connect the SCL pin on the ADS1115 to pin 4 on the Onion, and connect the SDA pin on the ADS1115 to pin 5 on the Onion. The last thing you’ll need to do with your ADS1115 is connect a small jumper wire from the ADDR pin to the GND pin. The ADS1115 can have four different I2C addresses, allowing you to use up to four of them at a time. By connecting the ADDR pin to GND, you’re giving it the I2C address of 0×48. Finally, you’ll need a power source for your Omega2 and one for your motors. This is one of the advantages of the external relay board; you can use a much larger power supply for your motors than your Onion could handle. I have a battery holder that holds five AA batteries, permanently attached to my Turtle, wired to the onboard switch. As for the Onion’s power, you can get small lithium polymer (LiPo) batteries pretty inexpensively from online vendors such as Adafruit and SparkFun; just make sure when you order that you get a battery with a 2-pin 2mm JST-H connector, which fits the plug on the Onion power dock expansion board. One nice thing about the power dock is that it will charge the battery for you if the microUSB plug is connected. To connect the motors to the relay board, just remember that the relays are essentially switches that the O2 is flipping. The IN for each relay should be from the battery source, and the OUT should go directly to the motors. When the relay is OFF, the motor will get no power; when the Onion turns the relay ON, the motor will be connected to the power source. That’s how your bot should be connected. Check out the Fritzing diagram in Figure 4-8 to make sure the connections to the bot are correct, and you should end up with something look- ing like Figure 4-9.

The Photovore 41 FIGURE 4-8: Schematic of photovore

FIGURE 4-9: Assembled photovore

42 Jumpstarting the Onion Omega2 SOFTWARE AND CODE Once you’ve built your bot, the last thing to do is make sure you have the correct Python modules and then write the code. First, let’s make sure we have all the Python modules we need. Luckily, Onion has released modules that allow users to interact with all the different expansion boards, in both C and Python. To start with, let’s install the I2C library. In your terminal, enter opkg update opkg install pyOnionI2C opkg upgrade libonioni2c pyOnionI2C

That last line is sometimes necessary if your board’s software hasn’t updated quite right; mine was a bit wonky, and I was get- 2 ting errors whenever I tried to run any I C code. The upgrade line fixed the issues. Finally, you’ll also need to control the relay expansion, so install the necessary code with opkg install pyRelayExp

Once that’s loaded, we’re ready to start our program. The nice folks at ControlEverything (www.controleverything.com) have figured out and shared how to communicate with the ADS1115 board via I2C, so we’ll borrow from their Python code. All the code necessary to communicate with the relay expansion board is available in the Onion documentation (http://onion.io/docs), including examples and instructions for the various functions for turning relays on and off. I’ll go into more detail as we write the program; right now the important thing to note with the relay board is the position of the three slide switches at the top right (Figure 4-10).

The Photovore 43 FIGURE 4-10: Address jumper switches

Those switches determine the I2C address of the board. As with the ADS1115 board, you can change the address of the board, allowing you to daisy-chain up to eight different boards. Make sure the switches are all in the OFF position, which gives

your board the address of 0×27. Take note, as well, of the numbers of the relays; when you hook up your board, connect the right motor to relay 0 and the left motor to relay 1. This will ensure your code activates the correct motors to turn the right way. The basic concept behind the light-follower is thus:

1. Read the values from each of the four photoresistors, placed at the NW, NE, SW, and SE quadrants of the bot.

2. Determine which shows the highest value. If the highest-value photoresistor is in the front, briefly turn in that direction and then move forward. If the highest-value photoresistor is in the back, turn a bit longer in that direc- tion, and then move forward.

3. Repeat.

Remember that because we’re using relays to control the motors on our bot and not PWM, we can only make our motors go forward. (It also means that you can’t adjust the speed—they’re either fully ON or fully OFF.) This means that there’s no reverse;

44 Jumpstarting the Onion Omega2 if your bot is facing one way and you want to go the opposite way, you’ll need to spin around so you’re facing the correct direction.

Let’s write our program. Start a new file, calledlightFollower.py , on your O2. from OmegaExpansion import relayExp from OmegaExpansion import onionI2C import time import sys if len(sys.argv) != 2: print "Need offset" exit()

Here we’ve imported the necessary modules, and we’re also checking for the address of the relay board. Remember that we set this address by sliding all the switches to the OFF position.

Since this sets our board to an address of 0×27 (the int value of which is 7), we need to call our program with python lightFollower.py 7.

The 7 on the command line is passed into the program, where the sys.argv function reads it and learns the address (0x27, or 7) of the board we’re using in the program. Continuing:

# Initialize relay board addr = int(sys.argv[1]) relayExp.driverInit(addr) # Initialize I2C i2c = onionI2C.OnionI2C()

Here, both boards are initialized and are ready to go.

# Define movement functions # Relay0 = right motor # Relay1 = left motor def turnRight90(): relayExp.setChannel(addr, 1, 1) time.sleep(0.25) relayExp.setChannel(addr, 1, 0) return

The Photovore 45 The turnRight90() function works by using the setChannel() function, which takes as parameters the board’s I2C address, the channel (relay) address (1 in this case), and the state (ON or OFF—1 or 0) to which to set the relay. So to turn right, we send an ON signal to the left motor (remember, in order to turn right, you advance the left wheel), wait for a quarter of a second, and then turn it off again. If we need to turn for a longer time, we can simply call the function again.

def turnLeft90(): relayExp.setChannel(addr, 0, 1) time.sleep(0.25) relayExp.setChannel(addr, 0, 0) return def moveForward(): relayExp.setAllChannels(addr, 1) time.sleep(0.5) relayExp.setAllChannels(addr, 0) return

Now that we’ve defined our movement functions, let’s start the body of the program.

while True: # Get values from photoresistors # Right rear = RR data = [0xC4, 0x83] i2c.writeBytes(0x48, 0x01, data) time.sleep(0.5) data = i2c.readBytes(0x48, 0x00, 2) RR = data[0] * 256 + data[1] if RR > 32767: RR -= 65535

This is the function we can thank the folks at ControlEvery- thing for. To get values from the ADS1115, we first write an array

of bytes (data) to the chip at address 0x48. We then wait for half a second and read the response. Finally, we convert that response to an integer we can use. Because the ADS1115 has four channels

46 Jumpstarting the Onion Omega2 (A0, A1, A2, and A3), we specify the channel we’re reading and writing from with the 0xC4 part of the data array. That changes when we read from the other channels, but the rest of the code remains the same. Continuing:

# Left rear = LR data = [0xD4, 0x83] i2c.writeBytes(0x48, 0x01, data) time.sleep(0.5) data = i2c.readBytes(0x48, 0x00, 2) LR = data[0] * 256 + data[1] if LR > 32767: LR -= 65535 # Left front = LF data = [0xE4, 0x83] i2c.writeBytes(0x48, 0x01, data) time.sleep(0.5) data = i2c.readBytes(0x48, 0x00, 2) LF = data[0] * 256 + data[1] if LF > 32767: LF -= 65535 # Right front = RF data = [0xF4, 0x83] i2c.writeBytes(0x48, 0x01, data) time.sleep(0.5) data = i2c.readBytes(0x48, 0x00, 2) RF = data[0] * 256 + data[1] if RF > 32767: RF -= 65535

Now to determine the brightest value:

top = "NONE" if LF > RF and LF > LR and LR > RR: top = "LF" elif RF > LF and RF > LR and RF > RR: top = "RF" elif LR > LF and LR > RF and LR > RR: top = "LR" elif RR > LF and RR > RF and RR > LR: top = "RR"

The Photovore 47 And now that we’ve found where the light is, let’s move toward the light (sounds vaguely ominous, doesn’t it?):

# Determine which way to move if top == "RR": turnRight90() turnRight90() moveForward() elif top == "RF": turnRight90() moveForward() elif top == "LF": turnLeft90() turnLeft90() moveForward() else: turnLeft90() moveForward()

And that’s the whole program. It’s also available at https:// github.com/wdonat/jumpstarting_onion/blob/master/Chapter4/ lightFollower.py.

You’ll notice that the else statement at the end handles any unforeseen situations, like LF equaling RR or something equally bizarre; if that’s the case, the bot will turn a bit to the left, move forward, and then take another reading. Also note that if the light

is behind our bot, we call the turn function twice, so that it’ll turn all the way around and be facing the right way. To run your program, set your bot down on the floor, plug in your battery, and let it power up. Then go over to your desktop or laptop connected to the Onion’s network. Log in either via SSH or with the console, and in the terminal, enter

python lightFollower.py 7

Your bot should start roaming around, seeking out the bright- est light in the room. It will not stop, however, when it finds the light, so don’t be surprised when before long it just kind of goes

48 Jumpstarting the Onion Omega2 in a circle, since the readings from the photoresistors can vary quite a bit over time. There are a few things you can do to add to and improve this code. The first thing you may want to consider is “smoothing out” the readings from the photoresistors, since they seem to wiggle around quite a bit. This could be done by taking a few readings over the course of a second or two and averaging them out. Another thing to try would be accounting for scenarios where both resistors in the front, for example, read the same; in that case, the bot should just move straight forward. The Omega2 can also use a webcam; it might be interesting to see a live view of what the photovore sees. Since the Omega2 is already a web server, you could stream the video live if you wanted to. That concludes our introduction to the Onion Omega2. I hope I’ve managed to give you a good overview of this cool little board and everything it can do, and also given you a few ideas to go forward with its capabilities. Have fun with it, and I look forward to seeing what you come up with!

The Photovore 49