🌈 ESP32-S3 Rainbow: ZX Spectrum Emulator Board! Get it on Crowd Supply →
View All Posts
read
Want to keep up to date with the latest posts and videos? Subscribe to the newsletter
HELP SUPPORT MY WORK: If you're feeling flush then please stop by Patreon Or you can make a one off donation via ko-fi

We’ve just finished the first iOSCon hackathon. Some great work was done with the Affectiva emotion SDK along with some great stuff with Estimotes and Scentees.

I played with my Raspberry Pi and turned it into a fully functional bluetooth device communicating with an app running on my iPhone. I also plugged in the Scentee SDK and got the phone making a smell when the Pi picked up key presses on the remote control. I really wanted the Pi to make the smells, but the volume from the Pi’s audio jack wasn’t loud enough to activate the device.

To get my raspberry pi communicating I installed node and then used Bleno.

Bleno is a really nice node.js module for implementing Bluetooth low energy peripherals. For example to get an iBeacon running you just need the following code:

var bleno = require('bleno');
var uuid = 'e2c56db5dffb48d2b060d0f5a71096e0';
var major = 0; // 0x0000 - 0xffff
var minor = 0; // 0x0000 - 0xffff
var measuredPower = -59; // -128 - 127

bleno.startAdvertisingIBeacon(uuid, major, minor, measuredPower);

Assuming you’ve saved this file to ibeacon.js you can run it using:

$ sudo node ibeacon.js

To create a more fully functional device than a simple iBeacon we need to do a bit more work. I wanted to fully exercise my Raspberry Pi, using all the sensors that I’d wired up so far, connected up with my iPhone. This meant that I’d need to be able to write strings to my LCD display, get a stream of temperature readings and also get notified when an IR remote control button was pushed.

The basic outline of a bluetooth device looks like this using bleno:

var bleno = require('bleno');

bleno.on('stateChange', function(state) {
    console.log('on -> stateChange: ' + state);
    if (state === 'poweredOn') {
        bleno.startAdvertising('MyDevice',['b1a6752152eb4d36e13e357d7c225465']);
    } else {
        bleno.stopAdvertising();
    }
});

bleno.on('advertisingStart', function(error) {
    console.log('on -> advertisingStart: ' + (error ? 'error ' + error : 'success'));
    if (!error) {
        bleno.setServices([
            new bleno.PrimaryService({
                uuid : 'b1a6752152eb4d36e13e357d7c225465',
                characteristics : [
                	// add characteristics here
                ]
            })
        ]);
    }
});

We can now add some characteristics to our service.

For my lcd characteristic I created this:

var data = new Buffer('Send me some data to display');

// new characteristic added to the service
new bleno.Characteristic({
	uuid : '9e739ec2b3a24af0c4dc14f059a8a62d',
	properties : ['read','writeWithoutResponse'],
	onReadRequest : function(offset, callback) {
		if(offset > data.length) {
			callback(bleno.Characteristic.RESULT_INVALID_OFFSET);
		} else {
			callback(bleno.Characteristic.RESULT_SUCCESS, data.slice(offset));
		}
	},
	onWriteRequest : function(newData, offset, withoutResponse, callback) {
		if(offset > 0) {
			callback(bleno.Characteristic.RESULT_INVALID_OFFSET);
		} else {
			exec('sudo ./lcd "'+newData.toString('utf8')+'"');
			data = newData;
			callback(bleno.Characteristic.RESULT_SUCCESS);
		}
	}
})

This characteristic provides a read function and a write function. The write function shells out to a simple command line program that sets the contents of the LCD. The read function lets you read back whatever it is you stored.

#include <stdio.h>
#include <wiringPi.h>
#include <mcp23s17.h>
#include <lcd.h>

// BASE port for the SPI GPIO extension
#define BASE    100

int main (int argc, char *argv[])
{
	printf("Will set text to %s", argv[1]);
	wiringPiSetup () ;
	// initialise the SPI extension
	mcp23s17Setup (BASE, 0, 0) ;
	// setup the LCD
	int fd = lcdInit(2, 16, 4, BASE + 10, BASE + 11, BASE + 12, 
					BASE + 13, BASE + 14, BASE + 15, 0, 0, 0, 0);
	// print whatever is in argv[1]
	lcdClear (fd);
	lcdHome (fd);
	lcdPrintf(fd, argv[1]);
}

For my InfraRed receiver characteristic I wanted to be able to notify a connected client that there was a new value. To do this we use the onSubscribe event coupled with the node module infrared. The infrared module gives us a nice wrapper around lirc.

var IRW = require('infrared').irw;

new bleno.Characteristic({
	uuid : 'b747cdd0ddcc11e38b680800200c9a66',
	properties : ['notify'],
	onSubscribe : function(maxValueSize, updateValueCallback) {
		irw.on('stdout', function(data) {
			updateValueCallback(new Buffer(data.split(' ')[2]));
		});
		irw.start();
	}
}),

When someone subscribes to this property we start up irw and whenever it gets an event we send the button push back to the client.

We should probably also handle the onUnsubscribe event as well and stop irw.

For the temperature sensor we can use the ds18b20 module - there are several other modules that we could use, but this is the first one I found.

new bleno.Characteristic({
	uuid : '4b842c60ddd611e38b680800200c9a66',
	properties : ['notify'],
	onSubscribe : function(maxValueSize, updateValueCallback) {
		setInterval(function() {
			sense.temperature('28-0000057cc14e', function(err, value) {
				updateValueCallback(new Buffer(value + 'C'));
			});
		}, 1000);
	}
}),

When someone subscribes I kick off a repeating timer to read the temperature and send it back every second. Once again, we should really handle the unsubscribe event and kill our timer.

To run the server we do the following:

# load up the SPI driver
$ gpio load spi
#load up the temperature sensors
$ sudo modprobe w1_gpio
$ sudo modprobe w1_therm
# start up the server
$ sudo node server.js

That’s it for the Raspberry Pi side of things - if you have any other sensors or outputs you want to wire up then you can follow a similar pattern.

You can now test your device using one of the many bluetooth test applications that are on the app store or download the (source code)[https://github.com/StudioSophisti/BTLE-Tools] and run one yourself.

To build our own app we need to use the Core Bluetooth framework to access our peripheral.

// create the CBCentral manager
self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:nil];


// when it is powered on start looking for our peripheral
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    if(central.state==CBCentralManagerStatePoweredOn)
    {
        CBUUID *serviceUUID = [CBUUID UUIDWithString:@"b1a67521-52eb-4d36-e13e-357d7c225465"];
        [central scanForPeripheralsWithServices:@[serviceUUID] options:nil];
    }
}

// central manager discovered a peripheral
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
    self.peripheral = peripheral;
    [self.centralManager stopScan];
    self.peripheral.delegate = self;
    // make a connection to the peripheral
    [self.centralManager connectPeripheral:self.peripheral options:nil];
}

// connected, start discovering services
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    if(peripheral.state == CBPeripheralStateConnected) {
        [peripheral discoverServices:nil];
    }
}

// services discovered - find their characteristics
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
    for (CBService *service in peripheral.services) {
        [peripheral discoverCharacteristics:nil forService:service];
    }
}

// discovered some characteristics
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    for (CBCharacteristic *characteristic in service.characteristics) {
        if([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"9e739ec2-b3a2-4af0-c4dc-14f059a8a62d"]]) {
        	self.lcdCharacteristic = characteristic;
		}
	    if([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"b747cdd0-ddcc-11e3-8b68-0800200c9a66"]]) {
            self.irCharacteristic = characteristic;
	    }
	    if([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"4b842c60-ddd6-11e3-8b68-0800200c9a66"]]) {
            self.tempCharacteristic = characteristic;
	    }
        [peripheral readValueForCharacteristic:characteristic];
        [peripheral setNotifyValue:YES forCharacteristic:characteristic];
	}
}

// this is called in response to the readValueForCharacteristic and also when the peripheral notifies us of changes
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
	// get the value
    NSString *value = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
    // see which characteristic was updated
    if(characteristic == self.lcdCharacteristic) {
        // LCD display
    }
    if(characteristic == self.irCharacteristic) {
        // InfraRed remote
    }
    if(characteristic == self.tempCharacteristic) {
        // Temperature
    }
}

The first step is to create the core bluetooth central manager. We have to wait for it to power on and then we can start scanning for peripherals.

Once we’ve discovered the peripheral we can connect to it and discover the services it offers and once we find the services we can ask the service what characteristics it supports.

When we get the set of characteristics for the service we can read the current value and we can also subscribe to changes in the value.

When we read values or are notified of values we get a call to didUpdateValueForCharacteristic.

To write values to our new LCD characteristic we call:

    [self.peripheral writeValue:[text dataUsingEncoding:NSUTF8StringEncoding]
              forCharacteristic:self.lcdCharacteristic
                           type:CBCharacteristicWriteWithoutResponse];

That’s it! Bleno provides a really nice environment for wiring up bluetooth services and the Core Bluetooth frameworks makes it very easy to connect up to your device.

Related Posts

Raspberry Pi iBeacon - In today's blog post, I successfully turned my Raspberry Pi into an iBeacon using a Bluetooth dongle and following an Adafruit tutorial. I had to go under the hood a bit to make sure my dongle was recognized, but after adding some udev rules, it was good to go. Then, with a string of terminal commands, I was able to set it up as an iBeacon broadcasting a specific UUID. Testing it out with a basic iOS app, I was able to detect the signal strength from the beacon! While it wasn't the flashiest project, it was definitely satisfying to see it work.
GameKit and GameCenter - Had a blast at iOSDevUK - a fantastic conference that was not only filled with intriguing talks, but also offered me the opportunity to present my own talk. I discussed making real time multiplayer games using GameKit and GameCenter. The slides and notes from my talk are available for download if you're interested!
iOScon 2014 - Stoked to let you know I'm part of the team organising the first ever iOScon 2014 with SkillsMatter! Be quick and snag an early bird ticket for a mere £95! Jam-packed with the brightest minds in iOS development and design, this is your golden chance to keep ahead of the curve, explore new techniques, collaborate and grasp new technologies. Don't miss out on the unique iOS hacking weekend!
Raspberry pi Infrared Receiver - In this fun tech adventure, I successfully managed to sync my infrared receiver to my Raspberry Pi. This involved correctly wiring up my IR sensor, installing and setting up LIRC, and creating a new lirc config file. I explained each step in detail and shared my major milestones, which included seeing a list of pulses when the remote was pointed at the receiver. Now my Raspberry Pi is fully controlled by my remote.
Using ChatGPT for home automation - In another thrilling adventure with ChatGPT, I endeavored to integrate it with a Raspberry Pi, effectively turning it into my own personal light switch. My custom ChatGPT plugin, sporting just two endpoints, could revolutionize how we handle APIs, as it managed to control five different lights with simplicity and style. With a dash of YAML magic, ChatGPT managed to deduce the entire process, paving the way for future smart home projects. Big or small, the potential applications are endless and might even lead to computers communicating in human language!

Related Videos

Lots of Stuff - And a NEW PCB! It's a rare mailbag video. - In today's episode, I'm unboxing some goodies from PCB way - my super tiny esp32 breakout boards, which I'm planning to use to recreate a mini TV complete with speakers and a display. Also received some convenient adapter boards for easier testing. Excited to explore a new Arduino Nano esp32 based on a different, tinier module, and contrasting it with other products like the Tiny Pico. Also up for testing is a new mini wear electronic load compared to my old one, and an ATX power adapter for more USB ports. I'll be testing power banks, playing with inexpensive yellow displays and nunchucks for fun gaming projects, and testing out an RGB bead curtain with hackable possibilities. Also, under my ongoing experiments is a Raspberry Pi zero, turning into a 'Doom' playing device with added sound and game controllers. Finally, an air quality measuring device for detecting air particles, CO2 levels, humidity, temperature and other parameters is up for exploration as well. A whole array of fun projects queued up, so stay tuned!
ESP32-TV Version 3 - Is it done? - In today's project update, I'm excited to share that my ESP32-TV boards, fresh from PCBWay, are operating flawlessly! We've successfully dealt with the USB2244 conflict with the ESP32, and the battery charging issue is now a thing of the past. We've also made some awesome additions like a microphone to our board. The real MVP though, is the USB2244 chip that’s given us significantly improved read/write speeds - making it perfect for handling video files. Next on the agenda, figuring out a solution for the non-standard display connector. As ever, there’s progress, there’s problems, and there's David Bowie animated gifs!
M5Stack CORE2 - Can't remember why I got this, but it looks nice! - Hey guys! So today, I'm testing out this really cool app. It's pretty interesting - I think it could be really handy if you're into tech stuff. Let's dive in and see what it can do!
Surprisingly not CR*P - Vibing hardware - Well folks, what an adventure! After vibe coding our vibing button, I took up the challenge to vibe code the actual hardware for an ESP32 S3 dev board. Used a tool called at pile and gave it a whirl with some AI help from Claude. Interestingly, it handled everything from sourcing components with LCSC part numbers to wiring them up. Had a wee hiccup with missing capacitor in the RC circuit, but overall it was a thrilling ride watching the AI process! A bit of tweaking here and there, and we're good to go! Can't wait to see it in action.
Live GPIO Viewer - In my latest discovery, I found an incredibly efficient visualization tool from the last outpost workshop that upgrades how I check the status of the GPIO pins on my ESP32. It's super simple to use and allows me to monitor pin activities directly. I set up a couple of LEDs and a button on various GPIO pins to demonstrate its effectiveness and the results were fantastic. Although it currently supports only digital input and output and PWM, I'm optimistic it will expand with time. Thanks to the open-source community, you can find the setup instructions in a GitHub repo. This tool is a revelation and I highly recommend it.
HELP SUPPORT MY WORK: If you're feeling flush then please stop by Patreon Or you can make a one off donation via ko-fi
Want to keep up to date with the latest posts and videos? Subscribe to the newsletter
Blog Logo

Chris Greening


Published

> Image

atomic14

A collection of slightly mad projects, instructive/educational videos, and generally interesting stuff. Building projects around the Arduino and ESP32 platforms - we'll be exploring AI, Computer Vision, Audio, 3D Printing - it may get a bit eclectic...

View All Posts