Wednesday, January 4, 2017

Mastering Swift 3 for Linux

My new book, Mastering Swift 3 for Linux has just been released.  While most books on Swift are written to introduce the language using Apple’s development tools, this book is written for the developer that wants to use Swift on the Linux platform. 

I have always thought that a developer cannot master a programming language without a good understanding of the basics.  With that philosophy in mind this book starts with the basics of the Swift language before moving into more advance features and concepts. The first five chapters will introduce the Swift programming language and will give the reader a good understanding of the Swift programming language.  The second half of the book will cover more advance topics such as concurrency, network development, using C libraries with Swift and memory management including strong reference cycles.

This book also has a chapter dedicated to using Swift on Single-Board Computers.  The first half of this chapter will show the reader how they can use Swift to interact with external devices like LEDs, buttons and temperature sensors. The second half of the chapters shows the reader how they can build and program an autonomous robot using Swift and the BeagleBone Black.

Here is a description of what is covered in each chapter of the book:

Chapter 1Taking the First Steps with Swift, gives a brief introduction to the Swift language. It also covers the basic Swift language syntax and discuss proper language styles.
Chapter 2Learning About Variables, Constants, Strings, and Operators, will show how to use variables and constants in Swift. It will also discuss the various data types and how to use operators in Swift.
Chapter 3Using Swift Collections and the Tuple Type, will look at how we can use the Swift collection types to store related data. These collection types are the array, set and dictionay types. 
Chapter 4Control Flow and Functions, will cover control flow and functions in Swift. It is essential to understand the concepts in this chapter before going on. Every application that we write, beyond the simple Hello World applications, will rely very heavily on the control flow statements and functions.
Chapter 5Classes and Structures, will look at what makes Class and Structures similar and what makes them different. We'll also look at access controls and object-oriented design. The chapter also covers memory management in Swift.
Chapter 6Using Protocols and Protocol Extensions, will cover both protocols and protocol extensions in detail since protocols are very important to the Swift language, and having a solid understanding of them will help us write flexible and reusable code.
Chapter 7Protocol-Oriented Design, will cover the best practices of Protocol-Oriented Design with Swift. It will be a brief overview of what is covered in my Swift 3 Protocol-Oriented Programming (POP) book.
Chapter 8Writing Safer Code with Error Handling, will look at Swift’s error- handling features. While we are not required to use this feature in our custom types, it does give us a uniform manner to handle and respond to the error. 
Chapter 9Custom Subscripting, will discuss how we can use custom subscripts in our classes, structures, and enumerations. Subscripts in Swift can be used to access elements in a collection. We can also define custom subscripts for our classes, structures, and enumerations.
Chapter 10Using Optional Types, will explain what optional types are and the various ways to unwrap them. For a developer who is just learning Swift, optional types can be one of the most confusing items to learn.
Chapter 11Working with Generics, will explain how Swift implements generics. Generics allow us to write very flexible and reusable code that avoids duplication.
Chapter 12Working with Closures, will teach us how to define and use closures in our code. Closures in Swift are similar to blocks in Objective-C except that they have a much cleaner and easier way of using syntax. This chapter concludes with a section on how to avoid strong reference cycles.
Chapter 13Using C Libraries with Swift, will explain how we can link and use standard C libraries with our Swift applications.  This gives Swift developers access to all the same libraries that Linux C developers have access too.  Knowing how to use C libraries with Swift is essential for any developer that wants to develop Linux apps with Swift
Chapter 14Concurrency and Parallelism in Swift, will show how to use Grand Central Dispatch to add concurrency and parallelism to our applications. Understanding and knowing how to add concurrency and parallelism to our apps can significantly enhance the user experience.
Chapter 15Swift's Core Libraries, will be a chapter on using the Swift core libraries, including reading/writing files, network primitives, and JSON parsing.
Chapter 16, Swift on single-board computers, will show how we can use Swift for IoT and robotic projects using a single-board computer.  This chapter will feature the BeagleBone Black and the Swifty Bones library.
Chapter 17Swift Formatting and Style Guide, will define a style guide for the Swift language that can be used as a template for enterprise developers who need to create a style guide, since most enterprises have style guides for the various languages that they develop in.
Chapter 18Adopting Design Patterns in Swift, will show you how to implement some of the more common design patterns in Swift. A design pattern identifies a common software development problem and provides a strategy for dealing with it.


This book is written in an example-based approach where each topic covered is backed by examples which are designed to reinforce the topic covered and show how to implement it within the reader's own code. 

You can purchase the book from Amazon.

Thursday, June 23, 2016

Swift on the Next Thing C.H.I.P

I just received two Next Thing C.H.I.Ps.  The C.H.I.P is a single-board computer, similar to the BeagleBone Black and Raspberry Pi but has a starting price of only $9.00.  If you would like to do robotics or other DIY projects and you are on a budget, the C.H.I.P may be the controller that you are looking for.

The C.H.I.P is loaded with features like built in WiFi B/G/N, Bluetooth 4.0, 1GHz processor and 4GB storage.  The C.H.I.P is also an open hardware platform and you can get information about the hardware on the Next Thing Co hardware github page.

Obviously the first thing I wanted to do once I received the C.H.I.Ps was to get Swift installed on it.  This post will walk you though how I setup the C.H.I.P  and how I installed Swift.  I will end this post by writing a Swift application that will turn an LED on and off.

Flashing the C.H.I.P

The first thing I needed to do upon received the C.H.I.Ps was to flash them.  This is done by going to the C.H.I.P flasher page and following the instructions.  One note: You will need to use the Chrome browser since the flasher is a chrome app.  I put the 4.4 headless version on one of the C.H.I.Ps and the 4.4 GUI version on the other.  Once flashing is complete I needed to configure the wireless network adapters on both of the C.H.I.Ps.

Configuring the Network
This is pretty easy to do with the C.H.I.P that has the HDMI adapter plugged into it (the one that I put the GUI version of the OS on) because I could simply plug in a USB keyboard/touchpad and connect it to a HDMI monitor.  I use the Logitech K400 but the K400+ should also work but I have not tested it. 

For the headless C.H.I.P, where I could not plug it into the HDMI monitor (only have one HDMI adapter) I ended up connecting though the USB port.  To do this I connected the C.H.I.P to the USB port on my laptop and gave it a minute or so to boot up.  I then connected to the C.H.I.P using the “sudo cu -l /dev/tty.usbmodem1423 -s 115200 “ command from a terminal prompt on my Mac.  For Linux machines you can use “sudo screen /dev/ttyACM0” command to log into the C.H.I.P.  To log onto the C.H.I.P I used the default root/chip username/password. 

Once I logged into the C.H.I.P, I used the nmtui utility to set the wireless network.  This is a very easy to use command line utility that will run in a terminal window.

Installing Swift

Now that I had the C.H.I.P setup and on my wireless network I could begin installing Swift.  I started off by updating any software that was installed on my C.H.I.P.  To do this I used the following two commands:

apt-get update
apt-get upgrade

Next I needed to setup a couple different repositories to pull packages from.  I did this with the following commands:
echo "deb [arch=armhf] http://repos.rcn-ee.com/debian/ jessie main" |  sudo tee –append /etc/apt/sources.list

apt-get update

apt-get install rcn-ee-archive-keyring

wget -qO- http://dev.iachieved.it/iachievedit.gpg.key | sudo apt-key add –

echo "deb [arch=armhf] http://iachievedit-repos.s3.amazonaws.com/ trusty main" | sudo tee --append /etc/apt/sources.list

Now I am able to install the dependencies for Swift.  This is done with the following commands:
apt-get update
apt-get install libicu-dev
apt-get install clang-3.6
apt-get install libpython2.7
update-alternatives --install /usr/bin/clang clang /usr/bin/clang-3.6 100
update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-3.6 100

Finally, I am able to install Swift with this command
apt-get install swift-2.2

At this point we should have a working copy of Swift installed on our system.  This is the 2.2 version of Swift.  I put instructions on how to get Swift 3 at the bottom of this post.

Testing the Swift installation
To test that Swift is installed correct, you can issue the following command:
Swift --version
It should return something like this:
Swift version 2.2-dev (LLVM 3ebdbb2c7e, Clang f66c5bb67b, Swift 1bf4643998)
Target: armv7-unknown-linux-gnueabihf

For an additional test we can try compiling a file.  Create a file named “main.swift” and put the following line of code in it:
print(“Hello World”)
Save this file and then run the following command to compile it.
swiftc main.swift

This should produce an executable file named main.  We can run it with the following command:
./main
If all is well you should see the message “Hello World” printed to the console.

Blinking an LED – Hardware setup
Now that we have out C.H.I.P configured and Swift installed it is time to see what we can do with Swift and the C.H.I.P.  For this initial project I will simply make a LED blink on and off.  Our circuit diagram looks like this:


We have a single LED connected to the CSID0 pin on the C.H.I.P via a 100 ohm resistor.

Blinking an LED – Swift SBDigitalGPIO
To access the GPIO pins on the C.H.I.P I modified a couple files from my SwiftyBones framework. You can find the files for the C.H.I.P on the SwiftyBones_CHIPrepository including a main.swift file that contains code from this post.

Lets see how we will use the SwiftyBones_CHIP library by creating an application that will blink the LED that is connected to the CSID0 pin.  The first thing we need to do is to include the SBCommon_CHIP.swift and SBDigitalGPIO_CHIP.swift files in our project.  Now lets create the main.swift file and include the following code in it:

import Glibc

if let led = SBDigitalGPIO(name: "CSID0", direction: .OUT) {
      while(true) {
           if let oldValue = led.getValue() {
                 let newValue = (oldValue == DigitalGPIOValue.HIGH) ? DigitalGPIOValue.LOW: DigitalGPIOValue.HIGH
                 led.setValue(newValue)
                 usleep(150000)
           }
      }
} else {
      print("error init pin")
}
 
This code starts off by creating an instance of the SBDigitalGPIO type (this is a value type) that is bound to the CSID0 pin on the C.H.I.P.  The next line creates an endless loop so the led will continue to blink.

We use the getValue() method from the SBDigitalGPIO type to retrieve the current value of the CSID0 pin.  We then use the ternary operator set the newValue constant to the opposite of what the current value of the CSID0 pin is and then write that new value to the CSID0 pin using the setValue() method of the SBDigitalGPIO type.  Therefore when the current value is high we set the new value to low and when the current value is low we set the new value to high causing the LED to blink on and off.

We use the usleep() function to sleep for a short period of time before looping back.  That is all there is to it.

Swift on the C.H.I.P
Hopefully in the coming weeks I can do more with Swift on the C.H.I.P.  I would like to create a framework for the C.H.I.P similar to SwiftyBones if time allows.  I would also like to use the C.H.I.P with some of my robotics projects like the BuddyBot because it is much cheaper than the BeagleBone Black (when you are funding the projects yourself every penny counts J)  and has a lot of nice features like the built in WiFi and Bluetooth 4.  The BeagleBone Black does have a lot to offer that the C.H.I.P does not have like the Analog In pins and 8 PWM pins (it does appear that the C.H.I.P has one PWM port but I have not tried to use it yet) however it does appear that the C.H.I.P is a much cheaper alternative to the BeagleBone Black if you do not need the Analog In or more that one PWM port.

Swift 3
If you would like to try out Swift 3, you can download it like this:
wget http://swift-arm.ddns.net/job/Swift-3.0-ARM-Incremental/lastSuccessfulBuild/artifact/swift-3.0.tgz

Once Swift 3 is downloaded you would need to unzip and untar it.  WARNING:  do not untar this from the root directory, it will overwrite your /usr directory.   The Swift executables like swiftc are located in the /usr/bin/ directory of the file structure that was just untared.






Sunday, June 5, 2016

Controlling a Motor with an H-Bridge using Swift and SwiftyBones

All of my robots that I have created use a motor controller board similar to the Rover 5 four channelmotor controller that I use in BuddyBot (the first robot programming in the Swift programming language with SwiftyBones). These motor controllers are very convenient and easy to use however they can get a little expensive when you are on a budget and want to create multiple robots.  Fortunately an H-Bridge is a very cheap alternative to the more expensive motor controllers boards.

An H-Bridge is an electric circuit that allows us to apply voltage to our motors in either direction allowing the motor to run forwards or backwards.   The term H-Bridge comes from the typical graphic representation of the circuit which looks like a capital H.  The following image shows how an H-Bridge works.



An H-Bridge is built with four, usually, solid state switches.  As we see in the previous image, when switches 1 and 3 (I1 and I3) are open and switches 2 and 4 (I2 and I4) are closed the right side of the motor is connected to the power supply while the left side is connected to ground spinning the motor in one direction.  If switches 1 and 3 (I1 and I3) are closed and switches 2 and 4 (I2 and I4) are open then the left side of the motor is connected to the power supply while the right side is connected to ground spinning the motor in the other direction.

For some fun (and this blog post) I created a H-Bridge using four 2n4401 NPN transistors as shown in the following image:



I am not going to explain how this was built because we do not need to create our own H-Bridges, I just did it for fun (my wife says my idea of fun is a bit weird but what can I say).   We can buy them as an IC like the L293D which is designed as a motor controller.  In this post I will show how to control two motors with the L293D H-Bridge motor controller and the BeagleBone Black. 

The L293D is a dual H-Bridge motor driver IC which means that it is capable of driving two motors simultaneously.   The following image shows the pin layout for the L293D IC.




Since the output from the GPIO ports on the BeagleBone Black is usually not enough to drive our motors, the L293D has both a Vcc (3.3V from the BeagleBone Black) and a Vmotor (power for the motors 6V->12V).   The  L293D also has two enable pins which should remain high to enable the motors.   If the enable pins are low the H-Bridge will be disabled.

Each side of the IC has two inputs and two outputs.  Each of the inputs should go to a separate GPIO pin on the BeagleBone Black.  To make the motor turn in the forward direction one input should be high and the other input low.  To make the motor turn in the reverse direction we should reverse which pin is high and which pin is low.  As an example if we are using the left side of the IC for our motor we could set IN1 to high and IN2 to low to drive our motor in one direction and then set IN1 low and IN2 high to drive our motor in the other direction. The OUT1 and OUT2 pins should be connected to the DC motor that we are trying to drive. 

The L293D has four GND pins.  All four GND pins need to be connected to a ground even if you are only driving one motor with the IC.  The following diagram shows how I have the L293D connected to my BeagleBone Black to drive two motors:



As you can see we are using six GPIO pins to drive our two motors.  Pins 15 and 25 of the P9 header are connected to the enable pins on the L293D IC.  Both of these pins will need to be high to enable the motors.  We have pins 11 and 13 of the P9 header connected to the IN1 and IN2 pins on the IC.  We also have pins 21 and 23 of the P9 header connected to the IN3 and IN4 pins. 

The DC motors that we are driving with the L293D are connected to the OUT pins of the IC.  To drive the first motor we will use the following table to see how we should set pins 11, 13 and 15. 

Pin 11 (IN1)
Pin 13 (IN2)
Pin 15 (Enable1)
Result
High
Low
High
Motor spins one direction
Low
High
High
Motor spins other direction
High
High
High
Stopped
Low
Low
High
Stopped
X
X
Low
Stopped


The same table can be applied to the second motor as well just substitute pins 11, 13 and 15 with pins 21, 23 and 25.

Now how can we program this with Swift.  For the SwiftyBones library I wrote a component called SBHBridge that makes it very easy to add an H-Bridge to your project.  You would create an instance of the SBHBridge type like this:

var leftMotor = try SBHBridge(forwardHeader: .P9, forwardPin: 11,
                          reverseHeader: .P9, reversePin: 13,
                          enableHeader: .P9, enablePin: 15,
                          componentName: "Left Motor")

var rightMotor = try SBHBridge(forwardHeader: .P9, forwardPin: 23,
                          reverseHeader: .P9, reversePin: 25,
                          enableHeader: .P9, enablePin: 27,
                          componentName: "Left Motor")

Now we can spin the motor in the forward direction like this:

leftMotor.goForward()
rightMotor.goForward()

 or in the reverse direction like this:

leftMotor.goReverse()
rightMotor.goReverse()

We can also enable or disable the motor using the enableMotor(Bool) function:

leftMotor.enableMotor(true)
rightMotor.enableMotor(true)


Adding an H-Bridge to your robotics project is a cheap and simple way to drive your motors. The SwiftyBones library makes it incredible easy to use it with your next project.