Monday, April 4, 2016

Swift and the BeagleBone Black

**** Update:  We have just built the first robot programmed with Swift and the SwiftyBones library.  You can read about it here:  http://myroboticadventure.blogspot.com/2016/05/the-first-robot-programed-in-swift-with.html  ****

Now that I have completed my three books on Swift (MasteringSwift, Mastering Swift 2 and Protocol Oriented Programming with Swift), I told my daughters that I would take a break from writing books for the summer.  My oldest told me that she wanted to start working on robots again.  At the age of ten, She is already a second-degree black belt, and an instructor in Tae Kwon Do so when she says she wants to do do something I generally listen.  So after a little discussion about what she wanted to do, we decided that we would pull out all of the robot parts and start working with our BeagleBone Blacks again.

I had to start off by doing some reading to catch up with everything that has happened over the past year and a half that spent writing.  In my reading I happened to stumble on the iacheived.it site that showed how to install Swift on the BeagleBone Black. I also found the SwiftyGPIO package (control the BeagleBone Black GPIO with Swift) that was featured on IBM’s Swiftpackage library.  So this got me thinking about being able to program our robots with Swift, now that sounds pretty exciting doesn’t it?

Note: This post and a most of the ones that show how to use Swift with the BeagleBone Black will be crossed posted between my Robotics Blog and my Swift programming blog.

The first part of this post will walk you through setting up your BeagleBone Black.  After we get the BeagleBone Black setup we will write some code that will let us control an LED with a button.  I know controlling a led with a button isn’t that exciting but we need to start somewhere and that really is like a “Hello World” application so lets get started.

Setting up our BeagleBone Black

The following list will walk you through setting up the BeagleBone Black.  Rather than writing out detail instructions I will provide links to the pages that I followed when I set up my boards.  Since I use a Macbook Pro, the instructions are for the Mac.  Sorry, but I do not have a Windows machine to mirror the steps on however the only Mac specific areas in these steps in where we copy the image over to the SD card and the Beagle Board site has a getting started page that may help anyone that uses Windows with these steps.  If you use the Beagle Board site, once you get the image on the SD card, you can skip to step 4 below.

1.  Get the latest Debian 8.3 image from Beagle Board’s site.  You can find the image here.
2.  We need to unzip the images.  We can do this using TheUnarchiver for Mac.
3.  Now we need to copy the image over to the SD card.  I would recommend using at least a 8 gig SD card.  Everything needed will take up 3.3 gig which will fit on a 4 gig card but you are not leaving yourself much extra space.  I use Pi Filler to copy the image onto the SD card.  Once installed, run the Pi Filler app and follow the on screen prompts.
4.  Once you have the image on the SD Card, go ahead and plug it into your BeagleBone Black and power it up.  
5.  If you are using a SD card greater than 4 gig, you will need to manually expand the file system since the image only uses 4 gig.  To do this you can following these instructions.  
6.  Now we are set to install Swift.  The instructions to do this are on the iachieved.it site.
7.  The last thing we need to do before we start to code is to get the SwiftyGPIO repository.  You can find the repository here.  Under the Sources directory you will find the file SwiftGPIO.swift file.  This is the file we will need to use with our code.

Now that our BeagleBone black setup, lets get ready to do some coding.  We will start by writing some code that will cause our LED to blink on and off.  We will then write a separate application to read the state of a button.  Finally we will combine the code to create an application that will turn the LED on and off with the button.  So lets get started.

Turning an LED On and Off

The first thing we need to do is to wire everything up.  When you do this wiring you will want to have the BeagleBone Black powered off.  The following diagram shows how we would wire a LED to our BeagleBone Black.  It is recommended that whenever we connect anything to the BeagleBone Black we should always disconnect the power.


   

We run a solder-less jumper from pin 1 of the P9 expansion header to the ground rail marked with the blue line on the breadboard and then take another solder-less jumper from pin 2 of the P9 expansion header to the power rail marked with the red line.  We will use these rails to provide power and ground for our LED and Button.

Now lets add the LED to our breadboard.  Connect the cathode end of the LED (shorter wire) to the ground rail of our breadboard and then connect the anode end of the LED (longer wire) to one of the other rows on our breadboard.

Now take a 100 OHM resistor and connect one end to the row on the breadboard that the LED is connected to and the other end of the resistor to another row on the breadboard.  Finally run a solder-less jumper from pin 12 of the P9 expansion header to the row that the 100 OHM resistor is connected too.  We are now set to power up the BeagleBone Black.

You will want to create a separate directory for each Swift project so lets begin by creating a directory named blinkyled and then change to that directory.  You will want to copy the SwiftyGPIO.swift file from the SwiftyGPIO package to this directory.

Copy the following code into a file named main.swift also in the blinkyled directory (the file needs to be named main.swift).

import Glibc

let gpios = SwiftyGPIO.getGPIOsForBoard(.BeagleBoneBlack)
var led = GPIO(name:"GPIO_60", id: 60)

led.direction = .OUT

while(true){
      print(“Changing”)
     led.value = (led.value == 0) ? 1 : 0
     usleep(150000)
} 

In this file we start off by importing the GLibc module.  In the next line we retrieve the list of GPIOs available for the BeagleBone Black.  Next we get a reference to GPIO_60 (pin 12 of the P9 expansion header).  You can see the GPIO ports listed here.

The next line configures the port direction for the GPIO port.  We can use GPIODirection.IN or GPIODirection.OUT here.  Now we create a while loop.  Within the while loop the first line prints a message to the console letting us know that we are changing the LED.  The next line checks the value of the LED and changes it causing the LED to blink.  A value of 1 turns the LED on and a value of 0 turns it off.  We then use the usleep function to pause before we loop back.

To compile this application we use the following command:

swiftc –o blinkyled SwiftyGPIO.swift main.swift 

This command uses the swift compiler to compile SwiftyGPIO.swift and main.swift and writes the output to the file named blinkyled.  We are now able to run our application.  If you attempt to run this without super user privileges the LED will not blink.  To access the GPIO ports you will need to run the application with sudo like this:

sudo ./blinkled 

If everything is connected correctly, the LED should blink on and off pretty quickly.  Now lets look at how we would check the state of a button.

Reading the state of a button

Now that we have the LED working lets look at how we would read the state of a button.  To begin with lets connect a button to our Beaglebone Black as shown in the following diagram.  Keep in mind that whenever we connect anything to the BeagleBone Black we should always disconnect the power.
   


In this diagram we add the push button to the breadboard.  You will want the button to straddle the middle section as show in the previous image.  Using a solder-less jumper, connect the power rail of your breadboard to one end of the button.  Next connect the same end of the button to the ground rail of your breadboard using the 10K pulldown resistor.  Finally connect the other end of the button to pin 23 of the P9 expansion header.  

Now lets power up the BeagleBone Black and write our code to read the state of the button.  Create a directory named button and copy the SwiftyGPIO.swift file to this directory.  Next create a file named main.swift in the button directory and add the following code to it.

import Glibc

let gpios = SwiftyGPIO.getGPIOsForBoard(.BeagleBoneBlack)
var button = GPIO(name: "GPIO_49",id: 49)
button.direction = .IN
while(true){
      if button.value == 1 {
           print("Pressed")
      }
      usleep(10000)
}

In this file we start off by importing the GLibc module.  In the next line we retrieve the list of GPIOs available for the BeagleBone Black.  We then get a reference to GPIO_49 (pin 23 of the P9 expansion header).  

The next line configures the port direction for the GPIO port.  We can use GPIODirection.IN or GPIODirection.OUT here.  Notice in the LED example we used GPIODirection.OUT however in this example we used GPIODirection.IN.  Next we create a while loop.  Within the while loop we check the state of the port and if it is high (value of 1) we print the message “Pressed” to the console letting us know the button is pressed.  We then use the usleep function to pause before we loop back.

To compile this application we use the following command:

swiftc –o button SwiftyGPIO.swift main.swift 

This command uses the swift compiler to compile SwiftyGPIO.swift and main.swift and writes the output to the file named button.  We are now able to run our application.  The following command will run our application.

sudo ./button 

If everything is connected correctly, when you press the button you should get a message printed to the console.  Now lets put our LED and Button examples together to turn the LED on whenever the button is pressed.

Putting it together


The following diagram shows how we would wire the LED and Button to our BeagleBone Black (notice no changes from the previous two diagrams just combined them).


The following code will go in our main.swift file:

import Glibc

let gpios = SwiftyGPIO.getGPIOsForBoard(.BeagleBoneBlack)
var button = GPIO(name: "GPIO_49",id: 49)
var led = GPIO(name:"GPIO_60", id: 60)

button.direction = .IN
led.direction = .OUT

while(true){
      if button.value == 1 {
            print("Pressed")
           led.value = 1
      } else {
           led.value = 0
      }
      usleep(10*1000)
} 

When you compile this, don’t forget to include the SwiftyGPIO.swift file.  When you run the application, the LED should turn on when you press the button and turn off when you release it.  The following image shows how my wiring looks in real life



Notice the sporty new BB8 case I made for my BeagleBone Black, pretty cool huh?  Not to mention that BB8 and BBB kind of go together.  Just printed it on my new 3D printer.  I will be talking about the printer in a post very soon and will include links to some of the stuff I have printed and designed including the BB8 case.  I am thinking about making a R2D2 case for my other BeagleBone Black.

If you are new to Swift, I will be discussing some of the basics while I am showing how to use Swift with the BeagleBone black however my assumption is you will have at least a basic understanding of Swift.  I will also be writing more blog posts that are specific to Swift on Linux on my Swift programming blog however if you are really interested in the language I would recommend my Mastering Swift 2 and Protocol Oriented Programming with Swift books.  Please keep in mind that those books talk about using Swift on the Mac however most of the language concepts themselves are the same whether you are using Swift on a Mac or with Linux.

Now that my books are done, you should start seeing a lot more posts on both my robotic and swift blogs.  I do have a question for anyone that might be able to answer: Does anyone know when/if we will see an update for the BeagleBone Black?  I am not talking about the X15 that looks like it is going to be pretty expensive.  I am looking more for an update to the BeagleBone black that will have roughly the same price point.




Sunday, February 8, 2015

Mastering Swift

This post does not have anything to do with robotics but I wanted to announce my new book on this blog as well as my other blogs.  A couple months back the publisher of my first book, Packt Publishing, asked me if I would be interested in writing a book on the Swift programming language.  I quickly agreed and went to working writing it.  This book will be titled Mastering Swift.

While most books on Swift programming focus on developing applications for iOS devices, this book is going to be a bit different.  We are going to focus on teaching the Swift language itself.  This means that all 350+ pages will be dedicated to helping you learn how to effectively write Swift code no matter what type of application you are writing or platform you are targeting. 

If you are a developer that learns best by looking at and working with code, then this book will be for you.  It starts off by giving the basics of Swift and slowly progresses to more advice topics like concurrency, Objective-C interoperability, networking and design patterns.

Over the past couple of months I have submitted the first drafts for the first ten chapters and will begin work on Chapter 11 next week.  As I continue to work on this book I will provide updates on this blog and on my twitter account.  I hope that those of you that are interesting in learning Swift will continue to look for updates.  As the book gets closer to publication, I hope to provide additional details about it.

Click this link to visit Packt Publishing page to preorder the book and to also get more details about the book.  I must say that I am really excited about this book.  Granted I am a bit bias since I am the author, but I believe this book will be one of the premiere books for learning the Swift programming language.  We are going to cover a lot of details that most other books are unable to cover because they are focusing on how to write applications for a specific platform while this book will be all about the Swift language itself. 


While I believe I can write a great book on the Swift programming language, what really has me excited about the book and why I believe this book will be special is the incredibly awesome team that Packt Publishing has to assist me with it.  So if you are a developer that wants to learn the Swift programming language or a Swift developer that wants to take your skills to the next level check out my Mastering Swift book, it may be the book you have been searching for. 

Sunday, August 31, 2014

IoT: Displaying the temperature from the BeagleBone Black on my iPhone

In the first post of this series I used Javascript to read a TMP36GZ temperature sensor and write the current temperature to the console.  In the second post I used the Restify library with Javascript to create a rest based web service that would send the current temperature to a remote client upon request.  In this post I will access that web service to display the temperature on my iPhone using the RSNetworking library.

Let begin by reviewing how we wired up the TMP36GZ temperature sensor to the BeagleBone Black.  Here is the wiring diagram:



Next lets review how we developed the REST Web Service that will respond to client requests for the current temperature.  Note:  I am making one change to the code, from my last post, so the REST service returns a valid JSON object. 

The first thing we need to do is to setup a directory structure that contains the node.js modules needed to run the service.  I used the following steps to get the structure/modules set up (this is based off of the latest Debian image 2014-05-14):

1.  Start off within our home directory.  In Linux the ~ directory is the users home directory.
cd ~

2.  Create a work directory and change to that directory
mkdir temperature
cd temperature

3.  Install the restify module
npm install restify

4.  Copy the bonescript module to our working structure
mkdir node_modules/bonescript
cp /var/lib/cloud9/static/bonescript.js node_modules/bonescript/

At this point you should still be in the temperature directory and both the restify and bonescript modules should be located in the ~/temperature/node_modules directory.   This will let our application use these two modules.

From the ~/temperature directory, create a file called tempServer.js and put the following code in it.

var b = require('bonescript');
var rest = require('restify');

var ip = '0.0.0.0'
var port = '18080'
var path = 'temperature'
var tempPin = 'P9_38';
var currentTemp = 0.0;

b.analogRead(tempPin, readTemperature);
setInterval(function() {b.analogRead(tempPin, readTemperature)},30000);

var server = rest.createServer({
   name : "Temperature"
});

server.get({path : path , version : '0.1'}, getTemperature);

server.listen(port,ip, function() {
   console.log('%s listening at %s ',server.name, server.url);
});

function getTemperature(req, res, next) {
   var key = "temperature";
   var tempResponse = '{"temperature":"' + currentTemp + '"}';
   res.send(200, JSON.parse(tempResponse));
}

function readTemperature(aRead) {
   console.log("Geting Temp");
       var x = (aRead.value * 1800/1024);
       var cel = 100*x -50;
       var fah = (cel *9/5)+32;
   currentTemp = fah;
}

This code begins by loading both the bonescript and restify modules that are needed for this application.  We then set the following variables:

ip:  The IP address of the interface to bind too.  By using 0.0.0.0 the server will bind to all available interfaces (this is what we want).
port:  The port to bind too.  Typically web servers bind to port 80 but we do not want to take up that privileged port (and it also requires root access to bind to ports below 1024) so we will use 18080 for our service.
path:  The URL path for our service. 
tempPin:  The pin that will be connected to the TMP36GZ temperature sensor.
CurrentTemp:  Will contain the current temperature.  This will be updated every 30 seconds.

After we set the variables, we then read the temperature using the analogRead function from the bonescript module.  This function will read the voltage from the tempPin and then call the readTemperature function when it has the voltage.  The readTemperature function calculates the current temperature based on the voltage of the pin and stores that temperature into the currentTemp variable.

We use the Javascript setInterval function to call the readTemperature function every 30 seconds to update the currentTemp variable.

Now that we have the temperature and updating it every 30 seconds, we need to create our web service that will respond to our requests.  We start off by creating a server object using restify’s createServer function. 

Next we define what services we wish to offer though this server object.  In this case we only have one service.  This service will respond to HTTP GET requests so the get function from our server object is used to define the service.  This service will listen on the path defined in our path variable and when a request comes in it will call the getTemperature function.

Finally we till the server to listen on the port and interface that we defined in the variables earlier.

The getTemperature function simply creates a JSON object that contains the current temperature and uses the send function from the res response object to send the object back to the client that requested it.  This is where I made the code change from my previous post.  To create the JSON object, I first create a string that contains the response that I want to send back to the client and I then use JSON.parse() function to create a valid JSON object.

Now lets look at how we would write the iOS client application to retrieve the temperature from the BeagleBone Black’s web service.  We will be writing the client app in Swift (Apple’s new development language) and will use the RSNetworking library.  RSNetworking is a network library written entirely in the Swift programming language.  RSNetworking is built using Apple’s powerful URL Loading System.  The main design goal of RSNetworking is to make it easy and quick for developers to add powerful asynchronous networking requests, to their applications written in Swift.  As a disclaimer, I created and maintain the RSNetworking library. 

The first thing we will need to do is to download the RSNetworking library from Github and include the library in our project. 

In the MainStoryboard of our project we will add a UILabel (to display the temperature) and a UIButton (to get the temperature from the BeagleBone Black).  Here is a screen shot of how UI is laid out.



Now lets look at the code that will retrieve the temperature from the BeagleBone Black’s Web Service and display it on the screen when the button is pressed.

import UIKit

class ViewController: UIViewController {
   
    @IBOutlet var tempDisplay : UILabel!
                           
    override func viewDidLoad() {
        super.viewDidLoad()
       }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
       }
    
    @IBAction func getTemp(AnyObject) {
        var rsRequest : RSURLRequest = RSURLRequest();
        var url : NSURL = NSURL.URLWithString("http://10.0.1.30:18080/temperature");
        rsRequest.dictionaryFromJsonURL(url, completionHandler:{(response : NSURLResponse!, responseDictionary: NSDictionary!, error: NSError!) -> Void in
            if error == nil {
                println(responseDictionary);
                var temp: Double! = responseDictionary["temperature"]?.doubleValue!
                let displayStr : NSString = "".stringByAppendingFormat("%.2f", temp!)
                self.tempDisplay.text = displayStr
               
            } else {
                //If there was an error, log it
                println("Error : \(error)")
            }
        })
    }
}

The getTemp() function is tied to the UIButton.  When the button is pressed the applications accesses the Web Service on the BeagleBone Black and retrieves the temperature.  If there were no errors it displays the temperature in the UILabel.  So lets look at the getTemp() function.

We begin by creating an instance of the RSURLRequest class.  We then create an instance of NSURL using the URL for our Web Service.  We then use the dictionaryFromJsonURL() function from the RSURLRequest class to send our request to the BeagleBone Black. 

We pass a block (of code) to the dictionaryFromJsonURL() function.  This block of code verifies that we did not receive any errors and if no errors were received it converts the temperature that was received to a Double values and displays the temperature, with the precision that we want, in the UILabel.  If there were errors we simply log them.

That is all there is to creating our first IoT service with the BeagleBone Black.