Monday 29 February 2016

Guitar EQ on-the-neck

We've got our guitar neck LEDs lighting up, displaying chord charts, scale patterns and more. We even have a nice swooshy rainbow effect and the ability to display play-along-tab. The entire display can be updated by sending serial data in a very simplified format (to reduce data length for faster refresh times) and it probably has a-hundred-and-one other uses we haven't even thought about yet.

One use we did think about was a volume display - like those VU diplays that were all the rage on boomboxes in the late 80s.

In super-flash versions, the EQ/VU display also had a "peak" marker, which trailed behind the actual volume/EQ bar graph. Since we already had a massive LED matrix, it was only a short while before we had a working VU meter.

During testing, we simply send a command to set the volume to a value between  0-15.

So far so good - we now had a VU meter function in our firmware which would display the VU on our guitar neck. All we needed now was to feed the guitar signal into an analogue input, convert into a 4-bit value and send that value into our function.

A guitar pickup typically outputs at around +/-100mV to +/-500mV. Some really "hot" pickups, with super-strong magnets can go as high as 1V output, but - because of the detrimental effect the magnets have on the string resonance - this is every unusual.

Typically a microcontroller, such as a PIC or an AVR, use the supply voltage as a reference for their analogue to digital modules. This means we could measure between 0V and 5V on an analogue input pin. If the guitar were to play relatively loudly, we might measure 0.5V on the input pin or 10% of the total supply voltage.

So our max range for measuring the voltage from the guitar pickups would be 0%-10% (since negative voltages would be "clipped" to zero). Which means, on a 10-bit A2D module, that normally returns 0-1023, we could expect to see values from zero to about one hundred.

This actually is almost workable for us. Let's consider what would happen if we just used our guitar output on an Arduino analogue pin, for example, Our VU meter has 15 segments, and we let's say full volume is 1V. We can expect to see analogRead values of 0-200  (since we're operating in the bottom 1/5th of the range). So at absolute full whack, we'd get an analogRead value of 200 and we'd need to convert this to a value of 15 (since our VU meter has 15 segments).

This means that each segment represents a change in the analogue input value of 200/15 = 13 (give or take a smidge). Which is fine. Except the A2D module on most microcontrollers has a degree of "drift" or an acceptable error range; if we allowed for an error of +/- 5 on the A2D, that means we've only got a few values between each step in the VU meter, It's quite possible that, even with a perfectly decaying audio signal, our meter display might fluctuate, rather than display the actual output voltage.

Our initial idea to overcome this was to use an op-amp.
This would allow us to not only increase the voltage range to feed into our analogue input, but also to "offset" it. But there is another way:  luckily, the AVR Atmega328P has an internal reference voltage. And this reference voltage is 1.1V - just about the maximum voltage we can expect from the guitar pickups. So by simply adding a single line in firmware


We can put the entire volume range onto the analogue input pin.
If we hit the strings really, really hard, and generate more than one volt, it'll cause the  display to "max out" - which would be exactly the behaviour we want!

Here's our VU meter running, with the output from a guitar going straight into an analogue input pin:

Don't you just hate videos of people playing un-powered electric guitars that are slightly out-f-tune? We hate it too.

Friday 26 February 2016

Overlaid scales and chords

Papastache was the first online guitar tutor to introduce us to the idea of "overlaying" scales and chords. That's not to say Steve Stine wasn't banging on about the "caged" system of playing some years earlier, nor that Griff Hamlin hasn't come around to using chords in his teaching recently either.

But Papastache was the first online tutor I recall that explained the idea of playing one particular scale (usually one of the pentatonic "boxes") and then visualising the underlying chord shapes that were being playing "underneath". By targeting one of the chord tones - whether it exists in the scale or not - his solos always sounded (to use his terminology) much more "legit" and melodic.

Here's the Papa with session studio maestro Tim Pierce explaining exactly how it works:

And here's Tim Pierce putting it into action with one of the most melodic blues solos I've heard in a long time!

The trouble is, being able to visualise both the scales and chords at the same time.
But as we've been building a light-up fretboard exactly to help us visualise things on the guitar neck, and because we're using full-colour RGB LEDs, it didn't take much to update the firmware to be able to display one or two patterns at the same time - either individually, or one on top of the other.

Here's a quick video to demonstrate:

First there's the pentatonic blues scale in blue. Then there's all the root notes in red. Individually, these are really useful things to know when playing blues guitar licks. Put them together and you're on the right track to creating some sizzling solos! Scales overlaid with chords...? Crack that little conundrum and you too can play awesome guitar like Tim Pierce! (ok, maybe there's a bit more to it than that.....)

After weeks of development and testing, it finally feels like we're actually, nearly, really there. Thanks Papastache, not only for the shout-out and the Kitchen Sink Bundle, but for the inspiration to create this thing in the first place!

Thursday 25 February 2016

Working with cheap bluetooth BTLE4 devices HM-10 BLE-CC41A

We recently got hold of some cheap bluetooth modules off eBay to create simple wireless serial communication between our hardware and a Unity app. They were listed as HM-10/ CC2540 /CC2541 serial wireless modules. At just over two quid each, they seemed too cheap to leave on the shelf!

The first thing, when using a module like this, is to try out some straight-to-serial AT commands. Our device had a six-pin connector rather than the four-pin shown. As it turned out, the outer pins are not strictly needed to make the device work (though it took a lot of messing about with the pin labelled EN - looking like an enable pin - before we worked this out and got any kind of response to our AT commands)

Like many of these kinds of plug-n-play type modules, interfacing with it is relatively simple, but there are a couple of gotchas to be aware of to get it up and running reliably. Getting the device to respond to AT commands was problematic at first. It didn't help that different online sources suggest trying them at different baud rates. We had the curious EN pin, and tried with that pulled high, pulled low and left floating, and still nothing worked.

The silkscreen on the back of the device says it needs a 3.6v-6v power supply, but the TX/RX pins are labelled with a legend saying level 3.3v

So we tried the device on a 3.3v usb-to-serial adapter. It was barely enough to power the bluetooth device - it definitely needed more than 3.3v on the Vcc pin to get it to power up! But at 5v, we still had no response on the serial monitor/putty window. We tried using a level shifter and even set our serial adapter to run at 3.3v, while providing a dedicated 5v supply to the bluetooth board (ensuring that we had a common ground between the two). Still no reponse to our AT commands.

In a fit of desperation, we tried the HMComAssistant exe from some random chinese website, which appears to be little more than a serial monitor type application. Still nothing. Then, entirely by accident, we sent an AT command and got the response OK.

It turns out that our device only responds if the AT command is immediately followed by a carriage return/line feed combination. Suddenly we were up and running! AT+HELP (followed by CrLf) returned the following list of commands:

Command Description
AT Check if the command terminal work normally
AT+RESET Software reboot
AT+VERSION Get firmware, bluetooth, HCI and LMP version
AT+HELP List all the commands
AT+NAME Get/Set local device name
AT+PIN Get/Set pin code for pairing
AT+PASS Get/Set pin code for pairing
AT+BAUD Get/Set baud rate
AT+LADDR Get local bluetooth address
AT+ADDR Get local bluetooth address
AT+DEFAULT Restore factory default
AT+RENEW Restore factory default
AT+STATE Get current state
AT+PWRM Get/Set power on mode(low power)
AT+POWE Get/Set RF transmit power
AT+SLEEP Sleep mode
AT+ROLE Get/Set current role.
AT+PARI Get/Set UART parity bit.
AT+STOP Get/Set UART stop bit.
AT+START System start working.
AT+IMME System wait for command when power on.
AT+IBEA Switch iBeacon mode.
AT+IBE0 Set iBeacon UUID 0.
AT+IBE1 Set iBeacon UUID 1.
AT+IBE2 Set iBeacon UUID 2.
AT+IBE3 Set iBeacon UUID 3.
AT+MARJ Set iBeacon MARJ .
AT+MINO Set iBeacon MINO .
AT+MEA Set iBeacon MEA .
AT+NOTI Notify connection event .
AT+UUID Get/Set system SERVER_UUID .
AT+CHAR Get/Set system CHAR_UUID .
Note: (M) = The command support slave mode only.
For more information, please visit
Copyright@2013 All rights reserved.

+VERSION=Firmware V3.0.6,Bluetooth V4.0 LE

After a bit of wire-swapping, we discovered that the device is entirely 5v tolerant, and runs just fine off a usb-to-serial adapter, running at 5v without any external power supply, nor requiring any level shifters on the tx/rx lines. We used the command AT+NAMEChrisBLE and successfully changed the name of our bluetooth device - so when a phone scans, it appears with our custom name. That's pretty nice already! But the list of commands don't look anything like the those in the official HM-10 datasheet.

After lots of scrabbling about on the net we eventually found this article ( which explains that our devices were in fact BLE-CC41a clones. The biggest giveway to this is because they are missing the crystal on the corner nearest the antenna - something "genuine" HM-10 modules have, but - as chinese clone manufacturers are wont to do in their drive for cutting costs (and, seemingly, corners) at every opportunity - these ones don't.

Knowing all this made finding the datasheet much easier!

Having got our bluetooth device up and running, and responding to AT commands, the next job is to connect and transfer data via serial. After all, that's what these things are for! So we booted up our trust old Galaxy phone and ran the BLEGattList app.

There's our (renamed) BLE4 device!

A list of all services on our bluetooth module

The device exposes four lots of service information. Just at the moment, we're not entirely sure what all these mean. From experience with our darts app, we know that somewhere in this little lot should be a couple of services for sending and receiving data. Cue a couple of hours poking about trying lots of long strings of GUIDs with our earlier bluetooth code, trying to establish a connection.

After trying the generic access service (and successfully connecting, but failing to exchange data) it turns out that it's our Unknown Service that we need to connect to. This service exposes just one characteristic

Unlike the BLEMini from RedBearLab, this module's UUIDs do actually follow the framework described for generic bluetooth serial devices (namely a pattern that matches 0000-xxxx-1000-8000-00805F9B34FB whereas the BLEMini is nothing like this!). The hardest job we had was finding both the read and write characteristics for the module.

Using the BTLE4 module from Unity's Asset store, we already had a simple framework for connecting our phones to bluetooth devices - simply "plug in" the device/connect, read and write characteristic UUIDs and the module does all the clever work, passing data to and from the bluetooth device.

With the RedBear module, everything works fine. Except the module is written specifically for modules that have different UUIDs for their read and write characteristics. Modules - like our cheap clone - that use the same characteristic UUID for both read and write don't work fully with the Unity libraries, as written. If you're using the same Unity libraries for bluetooth (and, at less than a tenner to easily add bluetooth support to your iOS and Android apps, why not?) the offending lines are inside the void connectBluetooth function:

if (IsEqual (characteristicUUID, _readCharacteristicUUID)) {
     _readFound = true;
} else if (IsEqual (characteristicUUID, _writeCharacteristicUUID)) {
     _writeFound = true;

The fix is simple enough to do (but took a good few hours to track down and fix!).
Without this change, it's possible to put data into your app and get it to appear on the bluetooth module, but not get it back the other way. The ELSE part of the IF statement is the culprit. So let's just take it out!

if (IsEqual (characteristicUUID, _readCharacteristicUUID)) {
     _readFound = true;

if (IsEqual (characteristicUUID, _writeCharacteristicUUID)) {
     _writeFound = true;

And with this code in place, we're able to send and receive data via our app to our new, cheap, chinese-knock-off bluetooth modules!

Now we can add wireless serial comms using bluetooth (and ultimately app-based support) for hardware for about the cost it would take with those nasty, unreliable 433MHz radio modules. That's the cost of cheap radio serial, with the reliability and speed associated with wifi, without the messy SSID/password set up.
Look out for bluetooth being shoved into just about everything from now on.......

Monday 22 February 2016

Parsing Guitar Pro files

Anyone who has ever picked up a guitar and tried to learn a song has probably come across guitar tab. Back in the 90s, when my only intention for playing guitar was to be able to pick one up and play Ugly Kid Joe's Everything About You as a party piece, tab books were expensive things.

I had a few tab books, and learned a few guitar solos (long since forgotten) by wrote. I had no idea what I was doing - just that if fret 15 followed 12, then drop a string and repeat, swapping 15 for 14 (I know, complex or what?!) it sometimes sounded a little bit like a tiny fragment from the guitar solo section.

Thanks to the interwebs, there are guitar tabs all over the place. And most of them are free. And many of them appear on the ultimate-guitar website. And the most popular tab-reading software is Guitar Pro. So - having created a guitar with a light-up fretboard - it only made sense to be able to parse some GuitarPro files and present them in LEDs on the physical guitar neck.

So, this weekend, we set about trying to untangle the .gp5 file format.
It's a bit of a nightmare, but just as we were making progress, one of the nerds downloaded a newer, GuitarPro 6 file. Initially our reaction was to ignore it. Just stick with .gp5 because - although navigating the file structure was a pain, it was doable.

Then someone found Tuxguitar.

And things got a whole lot easier.
Because TuxGuitar imports just about all of the GuitarPro tab files, and can export as XML.
This is brilliant for our guitar software. Although the XML format does lose some of the guitar notation (string bends, slides etc) this doesn't really matter to us, since we're only using the actual fret markers to make lights appear on the guitar neck. "Articulation" will have to be left for the player to interpret anyway.

And from XML we quickly had a php/jQuery based webpage up and running, able to parse the tab files.

Our webpage converts the messy time signatures found in the tab files and simplifies them somewhat. It splits the song up into measures and from the start of each measure we simply track number of milliseconds between each note to be played.

This will allow us to play the tablature back in real-time on our guitar neck - simply read a note from tab and make it light up on the guitar neck. Wait a few milliseconds and send another serial packet to change the note being displayed. That's all there is to it!

So far we've managed to import GuitarPro files, but we're making very fast progress on being able to edit the tablature online (so players can create their own riffs and leads, or edit pre-written tab to suit their preferred fingering of specific chords and so on). Look out for a video showing the tablature being played out in real time, very soon!

For the eagle-eyed amongst you, you've no doubt recognised the signature "lick" in the image above, from Metallica's Enter Sandman. Here's how it appeared in TuxGuitar

If nothing else, proof that we're importing the tab correctly at least!

Sunday 21 February 2016

Arduino sucks

Anyone who knows me, knows of my distaste for Arduino.
It's not (just) snobbery. Arduino is a great introduction to electronics for a lot of people. My biggest problem with it, is that all too often, that's where it ends.

I've been doing some consultancy work, and using Arduino.
The decision to use the Arduino platform was made because, apparently, people who know how to use Arduino are more plentiful than people who know how to use PICs or other, more obscure microcontroller parts. This is certainly true. And - being more plentiful - the inference is, cheaper to hire. This may also be true.

But plentiful access to developers is a double-edged sword. Just like everyone who ever used Microsoft Word became a web developer in the late 90s, the problem with plentiful developers is that it naturally introduces a wide range of skill levels. And while there will be some people who really know their stuff and producing good quality, well-designed, solid robust code, there will be an awful lot of charlatans doing more harm than good by publishing poor-quality code. And to anyone who isn't an expert, all developers start to look the same....

Arduino is a community supported project. Unfortunately, a lot of people not only using, but supporting, Arduino are..... well, there's no nice way to say it.... not very good.

There are a lot of libraries out there which are really badly written. Even from sources which have now become synonymous with Arduino and a source of "good code".

The early wav-shield code from Adafruit was very clever - it enabled people to play wav files in their embedded projects with nothing more than an mcu, an sd card holder and a speaker.

But the code was also pretty terrible.
Almost the entire sound playing routine was written inside the interrupt routine. There were so very few cycles remaining between interrupts that anything that tried to use the wav-shield code ended up being very flaky indeed - mcu resets, lost variable values and processor lock-ups were not uncommon.

I don't know if the code has been updated since, but when we looked at it before embarking on writing our own wav-player (entirely from scratch) a few years ago, the wav-shield Arduino library was horrible. The trouble is, hardly anyone who used it actually bothered to read the source code. They just copied-and-pasted what they'd been given and got on with the more interesting elements of their project. That's fine. If you're trying to get a job done, get on with finishing the job, not messing about understanding the inner workings of how it all works.

And that's also the problem with having lots of "Arduino developers" available when choosing Arduino as a platform. There are loads of developers who have used Arduino, but the number who actually know what they are doing is a tiny fraction of this. So when your project hits a problem, and you're left with a developer who only knows the copy-and-paste approach to embedded development, you've got a problem!

Arduino isn't really a "stable" platform for developing anything but the simplest of projects. And the level of support offered by the community isn't as great as the number of users of the platform would suggest (let's not get into how flaky the actual AVR mcu hardware is - that's a whole other discussion - this is just about developers and people who actually code for the things).

  • Sometimes it's just badly-written libraries.
  • Sometimes it's libraries written by people who've never read a datasheet, who don't even understand that a microcontroller is made up of registers and how to manipulate them correctly.
  • Sometimes it's libraries written by people with little electronics understanding, so they try to "code out" inaccuracies created by not understanding the things connected to the microcontroller pins.
  • Sometimes it's libraries that are incompatible with each other (libraries that take over the timer1 module for example, can't be used with other libraries that also want to use timer1). Sometimes fixing this would be as simple as moving one library onto another timer. But that might affect something else using another library - since not all libraries make it clear which mcu peripherals they use and which they need exclusive access to.

Despite this, after spending a day or more trying to understand why something isn't working properly, even when the problem comes down to timer conflicts or something along those lines, it's not even shonky code that makes Arduino so horrible to work with.

If the problem is a badly written library, well, it's all open source so there's nothing stopping you from rolling up your sleeves and finding and/or fixing whatever it is that's stopping the code from working (although by this time, it'd probably be quicker and easier to have developed the entire code yourself from first principles!)

What really makes Arduino stink is that the language tries to shoehorn C++ style 16-bit development into an 8-bit, flat, procedural architecture. Just one tiny example is the overuse (and abuse) of ints (16-bit, 2-byte integers) that litter example Arduino code found all over the internet.

But it gets even worse than this. Because sometimes, it's actually necessary to use the "wrong" datatype, to get code to work consistently. When you're using "correct" datatypes, and performing simple, core tasks, and the results are inconsistent, then there's an inherent problem with the language.

Long-time users of Arduino just laugh this kind of thing off or simply shrug and say "it's designed for artists, not programmers". But that's just denying the problem; if you're using the language correctly, but it's not working properly (or - worse still, as we recently found, works inconsistently, introducing intermittent errors) then it's not really fit for purpose!

Here's just the latest example of Arduino "weirdness" we encountered recently.
It involves writing a two-byte (16-bit) value to eeprom, and recalling it back. Casting different datatypes while assuming the language will automatically convert others is a classic way of introducing errors that are almost impossible to find, let alone debug and resolve.

So, partly for code-portability reasons, and partly to avoid data-type errors creeping into code when it's moved from one platform/language to another, on any 8-bit platform, we always write values as 8-bit values. That means that a two-byte/16-bit value is written to eeprom (and called back) as two single byte values.

The first byte value is the value we wish to store, divided by 256.
The second byte value is the remainder of the value to store.

When recalling the value, we get the first byte value from eeprom and multiply by 256. Then get the second byte value from eeprom and add it to the first. This technique works whatever language you're working with and for any platform.

Except Arduino.

Arduino screws things up.
More worryingly, it sometimes screws things up.

Here we create two byte data types.
A byte data type is an 8-bit, single byte value.

We pull back the first value from eeprom, multiply by 256, pull back the second and add it. In this example, our values were 0x6B and 0xA3. In real money, that's (107*256) + 163 = 27,555. Google agrees; put 0x6BA3 to decimal into the search bar and Google tells you it's 27555

Arduino says the value is 27299.

Even - as shown in the screenshot above - when casting data values into ints the problem doesn't go away. We even tried - although not shown above - taking each value from eeprom and performing a binary AND operation with the value 0xFF to force each eeprom value into the range 0-255. Arduino still pulled out the second value as a 32-bit value and treated it as -163, not the positive integer 163.

Frustratingly - the problem doesn't always manifest itself. So sometimes - depending on exactly which values you use/store in eeprom - the correct total value is arrived at. And it's not always the second of two bytes that is handled by the compiled code as  32-bit value; sometimes it is treated like an 8-bit value, sometimes the first byte is messed up, sometimes both, sometimes neither.

This isn't even about poor coding.
There's nothing wrong with manually splitting a two-byte/16-bit value into single bytes and storing them in eeprom. What really stinks is that the Arduino language/compiler makes such a mess of perfectly legitimate code.

What amazes us more than anything is how these "quirks" are generally accepted by the Arduino community. No less than five different long-term Arduino users told us, having had this problem demonstrated to them, to simply use an external eeprom; not to fix the problem, but to avoid using the parts of the Arduino architecture that are problematic.

And that's why Arduino sucks.
The actual platform is flaky.
A lot of the libraries and published code are flaky.
And problems are not fixed - they're just avoided.

I'm sure plenty of the nerds at nerd club will disagree. I've probably upset a lot of people with this rant. But, among the respected developers I deal with, a lot of them also agree that Arduino is the Duplo of microcontrollers suited only for rapid, hobby prototyping, and not really suitable for "commercial" or "industrial" uses.

I think I'll take the Arduino approach. I can't be bothered to fix the underlying problems with Arduino (of which this is just one of many). So I'll work around them. By simply avoiding them - by avoiding Arduino entirely (wherever possible!)

Saturday 20 February 2016

Setting up a stratocaster guitar and trussrod

"Setting up" is one of the most important - and often mis-understood - things you can do with a guitar. It's the difference between having a plank of wood that's almost playable, to having an instrument that is a joy to play.

There are loads of things involved with setting up a guitar, and many guitar players - even new, novice guitarists - will have a go at changing a few things to make their instrument more playable.

The most common change - and one of the easiest to do - is to change the string height at the bridge. Often people call this "altering the action"; and while changing the string height will indeed affect the action, there's more to altering the action than simply changing the string height!

Imagine that we're working on a theoretically, perfectly flat/level guitar neck:

With a very low bridge setting, the strings sit very close to the fingerboard. This is known as a "low action". To change the height of the strings, we alter the bridge saddles

With the bridge height raised, the strings are much further away from the fingerboard.

This is known as having a very high action. Generally speaking, most guitarists believe that having a low action is preferable.

A guitar with very high action will be difficult to play. Pressing the strings onto the frets will require a lot more effort and your fingers will tire more quickly. Playing single-note licks and solos is difficult. Bending strings (for that classic signature blues sound) is made hard, as your fingertips snag under other strings as you push them upwards on the neck.

Despite this, high action guitars do have some benefits. For a start, they're louder. If you have a particularly "grabby" playing style, you can play chords without pulling them out of tune. But, generally, a high action on a guitar makes it more difficult to play, and most guitarists seek to reduce the action as much as possible.

But at the same time, it's also possible to have too little action. A guitar has to have some degree of action, to allow the strings to vibrate.

Now guitar strings vibrate in an "ovoid" shape, with the maximum movement at about half way along the string. So while, at first, it seems that a perfectly flat guitar with very low action would be most preferable, to get a "good" guitar set-up, it's actually a balancing act between action height and playability.

The Aiersi kits we got recently are really well made. We put a couple together and made perfectly playable guitars, with the fingerboards held down with nothing more than a bit of double-sided tape! There was no messing about with shims of having to adjust the neck angle or any of that nonsense - simply bolt together, add some strings, and play away!

We lowered the bridge saddles, to make the action even lower, and played a few simple runs. You can hear that although the notes can be played (they don't "fret out" indicating that the fingerboard is, indeed, well made, and perfectly flat) as the strings vibrate, because there's no gap between the string and the next fret, there's a persistent buzz.

Luckily, this problem can easily be solved - but it's one that a lot of guitarists are quite nervous about tackling. Basically, we need to adjust the trussrod.

our fingerboard and neck are perfectly flat

The trussrod is a piece of steel running along the length of the neck.
When the strings are tightened up on a guitar neck, they actually pull the head of the neck forwards, creating a slight "bow" in the neck. The steel rod inside the neck counter-acts against this pulling force.

Somewhat counter-intuitively, a well-set up guitar actually has a tiny bit of "bow" in the neck. This is called relief. Because our guitars are made to be absolutely perfectly flat when assembled, they have no relief in the neck. By adjusting the trussrod, we can reduce the amount of "backbend" used to resist the pull of the strings.

Now it's understandable that, if you're playing around with a thousand-pound instrument, you might be a bit nervous about playing with the trussrod, given that it can have a massive impact on the instrument's playability.

But - then again - if you're trying to play a thousand-pound guitar and the trussrod isn't correctly set-up, you may as well be playing a second-hand, eighty-quid Encore copy!

A lot of websites bang on about how critical the trussrod is to making your instrument playable and how, if you get it wrong, you can render your guitar useless. They're not wrong. But it's not irreversible. And it's not difficult to do. It's scary - especially when it's your best/ most expensive instrument, and the temptation is to take it to a guitar shop and have someone else do it (I know, I've spent £40 to get my Yamaha set up before now, only for it to "settle" a few days later and I ended up with an unplayable guitar anyway!)

Just stick an allan key into the trussrod hole and turn. Give it a quarter of a turn. Leave it for ten minutes or so then try the instrument again (really, you should think about slackening off the strings, adjusting the rod and then re-tuning them but if you've got a floating tremolo, this can be a laborious task!). The strings will be all out of tune. That's ok. Just check that each note can be fretted and doesn't buzz.

Here's our guitar after the trussrod has been adjusted

Remembering that the fingerboard is only held on with double-sided tape at the moment, this  is actually a good result! It shows that our neck has a slight "bow" in it (which is why the fingerboard is lifting off slightly, as it tries to rest in a straight line across the two highest points).

Until the fingerboard is permanently fixed, it'll be difficult to play the guitar properly. But by pressing the fingerboard down onto the (ever-so-slightly-curved) neck , we're able to fret notes along its length and demonstrate that each note can be fretted and played without any buzz at all.

And that's how to set up a guitar neck/trussrod!

Wednesday 17 February 2016

Playable stratocaster guitar

We've had a dozen guitar kits cluttering up the place at Nerd Towers for a few days now. Unfortunately real life and work and having to pay the rent keeps getting in the way of messing about making cool stuff. But tonight, determined to make a playable instrument, we took a couple of hours to put one together.

As Steve always says - measure twice, cut once.
Although we had nothing to cut, there was plenty of drilling to do - so we made sure to measure each hole three times. I'm sure he'd go berserk at the idea of us using a long screw as a centre punch - but at least it shows progress: at least we knew to use a centre-punch this time (albeit a rather crude alternative)!

We started with the bridge, for no other reason that it needed six holes and looked quite interesting to do. We later learned that this wasn't the best place to start, but at the time, we were quite pleased with our bridge mounting.

A common mistake that people make with their stratocasters is making the bridge fixed to the body -what's often called a "hardtail" bridge. This basically means bolting the bridge down tightly so that it cannot move. But the bridge on a stratocaster is designed to float a bit.

So we used a 3mm bit for the guide holes, and tighted up the screws all the way down, before backing them off about half a turn. After doing this on all six screws, the bridge was in place...

....but still had room to lift slightly if necessary.
On the back of the body, we fitted the springs. It's the floating bridge and the tension in the springs that gives the stratocaster it's distinctive "jangle-y" sound.

We lined up the two screws for the plate holding the springs, drilled 3mm pilot holes, then fitted them to the back of the bridge

Some people prefer the springs to be straight, rather than this more common "fan" arrangement. Purists will argue about how it affects the tone. We just thought it looked nice like this. By tightening the two screws, you can increase the tension in the springs on the back.....

....which forces the bridge to sit tighter onto the body at the front. Note that the bridge still isn't "fixed" - it can be moved about - slackening off the springs at the back would allow the strings (when fitted) to completely lift the bridge off the body - this is a great technique for using the whammy bar and doing dive tricks and the like. But it does make tuning the guitar (especially with new, un-stretched guitar strings) an absolute nightmare!

Next it was time to drill and screw on the "bolt-on" neck. This was the bit that gave us most trepidation. One mis-placed screw and the entire neck could end up on the wonk!

There's not much to go on when fitting the neck. Maybe we could have put a couple of strings in place, temporarily and used them as a guide. But at this stage we were just thrilled not to have bolted it on upside-down or back-to-front.

We laid the fingerboard out on the neck where we thought it should go, and checked the distance from the inside of the nut to the string contact point on the bridge.

A perfect 25.5 inches. Things were looking promising!

Some double-sided tape on the neck (it's not a permanent fix - we'll be taking it up shortly and drilling it for the LEDs - plus the fingerboard isn't actually structural; it's the truss-rod inside the guitar neck, not the fingerboard that resists the tension in the string) and the fingerboard is ready to fix into place

Not looking bad at all! With the tuning pegs fitted to the head, we're ready to string her up!

So how does it sound?
Well, in my hands, pretty bloody awful.
Actually, that's not really true. It sounds exactly like what it is - a stratocaster guitar; the strings and the tone are bright and have a slight 60s sound to it. The neck needed hardly any adjustment - perhaps a quarter turn on the truss-rod to clear up the tiniest bit of fret buzz.

None of the electrics have been soldered up, so we've no idea how it sounds through an amp. But it actually plays quite nicely. We're going to have to leave it overnight, for the joints and the strings and everything to settle, and then tune it up again (the intonation is a bit off, with the harmonics at the 12th fret a little sharp, compared to the fretted notes) but even fresh off the bench, with no set-up at all, it sounds plays like quite a nice little guitar.

All we need to do now is to make sure the playability isn't affected when there's a 0.6mm PCB mounted under the fingerboard. It'll probably be another couple of days before we can get the CNC working, to rout one out, but it's exciting to know that - before we've butchered them at least - the guitar kits actually make half-decent, playable guitars!

Thursday 11 February 2016

Darts sight-right checker

After becoming engrossed with the darts on BBC over the New Year, it didn't take long for darts to become another fleeting infatuation. So, obviously, it was only a matter of time before a Winmau Blade 4 dartsboard and a set of Ted "The Count" Hankey "arrows" turned up in the post, thanks to those kindly Amazon carriers.

Darts is a great game. And easy to get into. Just about every pub has a dartboard, tucked away somewhere. And a decent set of darts - even like those used by top darts players - can cost less than twenty quid.

It wasn't long before the five and nine beds on my board were starting to take a battering. Hitting anything like a twenty, let alone a treble, was a pipe dream. To land anywhere in the twenty bed more than once an almost impossibility.

(it took only about forty-five minutes to get two arrows in the twenty bed at the same time!)

Despite this, I was getting better at "grouping" the darts - getting them within a few millimetres of each other in the board - just, more often than not, grouped around the nine or twelve beds.

Apparently, it's quite a common problem. You stand in front of the board, line yourself up with the treble twenty bed and hurl the darts. Except they drift off to one side. Or if they do land in the centre bed, they hit the board at a bit of an angle (the photo above shows a typical left-handed throw, with the arrows leaning into the board from the left).

And it's all because where the dart is being thrown from is not in front of the treble twenty. Although I might be looking at that bed, where I'm standing is not actually in line with it! Just a single image from the Winmau website gave me the answer to what was causing the problem, as well as how to fix it!

(this image shows the problem encountered by most right-handed players; as a left-handed player, I have the same problem, but mirrored).

So, at the next nerd night - and with some help from the others, as I can't always be trusted with sharp instruments - we set about building our own "sight right". The idea is that you place the "sight-right" at the foot of the dartboard, with the white line in-line with the bullseye. Then, stand at the oche in your normal throwing position. If you're off-centre, the white line appears as two broken pieces.

Move along the line, left or right, until the white line becomes a single, solid, unbroken line. At this point, you should be centred with the dartboard. And any arrows thrown should land in the centre; and if they do, because you're no longer throwing them into the board from an angle, they should be nice and straight. And nice straight darts mean that even if you miss the bed you're aiming for, the dart isn't lying at an angle, effectively blocking it for the next dart that follows.

The sight-right from Winmau isn't expensive. But when you add in carriage, and consider it's just a few bits of wood, it made sense to use up some of the stuff we had lying around at the BuildBrighton workshop.

First up we grabbed some 18mm mdf and cut the base.
Then, with some 18mm offcuts, created a "shelf" and stuck this on top.
Lastly, to make a three-part rather than a two-part sight-line, we stuck some 30mm batten on top of the shelf

All that remained as to draw in the centre-line and paint the whole thing (matt black, using blackboard paint, so as not to be dazzled by lights reflecting off it).

We also saw examples of these "sight-rights" online where the double-ten and double-sixteen lines were also painted in. As double-sixteen is a popular finish in darts (and double-ten a favourite for left-handed throwers) we thought it a good idea to include these too.

As most binary-number-addicts will understand, double-sixteen is a great number to finish on because if you miss by just a fraction and land in the single sixteen bed, you can immediately move on to double eight. Score a single eight and you can go straight to double four, then double two and finally double one. Other finishing scores usually mean having to throw for a treble or other non-finishing score at some point, if you keep missing the double!

So begin with, we stuck a dart in the middle of the bullseye and hung another dart from it using a bit of cotton (there's nothing hi-tech about this project!)

And marked the wood where the tip of the other dart touched

This is the centre-line for the sight-right. We then repeated the process by placing the first dart in the dead centre of the double 16 and double 10 beds. After marking the lines, painted the whole thing black and painted the white lines (with an old almost-crusty-dry pot of Tip-Ex!)

Here's the finished thing:

And the result - immediately after using the sight-right - was that the best score from three different players was.... 37.

Unlike a lot of "try-and-see" projects, we're refusing to call this a failure. The sight-right does actually work. It  makes throwing the darts easier and you feel more relaxed when throwing from the correct place. The trouble is, there isn't a decent darts-player between us! Maybe - with some help from the sight-right - this will change over time.....

[EDIT] Just a few days after using the Sight-Right, I noticed my darts grouping was getting better. Unfortunately there was no-one else to witness it, so I'll only be accused of setting the whole thing up, but here's a photo of the highest score I've ever managed at darts.

Onnnne - huuuunndred and forrrrty!

Wednesday 10 February 2016

Installing OpenCV/SimpleCV on Raspberry Pi

On a recent project, we were having difficulty successfully detecting the presence (or lack of presence of) people. On the face of  it, it's quite a simple problem: stick an ultrasonic range finder inside a device. When someone stands in front of the device, the range goes down, indicating that someone is present.

In fact, this is exactly the approach we initially used. But it wasn't without it's problems.
To begin with, the range sometimes didn't go down. It actually went up! A bit of investigating and we think we found out why: place a hard surface in front of an ultrasonic sensor and you can get very accurate distance measurements

But put a big lump of meat, dressed in a woolly jumper in front of the sensor (a person) and the sound is dampened. And reflected off at funny angles. And basically mangled, to the point where the return echo actually takes longer than it should to get back to the transducer. Now, instead of consistent, solid readings, you get a measurement greater than you should - not because the object is far away, but because it's squishy and has absorbed/distorted the sound waves.

High end ultrasonic sensors also include a degree of self-calibration. So the problem is exacerbated if it's getting a load of differing values reflected back. Quite often, the sensor will "calibrate out" the squishy meat-sack and it appears that nothing is there.

So when you first stand inbetween the sensor and a hard surface (like a wall) the range reading actually goes up, not down. This is ok, we can simply look for a difference in range and use that as a trigger. But as long as you stand in front of the sensor, dampening/absorbing the sound, the sensor will re-calibrate and return "nothing found" results (usually it just returns it' maximum range value, but the result is the same).

Move about, and occasionally, in among the "maxed out" values, you'll see a shorter value, indicating that the sensor has seen something up close. But the values are only just good enough to use as a trigger - and certainly not for determining how close a person is. It's the difference between a "person sensor" and a "movement sensor".

We tried a couple of other ideas - PIR sensors work well, but only as movement sensors, not person-proximity sensors. We even tried laser-range-finders. But if you wear dark clothes, it's enough to scatter the returning laser beam to make the readings inconsistent (they are designed, after all, to bounce off the walls of a house, not people).

So we came up with a bit of  a weird idea: we want to detect when someone is standing in front of our device. Preferably, detect when they are also facing the device. People have faces. Why not use face detection?

  • If they're in place, but facing the wrong way, we don't want to trigger.
  • If they're not in place, but their arm gets in the way of a sensor, we don't want to trigger.
  • If they're too far away - or too close - we don't want to trigger.

We basically want a trigger when someone is stood at the right distance, facing the device.

So why not stick a camera in the device, shove a Raspberry Pi inside it and use face detection? Most face detection routines can create a bounding box around a face - we could use these co-ordinates to determine how close (big) the face is and how far off-centre it is, to determine whether or not we should trigger.

What a handsome guy! And not looking weird at all.

So for the first time in a long while, we set about putting a fresh install on our model B+ Raspberry Pi. Getting the operating system working was easy enough - there are plenty of tutorials on how to do that - copy noobs onto an 8Gb sd card and let it do it's thing.

Getting the PiCamera working was equally as straight-forward: Google PiCamera and follow the instructions (even the sudo apt-get install stuff is just a matter of using copy-and-paste and letting the Linux/Debian operating system do its thing)..

Installing SimpleCV wasn't quite so easy.
The instructions at looked simple enough. But simply didn't work!

Trying the sudo pip install command that a lot of websites link to caused a whole raft of error messages, with no real clue about what was going on, nor how to fix it (I'm sure the answer is in there, but for a Linux-noob, using copy-n-paste to install stuff, it all looked like gobbledegook!)

Luckily, the answer was found at which suggested that trying to "pip install" something meant the package was download and unzipped/deflated into memory. And that was just too much for our little Pi to cope with.

So we used sudo wget to download the zip file to disk, then sudo pip install file to install from a file location, rather than a URL. This time the install worked just fine, and it wasn't long before we were bashing Python scripts to capture faces and highlight their locations:

Although our code is, by now, heavily modified, here's where we started from, capturing an image from the Raspberry Pi camera and processing it, to find a face:

# Programma test Haar Features

import picamera
from SimpleCV import Image
import time

with picamera.PiCamera() as camera:
       camera.resolution = (640, 480)

       if trovati:
              for trovato in trovati:
                     print "Trovato alle coordinate : " + str(trovato.coordinates())
              print "Non trovato"


The last stage for our project is to have the camera continually running (it takes about 10 seconds to initialise, so we'll set it running, then leave it) and use the GPIO pins to make a request. We'll use an Arduino/PIC or other microcontroller to send a pin high - effectively asking the Raspberry Pi "can you see a face". During the image processing, the Pi holds a different GPIO pin high to act as a "busy" line. When the controller detects a high-to-low transition on the busy line (as the Pi returns it low to say "finished processing" the controller can then query the "face found" GPIO on the Pi. The Pi, in turn, will raise this pin high is a face has been found in the image, or pull it low if none have been found.

The nice thing with the SimpleCV processing is that you can use something like:

if faces:
       for face in faces:

              c = face.coordinates()
              x = c[0]
              y = c[1]
              dist = face.distanceFrom()
              h = face.height()
              w = face.width()              

              print "Face found at coordinate : " + str(x)+"," + str(y)
              print "Distance from centre: " + str(dist)
              print "Size: " + str(h) + "h " + str(w) + "w"

and then compare the location and size of the face bounding box(es) to decide whether or not to include that face in your list of results

So we can use only the largest (closest) object, or compare it's x/y co-ordinates to determine how "off-centre" it is. Or perhaps ignore only faces that have a specific height/width (as a crude distance calculator). The possibilities are endless!