Sunday, May 22, 2016

Adventures in IOT - Particle Photon

Last summer I came across the Particle Photon and decided to pick up two of them and give them a try. Fast forward a number of months and I decided on a simple project combining a DHT22 temperature and humidity sensor with the Particle Photon in a simple IOT project.

Introduction

The Photon is a nice development platform in the style of the Arduino.  The Photon consists of a STM32 ARM Cortex M3 microcontroller paired with a Broadcom WICED wifi chip.  This allows easy access from the board to the Internet.

Development with the Photon can be done a couple of different ways.  There is a web based IDE paired with an online compiler known as Particle Build.  There is an IDE that can be installed on your computer which also uses the online compiler known as Particle Dev.  The online compiler can be accessed using a node.js based command line environment which allows you to use a iDE of your choice.  Finally you can roll your own development environment with the ide of your choice, ARM gcc and the DFU boot loader.  The flash process can be done over wifi or usb.

The development environment is styled after the popular Arduino development environment with good documentation and core and user contributed libraries  I have a good bit of experience with that Arduino and It’s IDE and found that there was a very minimal learning curve.

The most complex part of developing on the Photon is activating your Photon so that it can be flashed via wifi over the Internet.  There are a number of methods for doing this.  I used the Android App and the process went very smoothly.

To get started there is excellent documentation on the Particle website and a very good guide at Sparkfun.

image

image image image

image

My plan was to read the DHT22 with the photon and upload temperature and humidity data over the Internet to an IOT analytics service.

Hardware Setup

Minimal hardware is required for this project.  I used a mini breadboard, s photon, a DHT22, 10 K resistor and some hook up wire.

The DHT22 has four pins on it.  With the DHT22 facing you so you are looking at the vents the pins are numbered 1 – 4 left to right.

  1. VCC 3V to 5.5V: connects to 3.3V on Photon with a 10K resistor to pin 2.
  2. Data: connects to D3 on the Photon.
  3. N/A: is not used
  4. Ground: connect to GND on the Photon.

Software

Using Particle Build, Particle Dev or the command line development environment a program is written the same way as an Arduino sketch with a setup routine that is executed once and a loop routine that is executed continuously after setup completes.

My simple example was made considerably easier thanks to the user contributed library for the DNT22 sensor.  The PietteTech_DHT library can be found in the list of user contributed libraries in Particle Build or as a GitHub repository

To build this example I used the command line.  When using the command line environment you put your library files, in this caswe PietteTech_DHT.cpp, PietteTech_DHT.h, and your Photon program in the same directory.  When you compile or flash you specify the directory as the source.

The example below reads the sensor and then publishes the temperature, humidity and status to the Particle website.

#include <cstdio>
#include "PietteTech_DHT.h"

#define DHTTYPE  DHT22       // Sensor type for PietteTech_DHT
#define DHTPIN   3           // Digital pin for PietteTech_DHT

// Must be declared before PietteTech_DHT 
void dht_wrapper();

// Library instantiation
PietteTech_DHT DHT(DHTPIN, DHTTYPE, dht_wrapper);

float temp;
float humidity;
float status;

void setup() {
  Serial.begin(9600);
}

// Must be setup like this for PietteTech_DHT to work
void dht_wrapper() {
  DHT.isrCallback();
}

void loop() {
  int result = DHT.acquireAndWait();
  
  if (result == DHTLIB_OK) {
    temp = DHT.getFahrenheit();
    humidity = DHT.getHumidity();
  } else {
    temp = 0;
    humidity = 0;
  }
  
  char buf[80];
  
  int n = snprintf(buf, 80, 
    "{ \"temp\": \"%5.2f\", \"humidity\": "
    "\"%5.2f\", \"status\": \"%d\" }",
    temp, humidity, result);

  Particle.publish("THEvent", buf, 60, PRIVATE);
  
  delay(60000);
}

In a command window at the command line compile using the command below where THPublish is a subdirectdory that contains the ino file and library files.

image

To flash your code to the photon is done using the command below again THPublish is a subdirectory that contains the ino file and library files.  Also, photon2 is the name of the photon you are flashing.

image

The photon led will flash blue/red and then green and back to blue.

If everything is successful you can go to the Particle log and see you events and event data.  Starting at the main Particle web page select  image from the upper right corner.  Then on the left side of the screen select the log icon imageand see your events and event data in the log.  The way that logging works it will start logging when you show the log which means you will need to wait for your event to occur before it will be shown.

image

Thoughts

The folks at Particle has put together a very nice device and a comprehensive development environment.  The price of the device and the ease of use has greatly lowered the cost of entry in the IOT space.  Beyond traditional IOT the Particle Photon can be used to allow easy interaction with a microcontroller based project over wifi.

The Particle Photon can be purchased for $19 from Particle, Sparkfun or Adafruit making it an attractive option for your next project.

Saturday, December 26, 2015

It Worked For Me (Sort Of) - Raspberry PI and D-Link DWA-171A1

I recently purchased a D-Link DWA-171A1 Wireless AC Dual Band USB Adapter to use with a Raspberry PI 2 B after seeing a posting that stated that it worked out of the box.  Well…

It didn’t work out of the box but I was able to get it to work by compiling the driver.  I used this code from GitHub on the Raspbian Jessie image dated 11/21/2015

  1. Loaded the Raspbian Jessie image from here: https://www.raspberrypi.org/downloads/raspbian/ Linux raspberrypi (4.1.13-v7+)  to my SD Card.
  2. Added the following packages using apt-get: apt-get install dkms build-essential bc
  3. Downloaded and unzip the driver from abperiasamy/rtl8812AU_8821AU_linux GitHub repository:  https://github.com/abperiasamy/rtl8812AU_8821AU_linux/archive/master.zip
  4. Download the appropriate kernel headers for your version of Raspbian.  I found the ones I needed here: https://www.niksula.hut.fi/~mhiienka/Rpi/linux-headers-rpi/.
  5. Install the headers using sudo dpkg –i <package name>.deb.
  6. cd to the directory you unziped the driver into.
  7. Using nano or some other editor update the Makefile:
  8. CONFIG_PLATFORM_I386_PC = n
    CONFIG_PLATFORM_ARM_RPI = y
  9. The using the following commands build and install the driver.
  10. # sudo make clean
    # sudo make
    # sudo make install
    # sudo modprobe -a 8812au
You should now see the DWA-171 as a wireless interface and should be able to configure it.
I tried the same procedure using a Raspberry Pi B running Arch Linux with a 3.12.26-1-ARCH kernel and wasn’t able to get the driver to compile.
Thanks to all those who made resources available to help me along this journey.

Thursday, December 24, 2015

Project Raspberry Pi Music Player

Two weeks ago my wife informed me that the CD player attached to our stereo wasn’t working.  After a tinkering with it for a while, I decided that I wasn’t going to be able to fix it.

Over the years, we have moved from playing CDs to listening to music using computers, tablets and MP3 players.  The one time where we use the CD player is during the Holidays.

So now the holidays were almost upon us and no CD player.

I decided that this would be an opportunity to put one of the many single board computers (SBCs) to use.  I had a Raspberry PI B that I have been using in various projects over the past several years.  I had recently added a Raspberry Pi 2 B and a Raspberry Pi Zero so I figured I could turn the older system into a music player.

I figured correctly that given the huge community around the Pi that there would be at least a couple of options.  As it turned out I was not disappointed.

There are a number of options for music players for the Pi.  I checked out four of them installing three before finalizing on one.

The fist three volumio, rune, and Moode have the same look and feel as they came out of the RaspFi project and utilize the Music Player Daemon (MPD).  Pi MusicBox comes from a different lineage and has a different look and feel.

I installed all three RaspFi based versions.  There is one major difference between rune audio Player and volumio / Moode and that is that it is based on Arch Linux where as volumio and Moode based on Raspberian.  All three offer SD card images that can be downloaded, written to an SD card and insterted in the Pi and have you up and running in less than an hour.

These programs all support the Pi’s onboard audio as well as specialty Pi audio i2s audio boards as well as usb audio.  For my installation I am using the onboard audio.  With this setup I just needed a 3.5mm to RCA cable which I connected into my stereo receiver.

I started with volumio and had some success but the player ui would stall and leave me with spinning arrows.  I moved to rune audio Player and it was a much better experience.  I had some problems at first and that led me to check out Moode, but I didn’t like the ui as much and decided to go back and look at solving my problems with rune.

The first problem I had with rune was that songs would cut out.  Doing some network testing I determined that my wifi connection would drop occasionally and that caused the drop outs. The solution to this was to move the songs locally.  At fist moving the songs locally didn’t solve my problem.  Song continued to cut out.  I determined that the usb drive I was using was periodically resetting.  I moved to another usb drive and the problem went away.

I have been running rune for about a week now and am pretty happy with it.  I will detail my build over the next couple of days and post it here.

Wednesday, July 22, 2015

TI SimpleLink SensorTag 2015 - Development Environment Guide

Gerard at 43oh has posted an excellent guide for setting up the development environment for the CC2650STK.  I highly recommend that you check it out before you attempt to install Code Composer Studio.

image

Sunday, July 12, 2015

TI SimpleLink SensorTag 2015 - Python

Code for these examples is on GitHub in the dhSensorTag2015 repository.

Having successfully accessed data on the sensor tag I decided to try my hand at programmatically accessing data from the sensor tag.  I started out with the same two examples I had developed in bash: 1) to get the device name; and 2) get the humidty reading from the humidity sensor.

Surprisingly there are not too many options when it comes to Bluetooth Low Engergy APOs for Windows 7 or Linux. One of the few that exists is Ian Harvey’s bluepy for python on Linux.

Python isn’t something I use very much.  I do most of my work in Perl and C with a bit of Java thrown in for Android.  Fortunately there are a set of pretty good set of instructions for setting up bluepy on the Raspberry Pi that can be found at: http://www.elinux.org/RPi_Bluetooth_LE.  The output from these instructions is below:

pi@raspberrypi ~ $ git clone https://github.com/IanHarvey/bluepy.git
Cloning into 'bluepy'...
remote: Counting objects: 459, done.
remote: Total 459 (delta 0), reused 0 (delta 0), pack-reused 459
Receiving objects: 100% (459/459), 1.51 MiB | 556 KiB/s, done.
Resolving deltas: 100% (172/172), done.
pi@raspberrypi ~ $ cd bluepy/bluepy
pi@raspberrypi ~/bluepy/bluepy $ make
gcc -L. -O0 -g -DHAVE_CONFIG_H -I../bluez-5.4/attrib -I../bluez-5.4 -I../bluez-5.4/lib -I../bluez-5.4/src -I../bluez-5.4/gdbus -I../bluez-5.4/btio `pkg-config glib-2.0 dbus-1 --cflags` -o bluepy-helper bluepy-helper.c ../bluez-5.4/lib/bluetooth.c ../bluez-5.4/lib/hci.c ../bluez-5.4/lib/sdp.c ../bluez-5.4/lib/uuid.c ../bluez-5.4/attrib/att.c ../bluez-5.4/attrib/gatt.c ../bluez-5.4/attrib/gattrib.c ../bluez-5.4/attrib/utils.c ../bluez-5.4/btio/btio.c ../bluez-5.4/src/log.c `pkg-config glib-2.0 --libs`
pi@raspberrypi ~/bluepy/bluepy $ python btle.py B0:B4:48:B9:2C:82

Running the script generates the a dump of the services and characteristics.

Connecting to: B0:B4:48:B9:2C:82, address type: public
Service <uuid=Generic Access handleStart=1 handleEnd=7> :
    Characteristic <Device Name>, supports READ
    -> 'SensorTag 2.0'
    Characteristic <Appearance>, supports READ
    -> '\x00\x00'
    Characteristic <Peripheral Preferred Connection Parameters>, supports READ
    -> 'P\x00\xa0\x00\x00\x00\xe8\x03'
Service <uuid=f000aa70-0451-4000-b000-000000000000 handleStart=63 handleEnd=70> :
    Characteristic <f000aa71-0451-4000-b000-000000000000>, supports NOTIFY READ
    -> '\x00\x00'
    Characteristic <f000aa72-0451-4000-b000-000000000000>, supports READ WRITE
    -> '\x00'
    Characteristic <f000aa73-0451-4000-b000-000000000000>, supports READ WRITE
    -> 'P'
Service <uuid=f000ac00-0451-4000-b000-000000000000 handleStart=81 handleEnd=88> :
    Characteristic <f000ac01-0451-4000-b000-000000000000>, supports NOTIFY READ WRITE
    -> '\x00\x00'
    Characteristic <f000ac02-0451-4000-b000-000000000000>, supports READ WRITE
    -> '\x02\x02\x00\x00\x00'
    Characteristic <f000ac03-0451-4000-b000-000000000000>, supports READ WRITE
    -> '\x00D'
Service <uuid=Generic Attribute handleStart=8 handleEnd=11> :
    Characteristic <Service Changed>, supports INDICATE
Service <uuid=ffe0 handleStart=71 handleEnd=75> :
    Characteristic <ffe1>, supports NOTIFY
Service <uuid=f000aa64-0451-4000-b000-000000000000 handleStart=76 handleEnd=80> :
    Characteristic <f000aa65-0451-4000-b000-000000000000>, supports READ WRITE
    -> '\x7f'
    Characteristic <f000aa66-0451-4000-b000-000000000000>, supports READ WRITE
    -> '\x00'
Service <uuid=f000aa00-0451-4000-b000-000000000000 handleStart=31 handleEnd=38> :
    Characteristic <f000aa01-0451-4000-b000-000000000000>, supports NOTIFY READ
    -> '\x00\x00\x00\x00'
    Characteristic <f000aa02-0451-4000-b000-000000000000>, supports READ WRITE
    -> '\x00'
    Characteristic <f000aa03-0451-4000-b000-000000000000>, supports READ WRITE
    -> 'd'
Service <uuid=f000ffc0-0451-4000-b000-000000000000 handleStart=97 handleEnd=65535> :
    Characteristic <f000ffc1-0451-4000-b000-000000000000>, supports NOTIFY WRITE NO RESPONSE WRITE
    Characteristic <f000ffc2-0451-4000-b000-000000000000>, supports NOTIFY WRITE NO RESPONSE WRITE
Service <uuid=f000aa20-0451-4000-b000-000000000000 handleStart=39 handleEnd=46> :
    Characteristic <f000aa21-0451-4000-b000-000000000000>, supports NOTIFY READ
    -> '\x00\x00\x00\x00'
    Characteristic <f000aa22-0451-4000-b000-000000000000>, supports READ WRITE
    -> '\x00'
    Characteristic <f000aa23-0451-4000-b000-000000000000>, supports READ WRITE
    -> 'd'
Service <uuid=Device Information handleStart=12 handleEnd=30> :
    Characteristic <System ID>, supports READ
    -> '\x82,\xb9\x00\x00H\xb4\xb0'
    Characteristic <Model Number String>, supports READ
    -> 'CC2650 SensorTag\x00'
    Characteristic <Serial Number String>, supports READ
    -> 'N.A.\x00'
    Characteristic <Firmware Revision String>, supports READ
    -> '1.01 (Mar 13 2015)\x00'
    Characteristic <Hardware Revision String>, supports READ
    -> 'PCB 1.2\x00'
    Characteristic <Software Revision String>, supports READ
    -> 'N.A.\x00'
    Characteristic <Manufacturer Name String>, supports READ
    -> 'Texas Instruments\x00'
    Characteristic <IEEE 11073-20601 Regulatory Cert. Data List>, supports READ
    -> '\xfe\x00experimental'
    Characteristic <PnP ID>, supports READ
    -> '\x01\r\x00\x00\x00\x10\x01'
Service <uuid=f000aa80-0451-4000-b000-000000000000 handleStart=55 handleEnd=62> :
    Characteristic <f000aa81-0451-4000-b000-000000000000>, supports NOTIFY READ
    -> '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    Characteristic <f000aa82-0451-4000-b000-000000000000>, supports READ WRITE
    -> '\x00\x02'
    Characteristic <f000aa83-0451-4000-b000-000000000000>, supports READ WRITE
    -> 'n'
Service <uuid=f000ccc0-0451-4000-b000-000000000000 handleStart=89 handleEnd=96> :
    Characteristic <f000ccc1-0451-4000-b000-000000000000>, supports NOTIFY READ
    -> '6\x00\x00\x00d\x00'
    Characteristic <f000ccc2-0451-4000-b000-000000000000>, supports WRITE
    Characteristic <f000ccc3-0451-4000-b000-000000000000>, supports WRITE
Service <uuid=f000aa40-0451-4000-b000-000000000000 handleStart=47 handleEnd=54> :
    Characteristic <f000aa41-0451-4000-b000-000000000000>, supports NOTIFY READ
    -> '\x00\x00\x00\x00\x00\x00'
    Characteristic <f000aa42-0451-4000-b000-000000000000>, supports READ WRITE
    -> '\x00'
    Characteristic <f000aa44-0451-4000-b000-000000000000>, supports READ WRITE
    -> 'd'

At this point I created a directory SensorTag2015 off my home directory to work in.  I copied the bluepy python files into a subdirectory bluepy.  This gave me a setup that looked like this.

image

In the SensorTag2015 directory I created and ran my python examples.  I started with a very simple script that expects an address for the sensor tag on the command line.

pi@raspberrypi ~/SensorTag2015 $ python getDeviceName.py 00:00:00:00:00:00
SensorTag 2.0
pi@raspberrypi ~/SensorTag2015 $

The script imports two methods from the bluepy.btle fileand then it defines a UUID for the device name.  It checks to make sure that at least one argument is passed and then establishes a connection to the sensor tag.  If the script fails to connect to the sensor tag check to make sure that the sensor tag is advertising.  If it isn't push the left button and check that the green LED is flashing.  Once connected the script checks to make sure that the device name characteristic is readable, reads it and prints it out.

getDeviceName.py

import sys
from bluepy.btle import UUID, Peripheral

temp_uuid = UUID(0x2A00)

if len(sys.argv) != 2:
  print "Fatal, must pass device address:", sys.argv[0], ""
  quit()

p = Peripheral(sys.argv[1])

try:
    ch = p.getCharacteristics(uuid=temp_uuid)[0]
    if (ch.supportsRead()):
            print ch.read()

finally:
    p.disconnect()

Next I developed a slightly more complicated script for reading the Humidity sensor.  The template I developed with this script is what I used for most of the examples.

The script expects the address of the sensor tag to be passed on the command line as with the script above.  Then it defines TI unique UUIDs to configure the sensor and to get data from the sensor.  Next it sets up the values that get written to the sensor's configure UUID to turn the sensor on or off.  Note you must turn a sensor on before you are able to read it and get values other than zero back.

After these variables are setup the script connects to the sensor tag.  Once connected the script writes the value to turn on the sensor to the configuration UUID.  Then it reads the raw data from the sensor tag, converts it to values and calculates the sensor value.  The formulas for calculating the sensor values were pulled from the Android App source code. After the values are printed out the script turns of the sensor and disconnects from the device.

getHumidity.py

#
# TI SimpleLink SensorTag 2015
# Date: 2015 07 06
#
# Sensor: Humidity Temperature
# Values: Temperature and Humidity
#
import struct, sys, traceback
from bluepy.btle import UUID, Peripheral, BTLEException

def TI_UUID(val):
    return UUID("%08X-0451-4000-b000-000000000000" % (0xF0000000+val))

config_uuid = TI_UUID(0xAA22)
data_uuid = TI_UUID(0xAA21)

sensorOn  = struct.pack("B", 0x01)
sensorOff = struct.pack("B", 0x00)

if len(sys.argv) != 2:
  print "Fatal, must pass device address:", sys.argv[0], ""
  quit()

try:
  print "Info, trying to connect to:", sys.argv[1]
  p = Peripheral(sys.argv[1])

except BTLEException:
  print "Fatal, unable to connect!"
  
except:
  print "Fatal, unexpected error!"
  traceback.print_exc()
  raise

else:

  try:
    print "Info, connected and turning sensor on!"
    ch = p.getCharacteristics(uuid=config_uuid)[0]
    ch.write(sensorOn, withResponse=True)
    
    print "Info, reading values!"
    ch = p.getCharacteristics(uuid=data_uuid)[0]
    
    # IR Temperature sensor returns 4 bytes object(LSB),
    # object(MSB), ambient(LSB) and ambient(MSB).
    # Python unpack using "<" which denotes little-endian format
    # and "hh" which denotes 2 unsigned short (2 byte/16 bit) values.
    rawVals=ch.read()
    #(tempVal, humidVal) = struct.unpack('<HH', ch.read())
    tempVal = (ord(rawVals[1])<<8)+ord(rawVals[0])
    humidVal = (ord(rawVals[3])<<8)+ord(rawVals[2])
    
    #object temp and ambient temp are calculated as shown below
    print "Temp: %.2f F" % float((tempVal / 65536.0 * 165 - 40) * 1.8 + 32)
    print "Humidity: %.2f %%RH" % float(humidVal / 65536.0 * 100)
    
    print "Info, turning sensor off!"
    ch = p.getCharacteristics(uuid=config_uuid)[0]
    ch.write(sensorOff, withResponse=True)
    
  except:
    print "Fatal, unexpected error!"
    traceback.print_exc()
    raise

  finally:
    print "Info, disconnecting!"
    p.disconnect()
    
finally:
  quit()

On GitHub in the dhSensorTag2015 repository you will find these examples as well as additional examples to read the other sensors. 

A couple of things to bear in mind with these examples:

  • These examples were written using python 2.7.10 and were developed using V1.12 (Jun 23 2015) of TI’s firmware.
  • The barometer example calculation in the Andriod App doesn’t appear to be correct and therefore the example uses an updated calculation.
  • Data from all of the sensor examples, except the movement sensor, has been validated.

Friday, July 3, 2015

TI SimpleLink SensorTag 2015 - Reading Temperature and Humidity

Next up we are going to read the temperature and humidity from the HC1000 Humidity Sensor.  Each of the sensors that are accessible on the sensor tag has a GATT Service defined for it.  Below is the Humidity Service.

Handle Type Type (text) GATT Server Description/Value (text)
(hex) (hex) Permissions
0x27 0x2800 GATT Primary Service Declaration R Humidity Service
0x28 0x2803 GATT Characteristic Declaration R Humidity Data
0x29 0xAA21 Humidity Data RN TempLSB:TempMSB:HumidityLSB:HumidityMSB
0x2A 0x2902 Client Characteristic Configuration RW Write "01:00" to enable notifications, "00:00" to disable
0x2B 0x2803 GATT Characteristic Declaration R Humidity Config
0x2C 0xAA22 Humidity Config RW Write "01" to start measurements, "00" to stop
0x2D 0x2803 GATT Characteristic Declaration R Humidity Period
0x2E 0xAA23 Humidity Period RW Period = [Input*10] ms, (lower limit 100 ms), default 1000 ms

Before you can read a sensor value from the service you must turn it on.  For the Humidity Service this is done by writing a 01 to the handle at 0x2C labeled in the table above as Humidity Config.  Once you have turned on the Humidity Service you will read values from the handle at 0x29 labeled Humidity Data.

Referring to the table above we see that four values will be returned from left to right:

  1. Temp(LSB) - The least significant byte of the temperature data in hex.
  2. Temp(MSB) - The most significant byte of the temperature data in hex.
  3. Humidity(LSB) - The least significant byte of the humidity data in hex.
  4. Humidity(MSB) - The most significant byte of the humidity data in hex.

On page 14 of data sheet for the HC1000 Humidity Sensor are the formulas for converting this data into a temperature reading and a humidity reading.

  • Temperature in Celsius = (Temp(MSB) * 0x100 + Temp(LSB)) / 65536 * 165 – 40
  • Humidity = (Humidity(MSB) * 0x100 + Humidity(LSB)) / 65536 * 100

To get the values for the temperature and humidity readings follow the steps below.  In this example the values returned are 64 66 0c a2.

pi@raspberrypi ~ $ gatttool -b B0:B4:48:B9:2C:82 -I
[B0:B4:48:B9:2C:82][LE]> connect
Attempting to connect to B0:B4:48:B9:2C:82
Connection successful
[B0:B4:48:B9:2C:82][LE]> char-write-req 0x2C 01
Characteristic value was written successfully
[B0:B4:48:B9:2C:82][LE]> char-read-hnd 0x29
Characteristic value/descriptor: 64 66 0c a2
[B0:B4:48:B9:2C:82][LE]> char-write-req 0x2C 00
Characteristic value was written successfully
[B0:B4:48:B9:2C:82][LE]> disconnect
[B0:B4:48:B9:2C:82][LE]> exit

The resulting temperature is:

(0x66 * 0x100 + 0x64) / 65536 * 165 – 40 = 26.19 C

The resulting humidity is:

(0xa2 * 0x100 + 0x0C) / 65536 * 100 = 63.30%

Below is a bash script that will perform the commands above and calculate the temperature and humidity.

getTempHumidity.sh

#!/bin/bash
if [ "$#" != 1 ]; then
  echo "Need to pass BLE Address $0 <BLE Address>"
else
  echo "Turning on Temperature and Humidity Sensor"
  gatttool -b $1 --char-write-req --handle=0x2C --value=01
  echo "Getting Temperature and Humidity"
  for i in `seq 1 10`;
  do
    sleep 1
    str=`gatttool -b $1 --char-read --handle=0x29`
    # Discard everything up to and including the ": " in the

    # gatttool response.  Put the four bytes returned into an
    # array. Then swap the bytes and put the results in a variable. 
    #
Use bc to compute the temp and humdity.
    IFS=' ' read -a array <<< ${str#*: }
    temp="0x${array[1]}${array[0]}"
    temp=$((temp))
    humidity="0x${array[3]}${array[2]}"
    humidity=$((humidity))
    printf "temp: %s, humidity: %s\n" \
      `echo "scale=4; ($temp/65536*165-40)*1.8+32" | bc -l` \
      `echo "scale=4; ($humidity*1.0/65536.0)*100.0" | bc -l`
  done
  echo "Turning off Temperature and Humidity Sensor"
  gatttool -b $1 --char-write-req --handle=0x2C --value=00
fi

TI SimpleLink SensorTag 2015 - Reading the Device Name

In the last post we reviewed setting up a Raspberry Pi with Bluetooth to access the sensor tag.  We finished up by successfully performing a Bluetooth Low Energy scan which saw the sensor tag and returned the address.

In this post we will walk through reading and writing to the sensor tag using gatttool which is provided as part of the bluez Bluetooth stack.

Reading the Sensor Tag’s Device Name

As discussed in the previous post you will need to make sure your sensor tag is advertising.  When advertising the green LED visible on the back of the sensor tag will be blinking.  If it isn’t blinking try removing and reinstalling the battery.  If that doesn’t work replace the battery.

In the example below the hcitool lescan function is used to find the sensor tag.  It reports back the sensor tag’s address shown in green below.  Once you have the sensor tag’s address you should run gatttool providing –b and the address and a –I.  The –b tells gatttool that the next set of numbers is the address of the device you want to use.  The –I is for interactive mode.  gatttool has both an interactive mode and a command line mode.

As you can see the steps start with connecting to the device.  If the connect fails it could be because you waited too long and the sensor tag exited advertise mode or it could be that you have a version of gatttool that doesn’t work.  Put the sensor tag back into advertise mode, make sure the green LED is blinking and try to connect again.  If it fails this time it is most likely problem with gatttool.

Once you successfully connect to the sensor tag the green LED will stop flashing.  Enter the char-read-hnd command which stands for read characteristic by handle for handle 0x3 which is the device name.  You should get back the string of numbers below which if you convert from ascii values to characters spells SensorTag 2.0.

Disconnect from the sensor tag and the green LED should start blinking again and exit gatttool.

pi@raspberrypi ~ $ sudo hcitool lescan
LE Scan ...
B0:B4:48:B9:2C:82 (unknown)
B0:B4:48:B9:2C:82 CC2650 SensorTag
^C
pi@raspberrypi ~ $ gatttool -b B0:B4:48:B9:2C:82 -I
[B0:B4:48:B9:2C:82][LE]> connect
Attempting to connect to B0:B4:48:B9:2C:82
Connection successful
[B0:B4:48:B9:2C:82][LE]> char-read-hnd 0x3
Characteristic value/descriptor: 53 65 6e 73 6f 72 54 61 67 20 32 2e 30
[B0:B4:48:B9:2C:82][LE]> disconnect

[B0:B4:48:B9:2C:82][LE]> exit

Below is a bash script that will perform the commands above and translate the numeric values to their ascii equivalents.

getDeviceName.sh

#!/bin/bash
if [ "$#" != 1 ]; then
  echo "Need to pass BLE Address $0 <BLE Address>"
else
  # Discard everything up to and including the ": " in the
  # gatttool response.  Put the bytes returned into an array. 
  # Convert the bytes to ascii and print out.
  str=`gatttool -b $1 --char-read --handle=0x3`
  IFS=' ' read -a array <<< ${str#*: }
  for element in "${array[@]}"
  do
    printf "\x$(printf "%x" "0x$element")"
  done
  echo
fi