Syntax highlighting in Squarespace 6

I held off switching to Squarespace 6 because of its lack of support for javascript-based syntax highlighters that I have used in Squarespace 5. I finally found a solution that may not be ideal but works. I am using Textmate 2 on the OS X that provides very nice syntax highlighting for most languages. Use the menu Bundels -> Textmate -> Create HTML from Document. Enter the HTML into a code block in Squarespace 6 and you have nice looking code. There is also the option of including line numbers.

Continuous Bluetooth LE data transfer to iPhone using the RedBear BLE shield

This is an update on our work on creating a bluetooth home health monitor in my class BME 440/441 "Senior Design in Biomedical Engineering".  The idea is to create an iPhone app that can connect to several Bluetooth LE sensors (ECG, EEG, Galvanic Skin response) and then display and record the data.  There will also be a data analysis component to actively monitor the health of the subject.

This post will describe a simple Arduino sketch that measures an analog signal at regular time intervals and then sends it through the Bluetooth connection of the RedBear BLE Shield. The sketch uses a timer to set the frequency at which analog pin 5 is measured and writes it into a buffer that is then sent through the BLE shield. I had to add a flag analog_enabled to make sure that the BLE shield only receives data when connected to the iPhone app. Unfortunately, there is a bug in the RedBear BLE shield software that makes it necessary to first receive data before it can send (I used BLE_Shield_Library 1.0). I could not get this project to work without the iPhone first sending at least one byte of data. In our case, when the iPhone sends "I" then the BLE shield starts sending. When the iPhone sends "0" then the BLE shield stops sending. I also included the parameters for 100Hz and 2Hz data transmissions.  Here is the sketch:

#include <SPI.h>
#include <ble.h>

#define ANALOG_IN_PIN      A5

boolean analog_enabled = false;

void setup()
  // initialize timer1 
  noInterrupts();           // disable all interrupts
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1  = 0;
  //100 hz timer setup
  OCR1A = 2500;            // compare match register 16MHz/64/100Hz
  TCCR1B |= (1 << CS11) | (1 << CS10);    // 64 prescaler
  TIMSK1 |= (1 << OCIE1A);  // enable timer compare interrupt 
  TCCR1B |= (1 << WGM12);   // CTC mode
  //2 Hz Timer Setup
  OCR1A = 31250;            // compare match register 16MHz/256/2Hz
  TCCR1B |= (1 << CS12);    // 256 prescaler 
  TIMSK1 |= (1 << OCIE1A);  // enable timer compare interrupt
  TCCR1B |= (1 << WGM12);   // CTC mode
  interrupts();             // enable all interrupts   

ISR(TIMER1_COMPA_vect)          // timer compare interrupt service routine
  if (analog_enabled)  // if connected
    // Read and send out
    uint16_t value = analogRead(ANALOG_IN_PIN);
    ble_write(value >> 8);

void loop()
    // read out command and data
    byte data0 = ble_read();
    // if data is "I" then turn on transmission
    // if data is "0" then turn off transmission
    if (data0==0x49) {
       analog_enabled = true;
    else if (data0==0x30) {
      analog_enabled = false;
  // Allow BLE Shield to send/receive data
  if (!ble_connected()) {
    analog_enabled = false;

Now to the iPhone app. It can be found here:

The entry screen is a table view that scans for BLE devices and add them to the table. I used the new iOS6 pull down to refresh method that is really neat. When you select any of the available BLE shields, a Bluetooth LE connection is established and a new screen appears that displays the RSSI, analog value, and number of bytes send.  The number of bytes send is a measure for how often the BLE shield sends the data that is accumulating in the arduino buffer.


A few remarks about the BLE SDK 0.4 that RedBear provides.  I was not very happy about the object design.  The sdk provides a ble object that has a method to scan for Bluetooth devices but then you can only connect to one of those devices.  That did not really make sense in terms of object oriented design.  There should be a more general class that is used to scan and then there should be individual BLE devices that you can connect to and those will provide protocols to receive and send data.

The iPhone program is quite simple but there was one aspect of its design that I struggled with for a while.  When switching views I had to transfer the ble object between view controllers.  In the table view I use the ble object to find all BLE shields in the area.  When I select one, I need to connect and then define all the protocols in the next view which all happens in the ble object.  Because the data protocols of the ble object are needed in the data view controller I need to pass the ble object to the data view controller in the prepareForSeque method as such:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    if ([segue.identifier isEqualToString:@"Show Bluetooth Data"]) {
        NSIndexPath *path = [self.tableView indexPathForSelectedRow];
        BSCViewController *s = segue.destinationViewController;

In the data view controller I need to set myself as delegate and connect to the BLE device in viewDidLoad. When I return to the table view I need to disconnect and tell the Arduino to stop sending data. At first, I tried to set the ble delegate to nil but that was not necessary.

- (void)viewDidLoad
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self.ble connectPeripheral:[self.ble.peripherals objectAtIndex:self.path.row]];
- (void) viewWillDisappear:(BOOL)animated
    NSLog(@"ViewController will disappear");
    if (self.ble.activePeripheral)
            //send BLE shield "0" to turn off transmission
            UInt8 buf[1] = {0x30};
            NSData *data = [[NSData alloc] initWithBytes:buf length:1];
            [self.ble write:data];
            // after that cancel connection
            [[self.ble CM] cancelPeripheralConnection:[self.ble activePeripheral]];

Back in the table view controller I simply reconnect the ble.delegate to self. This is necessary since viewDidLoad will only be called once.

    //reconnect delegate when coming back to table view
    self.ble.delegate = self;

Now lets talk about the performance. With this setup, I was able to send 100 data points (2 bytes each) per second easily to the iPhone. At 200 data points per second the buffer overflows and the BLE arduino sketch crashes. Believe it or not, the RedBear BLE Arduino library does not protect from buffer overflows. I am planning to do a similar test with Dr. Kroll's BLE Shield because for our project we need 200 data points per second per sensor.

Let me know if you have any questions.

MatPlotLib running in Cocoa under Xcode

I have always been frustrated that python does not have a nice GUI builder similar to what XCode provides.  Since I am a scientist and engineer, I am really fond of the combination matplotlib/scipy/numpy.  Here I will give an example of how to combine the two using the python cocoa bridge that is build into the python that comes with the operating system (in my case Mountain Lion OS X 10.8).  The only thing that you need to install for this example to work is the SciPySuperpack.

Here is the link to my example:

Here is how it's done. The basic idea is that the python code creates a png file of the graph and that this graph is sent to the Cocoa program via a NSData object. I then convert NSData into a png image and display it. To show how fast this happens, I added a slider to change the frequency of the sine function that is being displayed. Every time you change the setting a new graph is created and displayed. This technique is not suitable for graphs that need to change dynamically at a high frame rate but for most applications it should work.

First the Cocoa part:
//  SMPLAppDelegate.m
//  ShowMatPlotLib
//  Created by Helmut Strey on 4/23/12.
//  Copyright (c) 2012 Stony Brook University. All rights reserved.
#import "SMPLAppDelegate.h"
#include "Python/Python.h"
// Global pointer to app delegate
SMPLAppDelegate* myprogram;
// sendGraph function for sending graph through NSData
PyObject* sendGraph(PyObject* self, PyObject* pArgs)
    char* GraphStr = NULL;
    int length;
    if (!PyArg_ParseTuple(pArgs, "s#", &GraphStr,&length)) return NULL;
    [myprogram pythonOut: [NSData dataWithBytes: GraphStr length:length]];
    return Py_None;
static PyMethodDef sendGraphMethods[] = {
    {"SendGraph", sendGraph, METH_VARARGS, "submit string"},
    {NULL, NULL, 0, NULL}
@implementation SMPLAppDelegate
@synthesize window = _window;
@synthesize matplotlibView = _matplotlibView;
@synthesize freq=_freq;
- (void)setFreq:(double)freq
    NSString *mystring = [[NSString alloc] initWithFormat:@"drawplot(%f)\n" , freq];
    PyRun_SimpleString([mystring UTF8String]);
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
    Py_InitModule("MPL", sendGraphMethods);
    NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"init" ofType:@"py"];
    // load the main script into the python runtime
    FILE *mainFile = fopen([scriptPath UTF8String], "r");
    PyRun_SimpleFile(mainFile, (char *)[[scriptPath lastPathComponent] UTF8String]);
- (void)pythonOut: (NSData*)pngimage
    NSImage *matplotlibGraph = [[NSImage alloc] initWithData:pngimage];
    [self.matplotlibView setImage:matplotlibGraph];
    [self.matplotlibView setNeedsDisplay:YES];

And here is the python part (MPL is a module that I inserted from the Cocoa side):

import MPL
import numpy as np
import StringIO
from pylab import *
def drawplot(freq):
    figure(num=None, figsize=(9,7),dpi=60)

Sending Humidity and Temperature data with ZigBee


This is the solution that I posed to my senior design in Biomedical Engineering class (BME 440).  Over the last few weeks we covered basic Arduino programming (e.g. debounced toggle, DHT sensor), we did some basic ZigBee communication (AT mode).  The final project was to build a wireless Humidity, Temperature sensor that can transmit the data to a central computer. Above you can see the wiring to connect the humidity sensor DHT22 (see Adafruit's tutorial) to the Arduino/Xbee Shield.  For this solution we configured the XBee S2's to "ZigBee End Device API" with AP = 2 (escape enabled).  The central computer is connected to the Network coordinator XBee ("ZigBee Coordinator API AP=1).  The Arduino code uses the XBee-Arduino library and the Adafruit DHT library.  The python code is using the python-Xbee library.

 * Copyright 2012, Helmut Strey
 * This is an Arduino sketch that reads the humidity and temperature
 * from a DHT 22 sensor and transmits it using a ZigBee RF module.
 * It combines two example sketches that came from the XBee-Arduino library: Series2_Tx
 * and DHTtester from the adafruit DHT arduino library.
 * *
 * HumindityTempZigBee is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see
#include "XBee.h"
#include "DHT.h"
#define DHTPIN 2     // data pin of the DHT sensor
// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11 
#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)
// Connect pin 1 (on the left) of the sensor to +5V
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
This example is for Series 2 XBee
 Sends a ZB TX request with the value of analogRead(pin5) and checks the status response for success
// create the XBee object
XBee xbee = XBee();
// we are going to send two floats of 4 bytes each
uint8_t payload[8] = { 0, 0, 0, 0, 0, 0, 0, 0};
// union to convery float to byte string
union u_tag {
    uint8_t b[4];
    float fval;
} u;
// SH + SL Address of receiving XBee
XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x406F4973);
ZBTxRequest zbTx = ZBTxRequest(addr64, payload, sizeof(payload));
ZBTxStatusResponse txStatus = ZBTxStatusResponse();
int statusLed = 13;
int errorLed = 13;
void flashLed(int pin, int times, int wait) {
  for (int i = 0; i < times; i++) {
    digitalWrite(pin, HIGH);
    digitalWrite(pin, LOW);
    if (i + 1 < times) {
void setup() {
  pinMode(statusLed, OUTPUT);
  pinMode(errorLed, OUTPUT);
void loop() {
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  // check if returns are valid, if they are NaN (not a number) then something went wrong!
  if (!isnan(t) && !isnan(h)) {
    // convert humidity into a byte array and copy it into the payload array
    u.fval = h;
    for (int i=0;i<4;i++){
    // same for the temperature
    u.fval = t;
    for (int i=0;i<4;i++){
    // flash TX indicator
    flashLed(statusLed, 1, 100);
    // after sending a tx request, we expect a status response
    // wait up to half second for the status response
    if (xbee.readPacket(500)) {
      // got a response!
      // should be a znet tx status             
      if (xbee.getResponse().getApiId() == ZB_TX_STATUS_RESPONSE) {
        // get the delivery status, the fifth byte
        if (txStatus.getDeliveryStatus() == SUCCESS) {
          // success.  time to celebrate
          flashLed(statusLed, 5, 50);
        } else {
          // the remote XBee did not receive our packet. is it powered on?
          flashLed(errorLed, 3, 500);
    } else if (xbee.getResponse().isError()) {
      //nss.print("Error reading packet.  Error code: ");  
    } else {
      // local XBee did not provide a timely TX Status Response -- should not happen
      flashLed(errorLed, 2, 50);

Below is my python script that I used to receive the data.

#! /usr/bin/python
Copyright 2012, Helmut Strey
This is a python script that receives and outputs the humidity and temperature
that was wirelessly transmitted from a DHT 22 / ZigBee RF module.
HumindityTempZigBee is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program.  If not, see
from xbee import ZigBee
import serial
import struct
PORT = '/dev/tty.usbserial-AE01CQ5N'
BAUD_RATE = 9600
def hex(bindata):
    return ''.join('%02x' % ord(byte) for byte in bindata)
# Open serial port
ser = serial.Serial(PORT, BAUD_RATE)
# Create API object
xbee = ZigBee(ser,escaped=True)
# Continuously read and print packets
while True:
        response = xbee.wait_read_frame()
        sa = hex(response['source_addr_long'][4:])
        rf = hex(response['rf_data'])
        # if datalength is compatible with two floats
        # then unpack the 4 byte chunks into floats
        if datalength==16:
            print sa,' ',rf,' t=',t,'h=',h
        # if it is not two floats show me what I received
            print sa,' ',rf
    except KeyboardInterrupt:

Arduino debounced toggle

I posed the following problem to my senior design class:  create an arduino sketch that toggles an LED with a button push ( similar to turning on/off a TV with one button).  The students quickly realized that they had to include a deboucing algorithm otherwise the boucing would result in a random on/off state.  Here is my solution that is an extension of Ladyada's "better debouncer"

/* Better Debouncer Toggle
 * Helmut Strey 9/21/2012
 * this sketch senses debouced edges (high-low) (low-high) and toggles at (high-low)
 * This debouncing toggle circuit is modified from Ladyada's better debounceer that can be found below
int inPin = 2;         // the number of the input pin
int outPin = 13;       // the number of the output pin
int LEDstate = HIGH;      // the current state of the output pin
int reading;           // the current reading from the input pin
int previous = LOW;    // the previous reading from the input pin
int switchprevious = LOW;
// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 50;   // the debounce time, increase if the output flickers
void setup()
  pinMode(inPin, INPUT);
  digitalWrite(inPin, HIGH);   // turn on the built in pull-up resistor
  pinMode(outPin, OUTPUT);
void loop()
  int switchstate;
  reading = digitalRead(inPin);
  // If the switch changed, due to bounce or pressing...
  if (reading != previous) {
    // reset the debouncing timer
    time = millis();
  if ((millis() - time) > debounce) {
     // whatever the switch is at, its been there for a long time
     // so lets settle on it!
     switchstate = reading;
     // Now toggle the LEDstate when button is pressed
    if (switchstate == HIGH && switchprevious == LOW) {
       switchprevious = HIGH;
       if (LEDstate == HIGH) { LEDstate = LOW;} else { LEDstate = HIGH;}
    if (switchstate == LOW && switchprevious == HIGH) {
       switchprevious = LOW;
  digitalWrite(outPin, LEDstate);
  // Save the last reading so we keep a running tally
  previous = reading;

How to setup pyobjc with enthought python

In my first blog post ever, I will describe how I got pyobjc running using the enthought python distribution.  For a while I have been trying to learn Cocoa programming but I find coding in C (or objective C for that matter) very unproductive.  Coding in C just takes forever.  My favorite programming language for quite some time now is python.  It is a wonderful language and ideally suited for my needs especially with the numpy, scipy and matplotlib modules.

So recently, I have been trying pyobjc again.  I had given up several years back because it was just too hard to get everything running. pyobjc is a Cocoa-python bridge that should allow you to code Cocoa in python.  Unfortunately, pyobjc has almost no documentation.

So here is how you do it

1. Install XCode (I have Version 3.2)

2. Download and install enthought python (I installed EDP 7.0-2)

2. Open the terminal application and type:

sudo easy_install -U setuptools

sudo easy_install virtualenv

create a directory for virtual environment.  All my virtual environment live in "/Users/hstrey/programming".

virtualenv pyobjc23

cd pyobjc23

source bin/activate

easy_install pyobjc-core

easy_install pyobjc

virtualenv establishes a safe installation that does not interfere with the standard installation. Every time you want to use pyobjc go to your virtualenv folder and activate it by source bin/activate

Now we need to install the XCode pyobjc templates.  Mount using "Connect to server" from the Finder.  Copy the "File Templates" folder into "/Library/Application Support/Developer/Shared/Xcode" (create this path if necessary). Copy "Project Templates" to the Desktop and follow the instructions in the README.txt file to install everything.

Open Xcode and create a new XCode project.  Under User Templates/AA Testing you will find the pyobjc templates.  Choose Cocoa-Python Application.  Call the project test for right now.

Open  Add the following two lines before the import statements:

activate_this = '/Users/hstrey/programming/pyobjc23/bin/'

execfile(activate_this, dict(__file__=activate_this))

Before compiling the project we need to replace the Python framework that is used for linking with the enthought python framework.  Right-click on Python.framework and Show Info.  Now change the path to "/Library/Frameworks/Python.Framework".  We also need to adjust the project settings to adjust for the fact that enthought python is intel-only and 32-bit (at least my academic version is).  Go into Project - Edit Project Settings and select the Build tab.  Here delete all valid architectures except for i386 and select Build Active Architecture only.

Now you can click on Build and run and voila - the program should compile and an empty window will appear. Your first pyobjc application is running!