Sunday, April 10, 2016

IPv6 over Bluetooth on the BeagleBone Black

When we remotely connect to a BeagleBone Black we generally SSH into them over a WiFi or wired network.  There are several drawbacks to using a WiFi or wired network connection with a BeagleBone Black especially with robotic projects.  In this post I will demonstrate how we can use 6LoWPAN over Bluetooth Smart to connect two BeagleBone Blacks together.  This will allow us to use standard Internet technologies like SSH or HTTP over a Bluetooth connection. 

6LoWPAN (IPv6 over Low Power Wireless Networks) for Bluetooth was introduced with the Bluetooth Smart 4.2 specifications.  It is defined by RFC7668. 6LoWPAN is a software specification that will work with most Bluetooth 4.0 adapters therefore we do not need a special Bluetooth 4.2 adapter to use it.  We also do not need any additional network infrastructure, beside the Bluetooth adapters, like we do with wired and WiFi networks.  Bluetooth smart technologies also use significantly less power as compared to USB WiFi adapters.

One thing to note is I am using two BeagleBone Blacks for this post however these instructions will also work with Ubuntu 15 computers (or most other Linux based computers) if you are using a 4.4.X or newer kernel.  You can check your kernel version by issuing the following command:

uname -r

In this post I will walk though installing a new kernel on the BeagleBone Black.  If you are using Ubuntu 15 and have an older kernel, you will need to upgrade it.  This Google search should return a number of sites that will walk you though the upgrade process.

For this post I am starting with the standard Debian 8.3 image on a 16 gig SD card.  When I attempted the steps described in this post with a 4 gig SD card I ran out of room so you will need to use at least an 8 gig SD card.  The first step will be installing a new kernel.


Installing a new kernel on your BeagleBone Black (pre-built 4.4.6-bone6 kernel)

If you attempt to use 6LoWPAN with the standard kernel that comes with Debian 8.3 the two devices appear to connect however the connection will drop after a few seconds.  The problem is fixed in the 4.4.X or newer kernels.  The kernel that I am using is the pre-built 4.4.6-bone6 kernel.  Any of the 4.4.X or newer kernels should work but I can confirm that the 4.4.6-bone6 kernel does work. 

When I first followed the steps define in this post I already had Swift installed on both of my BeagleBone Blacks as described in this post and the kernel installed correctly with the Bluetooth drivers.  After working with this a little bit, I had to reset one of my BeagleBone Blacks and I ended up installing the new kernel without installing Swift first.  When the installation of the new kernel was complete and my BeagleBone Black came back up, after the reboot, my Bluetooth adapters no longer worked.  In the logs I saw that there was an issue loading the Broadcom drivers for the adapter.  It took me two days of experimenting but I finally figured out that if I installed Swift first then after the new kernel was installed my Bluetooth adapters worked properly.  I believe it has to do with installing libicu-dev and clang-3.6 with Swift. 

If you have a problem with your adapter after upgrading the kernel you may want to start over and use the following steps to install libicu-dev and clang-3.6 prior to upgrading your kernel.

sudo apt-get install libicu-dev
sudo apt-get install clang-3.6
sudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-3.6 100
sudo update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-3.6 100

When we install the 4.4.6-bone6 kernel we also need to install the headers.  The following command will install both the kernel and the headers.

apt-get install linux-headers-4.4.6-bone6 linux-image-4.4.6-bone6

Once the new kernel is installed we will need to restart the BeagleBone Black.  Once it has restarted we can begin configuring the 6LoWPAN connection on both the master and slave devices.

Configure the 6LoWPAN Master

The 6LoWPAN Master is the device that listens for incoming connections.  Create a new file named bluetoothMaster.sh on the device you wish to use as the master and put the following code in it.

modprobe bluetooth_6lowpan
echo 1 > /sys/kernel/debug/bluetooth/6lowpan_enable
hciconfig hci0 leadv

In this script we begin by loading the bluetooth_6lowpan module.  We then echo a 1 into the 6lowpan_enable file.  This will enable 6LoWPAN on the device.  Finally we use the hciconfig hci0 leadv command to begin advertising. 

We will also need another script that will setup the network once the client connects.  Let's call this script setNet.sh but we will want to wait to add the code to this script until the first client connects.  This will make it easer to get the IP Address that we will define for our interface.

Configure the 6LoWPAN Slave

The 6LoWPAN Slave is the device that connects to the master.  Create a new file named bluetoothSlave.sh and put the following code in it.

modprobe bluetooth_6lowpan
echo 1 > /sys/kernel/debug/bluetooth/6lowpan_enable
hcitool lecc 98:58:8a:06:db:9b
echo "connect 98:58:8a:06:db:9b 1" > /sys/kernel/debug/bluetooth/6lowpan_control

Note:  Change the 98:58:8a:06:db:9b in this script to the Bluetooth MAC address of the Bluetooth adapter on the master device.  To get the MAC address for a Bluetooth adapter you can use the hcitool dev command on the device that the Bluetooth adapter is connected to. 

In this script we begin by loading the bluetooth_6lowpan module and enabling 6lowpan as we did in the bluetoothMaster.sh script.  We then use the hcitool command with the lecc option to connect to the master.  The address in the hcitool command is the MAC address for the Bluetooth adapter on the master.   Finally we echo “connect {MAC address} 1” to the 6lowpan_control file which will enable the 6LoWPAN connection between the master and slave devices.

Testing the 6LoWPAN connection

Now that we have a 6LoWPAN connection between our two devices we can test the connection by attempting to ping one device from the other.  The first thing we need to do is to get the IPv6 addresses assigned to each device. We can do this by running the following command on each device.
ifconfig bt0

You should see something like this:

bt0       Link encap:UNSPEC  HWaddr 98-58-8A-FF-FE-06-DB-9B-00-00-00-00-00-00-00-00 
          inet6 addr: fe80::9a58:8aff:fe06:db9b/64 Scope:Link
          UP POINTOPOINT RUNNING MULTICAST  MTU:1280  Metric:1
          RX packets:13 errors:0 dropped:0 overruns:0 frame:0
          TX packets:9 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1
          RX bytes:527 (527.0 B)  TX bytes:321 (321.0 B)

If this were the bt0 address on my master device then on the slave device I would run the following command:

ping6 –I bt0 fe80::9a58:8aff:fe06:db9b

If the ping works then our connection is correctly setup however addresses with the fe80 prefix are link-local address that really isn’t that useful except for testing the connection.  Lets see how we could generate a non link-local address and assign it to the bt0 interface.

Generating and setting an IPv6 address

Before we generate our own IPv6 address, lets look at how the OS generated the link-local address.  In the example above the address generate when the interface came up is: fe80::9a58:8aff:fe06:db9b .  The Bluetooth MAC address for the adapter is: 98:58:8a:06:db:9b.  Do you notice anything similar between the IPv6 address assigned to the bt0 adapter and the MAC address of the Bluetooth adapter?

As you probably saw, the OS uses the Bluetooth MAC address to generate the IPv6 address.  Lets look at how the IPv6 address was generated.  We start off with the MAC address and add an 0xFF and 0xFE between the third and forth octet to give us 98:58:8a:ff:fe:06:db:9b.  We then OR 0x02 to the first octet to give us 9a:58:8a:ff:fe:06:db:9b.  We can now covert this to standard IPv6 notation where we group four hexadecimal digits together and separate the groups by a colon.  This will give us  9a58:8aff:fe06:db9b.   Finally we need to add a prefix.  The OS used the fe80 prefix that is reserved for link-local connections which gave us the fe80::9a58:8aff:fe06:db9b .   

For the IPv6 address that we will assign to the bt0 interface we will use the 2001:db8 prefix that is reserved for documentation.  This will give us the following address: 2001:db8::9a58:8aff:fe06:db9b.  Since the OS generates the link-local address, rather than going through these calculation steps we could simply take the link-local address and remove the fe80 prefix and add the prefix we wish to use.

Now that we have an address we will want to assign it to the bt0 interface.  To do this we will add the following line to the setNet.sh script on the master:

ifconfig bt0 inet6 add 2001:db8::9a58:8aff:fe06:db9b/64

Remember to replace 2001:db8::9a58:8aff:fe06:db9b with the address for your device. 

We will also want to add the following two lines to the end of the bluetoothSlave.sh file on the slave device:

sleep 2 //pause to make sure the bt0 interface is up
ifconfig bt0 inet6 add 2001:db8::5ef3:70ff:fe75:b1d6/64

Remember to replace the 2001:db8::5ef3:70ff:fe75:b1d6 address with the one for your slave.

The final scripts

Before we test everything lets look at the final versions of our scripts.  On the master we have two scripts.  These are named bluetoothMaster.sh and setNet.sh.  The bluetoothMaster.sh should contain the following code:
 
modprobe bluetooth_6lowpan
echo 1 > /sys/kernel/debug/bluetooth/6lowpan_enable
hciconfig hci0 leadv

The setNet.sh should contain the following code:

ifconfig bt0 inet6 add 2001:db8::9a58:8aff:fe06:db9b/64

Remember to replace the IPv6 address in this script with the correct address for your device.

The slave should contain one script named bluetoothSlave.sh which should contain the following code.

modprobe bluetooth_6lowpan
echo 1 > /sys/kernel/debug/bluetooth/6lowpan_enable
hcitool lecc 98:58:8a:06:db:9b
echo "connect 98:58:8a:06:db:9b 1" > /sys/kernel/debug/bluetooth/6lowpan_control

sleep 2 //pause to make sure the bt0 interface is up
ifconfig bt0 inet6 add 2001:db8::5ef3:70ff:fe75:b1d6/64

In this script your will want to replace the  98:58:8a:06:db:9b with the Bluetooth MAC address of your Master device and replace the 2001:db8::5ef3:70ff:fe75:b1d6  with the IPv6 address for your slave device.

Putting it all together

Now that we have our scripts lets test everything and see how it works.  Go ahead and reboot both devices to clear everything.  When the master device comes up run the bluetoothMaster.sh script.  After the bluetoothMaster.sh finishes, run the bluetoothSlave.sh script on the slave device.  After the bluetoothSlave.sh finishes run the setNet.sh script on the master.  

After all three scripts complete the 6LoWPAN connection should be up.  We can test this with the ifconfig bt0 command.  If all is well we should see that the bt0 interface is up on both devices with both the link-local IPv6 address and the IPv6 address that you assigned it.  We can now test the connection by using ssh to remotely connect to one device from the other.



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 (MasteringSwiftMastering 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.