Corbin's Treehouse - Corbin Dunn, Santa Cruz, CA
Plug Bug

Archive for 2015

Tricks for fast Bluetooth LE data transfers

I’ve been using the Adafruit LE friend to do some data transfer tests. With the basic setup, I was sending 1 kB of data in about 9.5 to 10 seconds. That is horribly slow! About 100 bytes per second. 

I did some research and found a couple of good links. This link about BLE discusses using the Nordic nRF chip and mbed to send data to a peripheral (i.e.: from the computer to the device). This link about sending data from the peripheral has some good tips when going in the other direction.  

I gave up trying to get the Adafruit LE friend to be fast and started working with the RedBearLab BLE nano (v1.5). It has been tough getting Xcode setup to compile code right, and  I ended up using “embedXcode” as a starting point, and the Arduino plugin for RedBearLab. I’d rather just use mbed, but the web experience is terrible, and I must use Xcode. However, I couldn’t get their scripts to compile..mainly do to case sensitivity issues (BLE.h and ble.h both exist, and my drive partition is insensitive). 

For the Nano, the bottom line was I had to edit the projectconfig.h file and use these settings:

    #define CFG_GAP_CONNECTION_MIN_INTERVAL_MS           20// corbin!! fYI, 40 worked. 50                     /**< Minimum acceptable connection interval */

    #define CFG_GAP_CONNECTION_MAX_INTERVAL_MS          40// corbin!! 500                     /**< Maximum acceptable connection interval */

    #define CFG_GAP_CONNECTION_SUPERVISION_TIMEOUT_MS  500// corbin!! 4000                     /**< Connection supervisory timeout */

The key part was not just the min interval, but the max; 500 was too large, and there is no API to control it (I can add some in for myself). 40 is required. I didn’t test lower…but lower might be better too. Too low, and the Mac (or iOS device) might not be able to keep up.

 When sending from an OS X app, I discovered I could get the most data by doing a “write without response”:

            peripheral.writeValue(subData, forCharacteristic: _uartTransmitCharacteristic!, type: CBCharacteristicWriteType.WithoutResponse)

 And batching the 20 byte data chunks every 2 nano seconds:

            let delay: Int64 = Int64(NSEC_PER_MSEC)*2// At about 4ns, it starts to get slower on the recieving end.

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delay), dispatch_get_main_queue(), { () -> Voidin



 Anything longer and it would be slower. This doesn’t make sense…as the BLE stack can’t really be faster than 7.5ms, but I’m sure the computer is doing a bit of processing and handling the BLE stack separately from my process. I have yet to test the code on iOS…it might need a larger delay, and might be slower. That is fine… my goal is to send files from the desktop to the device, and potentially vice-versa. 

With my above changes, a raw read of 1024 bytes (1kB) took 185ms; and it was fairly consistent. That’s about 5.4kB per second! I could probably improve it 6x more by using multiple characteristics to write at simultaneously, but I’ll test that later. 5.4kB/second is fast enough to start with.



I was curious if the Adafruit Bluefruit LE friend could be made faster. I know the GAP interval can be changed, so I made it match with:


Indeed, this did help! the UART service can read 1024 bytes in 3.5 seconds, instead of 10 seconds, or about 0.3kB/second versus 0.1kB/second.  This is reading the data from a teensy, which means the Adafruit BLE friend first reads the data, and then transfers it to the teensy over SPI. That protocol is somewhat slow, and it has a 16 byte payload (it really needs to be 20 bytes to transfer complete packets from the BLE). 
Of course…my test is ignoring the SPI transfer from the nRF chip to the teensy chip. This is also going to take some time, and might slow my numbers down a bit. I also need to learn how to write SPI code and make my own mechanism for transferring data. Lots more coding to do…

Adafruit Bluetooth LE SPI “Friend” with data loss and stalls (infinite loops)

I’m working on adding bluetooth support to my LED cyr wheel.  A long time ago I picked up an Adafruit nRF8001 breakout board — I was worried it was too big to fit in my wheel, and once I started working with it I realized it sucked. Specifically, the API was limiting; you couldn’t even set the peripheral’s name to something longer than 8 characters! Luckily they now have an “Bluefruit SPI Friend”, so I got one of those. Well, I ended up accidentally getting two. The first one I had sent via USPS, and it took 3 weeks to arrive! I thought it was lost, and I had to order another one via UPS 3 day shipping, and of course…they both arrive on the same day. 

The Bluefruit LE Friend is interesting. Adafruit’s produce page doesn’t even mention what chip it runs. You can discover it if you read their “intro page”; a long ways down they mention a nRF51822 flash updated, and you realize it is a nRF51 based ship from Nordic.  I’m hoping they will fix their page to be a little more clear on what is being used. The way it works is they created some closed source code that runs on the nRF51822 chip using the Nordic SDK. Their code talks to your microprocessor (Teensy/Arduino/etc) via SPI or UART. I picked SPI, because I thought it would be better and faster…but their implementation basically forces it to be UART. I was really hoping for regular callbacks for characteristic updates…but you don’t get those. You have to poll it using “AT” commands, and then parse the AT response. This is horribly slow, and the underlying SPI mechanism uses some special “Simple Data Transport” mechanism that transfers at most a 16 byte payload at a time. That is not good considering bluetooth transfers 20 bytes max at a time. Well, you can do more if you have more control, like from iPhone to iPhone…but not so with the nRF51 from what I can tell. 

The only way for you to quickly read data with the Bluefruit LE friend is to use their UART service which provides a transmit and receive characteristic. When you do this, the SPI protocol lets you receive packets at their SPI transfer packet size (yeah, just 16 bytes of “payload”, which is terrible..).  I figured I’d try it out.

I wrote a Mac app that connects to the Bluefruit LE. I chunk up data into 20 byte sizes, and send it (until I’m done) in: (Swift code):

    func peripheral(peripheral: CBPeripheral, didWriteValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {

      if characteristic == _uartTransmitCharacteristic {

            let dataLeft = _dataToSend!.length_dataOffset;

            if dataLeft > 0 {

                let amountToSend = min(dataLeft, _dataChunkSize)

                let subData: NSData = _dataToSend!.subdataWithRange(NSMakeRange(_dataOffset, amountToSend))

                _dataOffset += subData.length

                peripheral.writeValue(subData, forCharacteristic: _uartTransmitCharacteristic!, type: CBCharacteristicWriteType.WithResponse)






In my Teensy/Arduino code, I would read it. This a pure hack for testing the sending of data:

   if (m_ble.available()) {

        int count = 0;

        uint32_t start = millis();

        // Read in the size

        int32_t totalBytes = 0;

        m_ble.readBytes((char*)&totalBytes, sizeof(totalBytes)); // skanky!


#define bufferSize 1024

        uint8_t buffer[bufferSize];


        DEBUG_PRINTF(“totalBytes: %d\r\n”, totalBytes);

        if (totalBytes > 0) {

            int sizeLeft = totalBytes;

            uint32_t lastReadTime = millis();

            while (sizeLeft > 0) {

                while (!m_ble.available()) {

                    if (millis() – lastReadTime > BT_FILE_READ_TIMEOUT) {

                        DEBUG_PRINTF(“timeout! read: %d/%d\r\n”, count, totalBytes);

                        sizeLeft = 0;


                        // TODO: errors




                int read = 0;

                while (m_ble.available()) {

                    int amountToRead = min(sizeLeft, bufferSize);

                    int amountRead = m_ble.readBytes(buffer, amountToRead);


//                    DEBUG_PRINTF(“%c”,;

                    count += amountRead;

                    sizeLeft -= amountRead;

                    lastReadTime = millis();

                    read += amountRead;




        uint32_t time = millis() – start;

        DEBUG_PRINTF(”  read %d, time took: %d ms, %g s\r\n”, count, time, time /1000.0 );



This works, but I was frequently seeing my Teensy “lock up”. I realized some code was infinite looping in the SPI layer…but adding in logs was allowing it to work. This told me they had timing issues with a fast chip. Doh! But…even so packets wouldn’t come complete..and guess what — they were 16 of the 20 bytes I was expecting!  So, clearly this was something in the Bluefruit SPI layer.

I don’t really know SPI, but I took the time to learn how all their code worked, and figured out what was wrong. It makes sense, and I fixed it on a clone/fork:

 I sent them a pull request.. we’ll see what happens!

For everyone else…use my code.


Unfortunately, this mechanism is too slow. It takes 9.5-10 seconds to transfer 1kB. 270kB files would take 45 minutes to send over!  So, I’m looking into faster options..which I think means writing custom firmware with a RedBearLab BLE Nano. 



Utility sink counter top: The Sculpin IPA Counter

I wanted to touch up some of the areas next to my newly remodeled bathroom, and the laundry room needed a new utility sink. The plastic piece of crap I had was junk and I couldn’t find anything that would fit in the space I need. So, I made a custom cabinet, and planned on a nice concrete counter top similar to my last one.  This time I decided to do a more complex mold:

IMG 5666

I did a 3D design in Sketchup and made a template to go off of (based on my real top). The above shot is what it looks like in the mold, so it is upside down. The mold was quite tricky because I wanted a large overhang, and a backsplash that was all one piece. The sink itself is a stainless steel undercount sink that I ordered from eBay.

For the color, I picked Cheng Concrete’s PLATINUM color. I decided my specialty for this countertop would be to use brown IPA beer bottles as accent pieces. I had to drink a few six packs of Sculpin IPA, and scrape the labels off as a starter for this project. I broke up the bottles, and tumbled them in my cement mixer for a bit to get them to have soft edges. After a few minutes of tumbling, I could stick my hand in the broken glass and there were no sharp edges to cut me. I dropped broken pieces in the bottom of the mold and mixed a TON of them in to the main mix, hoping they would show up. 

Here’s a shot of the top right off of the mold, but before the bottom was removed (again, remember it is upside down):

IMG 5712

The Platinum color turned out a lot more gray than I expected. If I were to do it again, I would try to use a different color. I think the green would look really nice with the brown bottle pieces. Or, a color without aggregate (i.e.: don’t use Secrete, and custom mix your own concrete, or buy the D-FRC from Cheng). I will definitely do experiments before I ever do a kitchen top, because I want more control.

Here’s a shot of the top outside of the mold and turned over:

IMG 5718

There were some big holes from the glass pieces preventing concrete from settling just right, but I did manage to prevent a lot of smaller holes. I didn’t spray-glue the glass aggregate down on the “bottom” of the mold like I did for the last one. this helped with preventing extra holes, but probably was a mistake, as it allowed the glass to move as I poured the concrete in. I worked a lot of the concrete down with my fingers, doing shallow layers. The first layer was less than the steel re-enforcement. Another “new trick”  I did on this top was to weld the re-bar together. I welded it into just the right shape, as opposed to bending. This worked awesome!

I didn’t take hardly any pictures this time. Here it is all ground and sitting on top of the counter:

IMG 5728


IMG 5730

The gray makes it look a *lot* more industrial than I expected, but I like the effect. I wish I could have gotten more glass to show up, and if I do it again I will explicitly lightly glue pieces of glass to the mold (or use caulk) so I can control the placement of them.

In the pictures, you can notice that I ground the horizontal plane *a lot*, and the vertical planes very little. This was intentional to create the effect of industrial style.

I made a mistake with the placement of my sink knockout; it is slightly off for some reason, and I have to move the sink back ¾” or so to make it fit. I don’t know what I did wrong..but I should have double checked a bit more!

Luckily, the costs of this project were very cheap. The colors were about $70, concrete about $10, and the reset of the stuff (including the mold parts) I had leftover from the first project. Oh, Sculpin IPA was expensive..but worth it! So, for under $100 I had a nice custom top.




The Electric Bug Chronicles: Yeah, those skid marks on Highway 85 are mine…

Oh boy…

My bug needed new brake pads. I go through them crazy fast, as I drive down the famous “Highway 17” on a daily basis and my car doesn’t do any re-gen braking. This means I “ride the brakes” the whole way down. About a month ago the car started pulling hard to the left, so I popped the front tires off and the front right pad was way worn down. I ordered a new set from CIP1 (accidentally ordering the wrong ones first…) and put them on one evening 30 minutes or so before I had to go somewhere. The brakes screeched like mad for quite a while, and only now, about 200-300 miles later, are they starting to calm down. I know that this is partly because I didn’t grease them well enough, but I was okay with it. 

With fresh new brake pads I got to test them out right away at the intersection of Highway 17 and 85. I hopped onto 85 and quickly made my way into the “carpool lane” and started accelerating to avoid stalling traffic, but the car in front immediately started braking hard. I had to slam on my brakes, and did it a little too hard, locking up the tires. Yeah, no anti-lock brakes and I quickly pumped them to make me stop faster, and luckily I didn’t slam into the car in front of me (not even close — but I was nervous for a minute!)

A few days later I’m getting onto 85 again and see some long skid marks in the fast lane. Yeah, those were mine…

IMG 5663

The Electric Bug Chronicles: Cops.

Stories from the driver’s seat.

I have been pulled over at least ten times by the cops. It has become less frequent the past two years, although part of the reason is probably because I didn’t get to drive the bug a lot for the past year due to transmission trouble. I can recognize when it is going to happen, and let me share some of my favorite stories.
One time I was driving home on Highway 85 in the carpool lane. A cop pulls in the lane behind me, and starts tailgating me. Now, his lights aren’t on, and I’m not doing anything wrong. I figure he just really needed to get by me, so I pull into the next lane and let him pass. Then I immediately get back into the fast lane. The cop, now in front of me, pulls into the left breakdown lane area and slams on his brakes causing me to speed by him. He pops back into my lane right behind me and flips on the lights. I pull over into the breakdown lane, and he walks up to the window and says, “I was going to let you go but you got right back into the carpool lane!” I showed him piece of paper that validates the carpool lane stickers and said I have a zero emissions vehicle. He looks it over and says “alright”, and I take off ahead of him.
I’ve always liked monkeys and on one of my old cars I had found some stickers and put a call sign on the door titled “Monkey <star>”. My friend Jason laser cut some for my bug to continue the tradition:

The Electric Bug Chronicles: You’re kicked out!

Stories from the driver’s seat.

So, this happened about three years ago. I was driving the bug to the Summit Store in the Santa Cruz mountains, and pulled into the parking lot. It was a hot day, and my “air conditioning” is just a matter of rolling the windows down. Some guy was staring at me as I pulled in and gave a yell: “HEY! That doesn’t sound right — they are going to kick you out of the VW club!”. Hah! Yeah, vee-dubs have a distinctive sound and my car lacks it. I still plan to add a jetson soundtrack to the car at some point….
Below is a shot of the hood. If you look carefully you can see a unicycle in the back seat on top of the batteries. And a skateboarder.
IMG 5301

The Electric Bug Chronicles: Hey, Don’t Pull Him Over!

Stories from the driver’s seat.

In the past four or five years I have been pulled over by cops a lot. I always get set on my way without a ticket; so far I haven’t been caught for speeding.
One day, about two or three years ago, I was driving along on Highway 85 in the carpool lane. A cop pops behind me, and I know the drill before it happens: they are going to turn on their lights and pull me over. They do. As soon as they walk up to my window I hand them a little piece of paper that validates my coveted “white stickers”. They look it over, and send me on my way. 
But that isn’t the story! The fun part came the following day as I’m driving up Highway 17 in a lot of heavy traffic. I’m in the “fast” lane and see a motorcyclist splitting the lanes. He slows down beside my passenger window, and starts revving his engine to get my attention. Now, keep in mind my last encounters with motorcyclists hadn’t been so great. I roll down my passenger window (which isn’t easy), and the guy starts yelling at me: “I saw the cop pulling you over yesterday, and said no! Don’t pull him over — he’s electric!”. It made my day to hear him say that. Some people get it!
Here’s a picture of the motor from back in 2011. It looked really clean back then!  
IMG 5276

The Electric Bug Chronicles: F – You

Stories from the driver’s seat.

This is something that happened about four years ago, and the picture below is from 2011. 
The California HOV white stickers: the privilege to drive solo in the carpool lane during rush hour is very mjuch coveted by EV drivers. Back in 2011 it was a time when the yellow hybrid stickers had already expired, and people would only occasionally see a Tesla Roadster, and even less frequently a boxy EV RAV4 (unless your last name is Adelman). So, I was driving solo the carpool lane on Highway 85 one day, and a motorcycle comes by splitting the lanes. He slows down and takes a good peek at me going solo in the carpool lane, and assumes I was violating the law. His answer was to show me his middle finger, and then continue alone his way. Ah, ignorance! 
I would have taken this as a one-off event, but the same thing happened again about six months later! And I’m pretty sure it was a different motorcyclist. 
Below is a shot of the oft-missed white stickers. Some people hate putting them on their cars; I think they are a badge of honor!
IMG 5274


The Electric Bug Chronicles: Window down

Stories from the driver’s seat.

It was quite chilly out as I was driving home on 17 yesterday in the fast lane. I was surprised to see a guy in a red BMW with his window fully rolled down driving in the right lane and zipping past me a bit. He slowed down, and cranked his head out the window, pointing his ear at my car as I passed by. He then sped up and gave me a big thumbs up. He must have saw my carpool lane stickers, and was leaning out to “hear” how quiet my car is!

And now a picture of one of my charging spots at work. The Tesla and I are parked in non-marked EV spots. When we are done charging we don’t have to move our cars, and two other EVs can take the plug and start sucking electrons. 

IMG 5651

Bathroom Vanity / Remodel

A “walk around” video of my vanity:

I’m super happy with how it turned out! A nice eco friendly concrete countertop:

IMG 5634

(c) 2008-2017 Corbin Dunn

Corbin's Treehouse is powered by WordPress. Made on a Mac.

Subscribe to RSS feeds for entries and comments.

16 queries. 0.213 seconds.