Showing posts with label LED. Show all posts
Showing posts with label LED. Show all posts

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.






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.




Thursday, July 24, 2014

Spark Core – iOS Library

The only issue we have encountered, using the BeagleBone Black with our robot, is the only wireless communication option is Bluetooth.  I know I can communicate from my laptop to the BeagleBone Black over Bluetooth but we want to control the robot from our iPhone/iPad/iPods.  If you are familiar with Apple’s iOS Bluetooth stack, you know that it is very limited and communicating to custom devices like the BeagleBone Black isn’t really an option.

I could add a WiFi USB adapter but it would draw too much power when I use the EasyAcc Battery Charger to power the BeagleBone Black.  After doing a bit of research, I stumbled on the Spark Core.  The Spark Core is a complete WiFi enabled development platform that is code-compatible with the Arduino.  I believe I can use the Spark Core as a communication module for our robot but the first thing I needed to do was to create an iOS library to communicate with Spark’s Web API because Spark does not currently have one.  You can get the library that I created from my GitHub repository at:  https://github.com/hoffmanjon/SparkCoreIOS.

Lets begin by looking at the classes that make up the Spark Core library.  After the class summaries, I will show how to use the library.  If you download the library there is a complete sample application with it and I will discuss that sample at the end of this post.  The library has two main classes:

- SparkCoreConnector:  This class is the main communication class that handles all communication between an iOS device and Spark’s Web API.  This class expose one static method:  connectToSparkAPIWithTransaction:andHandler:
- SparkTransaction:  This class defines the information that is used to build the URL to Spark’s Web API and also the parameters that we need to send.  This class is meant to be sub classed for each of the transaction types.  This base class exposes three public properties, these are:
- baseUrl – the base URL that is used to build the final URL.  By default this is:  https://api.spark.io/v1/devices.
- accessToken – The access token for your Spark Core.
- deviceId – The id of your Spark Core.

Next lets look at the transaction types that subclass the SparkTransaction class.  Currently I have two types defined in the library:

 - SparkTransactionGet:  This library is used to submit a GET request to Spark’s Web API.  This type of request is used to retrieve data from your Spark Core.  You will need to set the “property” property to the name of the variable you want to retrieve.
 - SparkTransactionPost:  This library is used to submit a POST request to Spark’s Web API.  This type of request is used to submit data/commands to your Spark Core.  You will need to set the “functionName” parameter to the function you want to call and the “parameters” property to the commands you want to send.

Now lets see how to use the library with some sample code.  The code to send a SparkTransactionPost request would look something like this:

SparkTransactionPost *postTransaction = [[SparkTransactionPost alloc] initWithAccessToken:ACCESS_TOKEN deviceId:DEVICE_ID functionName:FUNCTION andParameters:parameter];
   
[SparkCoreConnector connectToSparkAPIWithTransaction:postTransaction andHandler:^(NSURLResponse *response, NSDictionary *responseDictionary, NSError *error){
        if(error == nil) {
            NSLog(@"Response: %@",responseDictionary);
        } else {
            NSLog(@"Error: %@",error);
        }
    }];

We start by creating a SparkTransactionPost object using the initWithAccessToken:deviceId:functionName:andParameters: initializer.  We then call the static connectToSparkAPIWithTransaction:andHandler: method of the SparkConnector class to send the request.

Creating a SparkTransationGet request is very similar to the Post request.  The code looks like this:

SparkTransactionGet *getTransaction = [[SparkTransactionGet alloc] initWithAccessToken:ACCESS_TOKEN deviceId:DEVICE_ID andProperty:COUNT_VAR];
   
[SparkCoreConnector connectToSparkAPIWithTransaction:getTransaction andHandler:^(NSURLResponse *response, NSDictionary *responseDictionary, NSError *error){
        if(error == nil) {
            NSLog(@"Response: %@",responseDictionary);
          } else {
            NSLog(@"Error: %@",error);
          }
    }];

The only difference between the Get and Post requests is we create a SparkTransactionGet object using the initWithAccessToken:deviceId:andProperty: initializer instead of the SparkTransactionPost object.

It is that easy to send requests from you iOS device to your Spark Core with this library.

Lets take a quick look at the sample project that comes with the library.  The first thing we need to do is to wire up two LEDs and flash the Spark Core.  If you do not understand the wiring diagram or the code that needs to be flashed to the Spark Core, please see Spark’s documentation here:  http://docs.spark.io:



Now that we have the LEDs wired to our Spark Core, we need to flash it with the following code:

int ledUser = D7;
int led1 = D0;
int led2 = D5;
int myvar = 0;

void setup() {
    Spark.function("led", ledController);
   
    pinMode(ledUser, OUTPUT);
    pinMode(led1, OUTPUT);
    pinMode(led2, OUTPUT);
   
    digitalWrite(ledUser, LOW);
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
   
    Spark.variable("myvar", &myvar, INT);
}

void loop() {
   
}

int ledController(String command)
{
    myvar = myvar +1;
    int ledState = 0;
    int pinNumber = (command.charAt(1) - '0');
   
    if (pinNumber != 0 && pinNumber != 5 && pinNumber !=7) {
        return -1;
    }
   
    if(command.substring(3,7) == "HIGH") ledState = HIGH;
   else if(command.substring(3,6) == "LOW") ledState = LOW;
   else return -2;
   
    digitalWrite(pinNumber,ledState);
   
    return 1;
}

Now lets look at our example application.  If you run the code you will see a screen that looks like this: 



By flipping the switches, you can turn the LEDs off/on.  If you press the count button you will retrieve the number of times the LEDs have been toggled and display that count.

Lets look at the ViewController.m file to see how this application works.  We start by defining a number of constants:

#define ACCESS_TOKEN @"123456789"
#define DEVICE_ID @"my-core"
#define FUNCTION @"led"
#define COUNT_VAR @"myvar"

#define LED_USER @"D7"
#define LED_1 @"D0"
#define LED_2 @"D5"

#define STATE_HIGH @"HIGH"
#define STATE_LOW @"LOW"

These constants are:

ACCESS_TOKEN:  The access token for your Spark Core.
DEVICE_ID:  The device id for your Spark Core.
FUNCTION:  The name of the function that we call in our Post requests.
COUNT_VAR:  The name of the variable to request in our Get requests.
LED_USER:  The pin for the user LED on the Spark Core.
LED_1:  The pin for the first external LED that we connected to the Spark Core.
LED_2:  The pin for the second external LED that we connected to the Spark Core.
STATE_HIGH:  Defines the string for the pin’s high state.
STATE_LOW:  Defines the string for the pin’s low state.

Now lets look at our viewDidLoad method.  This method is called after the view is finished loading.

- (void)viewDidLoad {
    [super viewDidLoad];
       [_led1Switch setOn:NO animated:YES];
    [_led2Switch setOn:NO animated:YES];
    [_ledUserSwitch setOn:NO animated:YES];
    [self getCount];
}

We start off my using the setOn:animated: method of the UISwitch class and set all of the switches to off since our LEDs will be in the off state to begin with.  We then call our getCount method to retrieve the count from the Spark Core.  The getCount method looks like this:

-(void)getCount {
    SparkTransactionGet *getTransaction = [[SparkTransactionGet alloc] initWithAccessToken:ACCESS_TOKEN deviceId:DEVICE_ID andProperty:COUNT_VAR];
   
    [SparkCoreConnector connectToSparkAPIWithTransaction:getTransaction andHandler:^(NSURLResponse *response, NSDictionary *responseDictionary, NSError *error){
        if(error == nil) {
            NSLog(@"Response: %@",responseDictionary);
            NSString *cnt = [responseDictionary objectForKey:@"result"];
            _countLabel.text = [NSString stringWithFormat:@"Count:  %@", cnt];
        } else {
            NSLog(@"Error: %@",error);
            _countLabel.text = @"Error Getting Count";
        }
    }];
}
In this method we create a SparkTransactionGet object using the initWithAccessToken:deviceId:andProperty: initializer. 
We then use the connectToSparkAPIWithTransaction:andHandler: static method to send the request to Spark’s Web API.  For the handler parameter we pass in a block object that will run after Spark’s Web API returns a response.  In the block object we check to see if there was an error.  If there was no error we display the count.  If there was an error we display the error message.  The request created by this method is the same as using curl like this:  curl –G https://api.spark.io/v1/devices/my-core/myvar –d access_token=123456789

Next we need to create methods that will be called when the user flips the switches.  These methods look like this:

-(IBAction)ledUserSwitchAction:(id)sender {
    NSString *pin = LED_USER;
    NSString *state = STATE_HIGH;
    if (_ledUserSwitch.on)
        state = STATE_LOW;
    NSString *param = [NSString stringWithFormat:@"%@:%@",pin,state];
    [self sendRequestWithParameter:param];
}

-(IBAction)led1SwitchAction:(id)sender {
    NSString *pin = LED_1;
    NSString *state = STATE_HIGH;
    if (_led1Switch.on)
        state = STATE_LOW;
    NSString *param = [NSString stringWithFormat:@"%@:%@",pin,state];
    [self sendRequestWithParameter:param];
}

-(IBAction)led2SwitchAction:(id)sender {
    NSString *pin = LED_2;
    NSString *state = STATE_HIGH;
    if (_led2Switch.on)
        state = STATE_LOW;
    NSString *param = [NSString stringWithFormat:@"%@:%@",pin,state];
    [self sendRequestWithParameter:param];
}

Each of these methods does the same thing.  They begin by setting the “pin” NSString to the pin on the Spark Core that we want to set.  We then set the “state” NSString to High or Low depending on the state of the switch.  We use the “pin” NSString and the “state” NSString to create our “param” NSString.  Finally we call the sendRequestWithParameter: method to send the request to Spark’s Web API.  Now lets look at the sendRequestWithParameter: method.

-(void)sendRequestWithParameter:(NSString *)parameter {

    SparkTransactionPost *postTransaction = [[SparkTransactionPost alloc] initWithAccessToken:ACCESS_TOKEN deviceId:DEVICE_ID functionName:FUNCTION andParameters:parameter];
   
    [SparkCoreConnector connectToSparkAPIWithTransaction:postTransaction andHandler:^(NSURLResponse *response, NSDictionary *responseDictionary, NSError *error){
        if(error == nil) {
            NSLog(@"Response: %@",responseDictionary);
        } else {
            NSLog(@"Error: %@",error);
        }
    }];
}

This method begins by creating a SparkTransactionPost object using the initwithAccessToken:deviceId:functionName:andParameters: initializer.  We then call the same connectToSparkAPIWithTransaction:andHandler: static method that we saw in the getCount method.  In the block object that we pass to the handler, we simply log the response from the Spark’s Web API or we log the error depending on if we received an error or not.  The request created for this method is the same as using curl like this:  curl https://api.spark.io/v1/devices/my-core/led –d access_token=123456789 -d params=d0,HIGH


I have just started using the Spark Core so I put in the functionality that I think I need to communicate to my robot.  If anyone has any suggestions or recommendations on what functionality they would like to see in the library, please let me know.  I hope you find this library useful.