9. Temperature iPhone App - Spark Core

Now lest’s TMP36 to measure temperature. Hook up a analog temperature sensor (TMP36) as follows. You may want to read data sheet of TMP36.

Implement API

We are using Spark.variable() function to expose temperature as API.

Spark.variable("temperature", &temperature, DOUBLE);

The whole code

#include <stdarg.h>

#define PRINTF_BUFFER_SIZE 128
void Serial_printf(const char* fmt, ...) {
   char buff[PRINTF_BUFFER_SIZE];
   va_list args;
   va_start(args, fmt);
   vsnprintf(buff, PRINTF_BUFFER_SIZE, fmt, args);
   va_end(args);
   Serial.println(buff);
}

double temperature = 0.0;

void setup()
{
  // Use serial port for debug print
  Serial.begin(9600);

  // register API variable
  Spark.variable("temperature", &temperature, DOUBLE);
  pinMode(A7, INPUT);
}

void loop()
{
  int analogValue = analogRead(A7);
  double voltage = 3.3 * ((double)analogValue / 4095.0);

  // http://www.analog.com/static/imported-files/data_sheets/TMP35_36_37.pdf
  temperature = (voltage - 0.5) * 100;
  Serial_printf("voltage=%g temperature=%g", voltage, temperature);
  delay(500);
}

Call the API

You can call & test the API using curl. Please note that the response is JSON format.

% curl "https://api.spark.io/v1/devices/YOUR_DEVICE_ID/temperature?access_token=YOUR_ACCESS_TOKEN"
{
  "cmd": "VarReturn",
  "name": "temperature",
  "result": 27.04029304029304,
  "coreInfo": {
    "last_app": "",
    "last_heard": "2014-09-15T03:56:33.912Z",
    "connected": true,
    "deviceID": “YOUR_DEVICE_ID"
  }
}

iPhone App

Okay, then let’s create simple iPhone App viewer. Don’t worry it’s not very difficult.

1. Open Xcode
2. File - New - Project - Single View Application

3. Name the project as Temperature
4. Click Main.storyboard in the left side view
5. Add Label and Button to the storyboard view

6. Connect the Label and Button to ViewController

7. Implement ViewController
8. Build & Run

//
//  ViewController.swift
//  Temperature
//
//  Created by Taro Minowa on 9/14/14.
//  Copyright (c) 2014 Higepon Taro Minowa. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var reloadButton: UIButton!
    @IBOutlet weak var temperatureLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        // initial load
        reloadTemperature()
    }

    // when the reload button tapped
    @IBAction func reloadDidTap(sender: AnyObject) {
        reloadTemperature()
    }

    // call the API, parse the response and show result
    private func reloadTemperature() {
        let url = NSURL(string: "https://api.spark.io/v1/devices/YOUR_DEVICE_ID/temperature?access_token=YOUR_ACCESS_TOKEN")
        let request = NSURLRequest(URL: url)
        temperatureLabel.text = "Loading..."

        // call the API
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
            if error != nil {
                println("Request Error \(error.localizedDescription)")
                return;
            }
            var err: NSError?
            // parse the API response
            var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
            if err != nil {
                println("JSON Error \(err!.localizedDescription)")
            }
            println(jsonResult)
            if let temperature = jsonResult["result"] as? Float {
                // Show the result
                self.temperatureLabel.text = String(format: "%.2f°C", temperature)
            }
        }
    }
}

Yay! Now you can see the temperature via the Internet!

source code

You can download whole source code at github.