TMP102

Using Arduino code on Spark Core

In an earlier post Spark Core Weather Station I presented code that was reading weather sensors and sent the data over USB to a PC terminal. However the approach I took there to combine all code into a single file is not very practical. So now that the Spark IDE supports multiple project files we can just include Arduino library files.
Screenshot 2014-04-16 20.49.13
So here are some hints how to get Arduino library code and sketches to compile in the Spark framework. I use a TMP102 I2C temperature sensor to demonstrate the porting. Below is an example Sketch that reads the temperature values and sends them to the serial interface:

//////////////////////////////////////////////////////////////////
//Released under the MIT License - Please reuse change and share
//Simple code for the TMP102, simply prints ambient temperature via serial
//////////////////////////////////////////////////////////////////
#include <Wire.h>
int tmp102Address = 0x48;
void setup(){
  Serial.begin(9600);
  Wire.begin();
}
void loop(){
  float celsius = getTemperature();
  Serial.print("Celsius: ");
  Serial.println(celsius);
  float fahrenheit = (1.8 * celsius) + 32;
  Serial.print("Fahrenheit: ");
  Serial.println(fahrenheit);
  delay(200); //just here to slow down the output. You can remove this
}
float getTemperature(){
  Wire.requestFrom(tmp102Address,2);
  byte MSB = Wire.read();
  byte LSB = Wire.read();
  //it's a 12bit int, using two's compliment for negative
  int TemperatureSum = ((MSB << 8) | LSB) >> 4;
  float celsius = TemperatureSum*0.0625;
  return celsius;
}

The main reason this code fails to compile is the Arduino Wire.h library include statement fails on the cloud based Spark Core IDE. The TMP102 sketch code use I2C. So it includes the Arduino Wire Library with the following line:

#include <Wire.h>

This triggers an error in the Spark IDE. To solve this problem I created a new library named Wire.h with the following content:

#include "spark_wiring.h"
#include "spark_wiring_interrupts.h"
#include "spark_wiring_usartserial.h"
#include "spark_wiring_spi.h"
#include "spark_wiring_i2c.h"
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "debug.h"
#include "math.h"
#include "limits.h"
#include "stdint.h"
#include "spark_utilities.h"
extern "C" {
#include "usb_conf.h"
#include "usb_lib.h"
#include "usb_desc.h"
#include "usb_pwr.h"
#include "usb_prop.h"
#include "sst25vf_spi.h"
}
#include <sys/types.h>

With this library all we have to do is to uncomment or delete the original include statement. By adding Wire.h file the IDE automatically adds a line like this to the source code:

// This #include statement was automatically added by the Spark IDE.
#include "Wire.h"

As long as the Arduino source follows basic guidelines for portable code I did not face much difficulties to use existing Arduino sources on the Spark Core.