Skip to main content

Wanted: ted or alive




By now, you would have realised that not all technology is useful.  In fact, some are despairingly the opposite.  And stuffing a cuddly teddy bear full of servo motors and plastic in an effort to make it bop to high-tempo dance music rates rather highly on the scale of pointlessness.  So silly... it transpires... that it deserves a rather long post on it.  Obviously.

Because once you overcome the acute disappointment associated with discovering that TEDx has nothing to do with teddy bears throwing "X shapes" on the dance floor, you naturally start to wonder: what platforms there are out there for these stuffed mammals to express their inner emotions?  And express them - of course - to 160 beat-per-minute nightclub bangers.

So it's time once again to bear with us, because on that rather ridiculous pretence, we'll proceed to lose our bearings, and bear it all through a (hopefully) laughable attempt at resuscitating a stuffed companion.  Using a Raspberry Pi, and some Python.

Let's get this over and done with...

In the highly-regarded (and wholly fictitious) field of teddy-matronics, a branch of engineering in which no-one has yet been awarded (or even been considered for) a Noble Prize, possibly the most important requirement is to be able to make your friendly bear move.  And most of the time, this will involve the use of a motor of some description.  Now, clearly, if we wanted the teddy's head to continuously spin 360 degrees like a horrific out-take from the The Exorcist, we'd be getting our hands on some Direct Current Motors.  But we're not in the business of (intentionally) terrifying little kids.  What we want are motors that we can control positionally, rather than rotate repeatedly.  And that task, ladies and gentlemen, bears and girls, calls for the use of Servo Motors.

Remember; we've used the tetchy micro-servos before - the cheap and cheerful SG90s.  But we also started to have a go at using some bigger HiTEC servos.  Ultimately, your choice of servos will depend on how heavy the teddy bear's fluffy limbs are going to be, how fast you want to be able to move them, and most importantly... how much you are prepared to invest financially on - what is, at the end of the day - a rather immature and nonsensical project.

But don't let that deter you.  Search on eBay (*other auction sites are apparently available, so we're told) and you'll find plenty of used servos on sale.

Below is what a ragtag assortment of HiTEC servos procured from the aforementioned auction site looks like.  They vary in condition, model and age... which means they all have slightly different characteristics (most significantly the torque, and speed).  But are we bothered?  Clearly not.  We care about our little project... but it turns out, not that much*.

*You will most definitely care, however, when you inevitably start to want your robotic creation to do other "useful" stuff - like walk.  Vast majority of these servos (such as HiTEC HS-311 and HS-422) will simply not pack enough torque to lift sizeable robot anatomies against the forces of gravity. 

Here is a glorious photo of the servos in the winning 6-4-3 formation... a commonly adopted football tactic of the England 13-a-side team under the tenure of Fabio Capello.  And yes, you probably noticed.  We have a few screws loose.


At this stage, if there are bits missing, don't panic.

It's easy enough to stock up on some spares.  Servo horn hardware sets can be found online (part number 56317 for HiTEC standard size if you really must know) which contain all the goodies to make your incomplete HiTEC servos, in the wise words of Atomic Kitten, whole again.  Other servo manufactures are also available.

Let's swiftly observe an insanely boring picture of some servo hardware sets, snoozing unassumingly in a cardboard box.  They don't quite know yet what absurdity they are about to be asked to participate in.


So what exactly is it that we're doing with all these servos, we hear you ask (if you dared to make it this far, that is, and you haven't simply succumbed to sheer disbelief, and decided to abstain from the Internet).  Good question.

And it's probably best answered using a suspect schematic.

Below is a completely un-technical diagram, outlining how these servos are going to produce genuine, WWF-certified (or should that be this WWF judging by some of the vicious moves) dancing teddy bear-like movement.  Yes, that's right.  12 servos in total, 3 in each of our raving friend's 4 limbs.  Just as well, as we only got our hands on the 13 servos (remember the formation above) - leaving only 1 spare.  Don't worry.  England, it transpires, are often out of the World Cup, even before they can use up all three of their substitutes.


That was it.  Flashed before your unsuspecting eyes was the crude master-plan.  Disappointed?  You will be now.  As we'll inevitably have to revisit a few boring concepts first, if this dancing teddy is ever going to... well... dance.

But before we go any further, let's give this affable party-goer a wholly inappropriate name.  Yes, it's a teddy.  And quite frankly, faced with an enormous amount of work, we're not feeling very imaginative at this point.  So let's start with Mr. Ted.  But because we want to make it sound like it will be loaded with advanced tech (which we assure you, it will not), let's append a totally unnecessary "E" to his name... a trend made fashionable by a certain Pixar robot no doubt originally called a mind-numbingly boring "Wall".  Furthermore, because we want to provide the illusion that this invention has been painstakingly personalised just for you (again, which it clearly has not), we'll add a totally misspelt U for good measure.

There.  Everyone, meet: Mr. Ted-E U (pronounced ted-ewwww).  We can now sleep easily on the knowledge that there's no real risk of a trademark lawyer turning up on our doorstep (partly because no-one would ever want to claim such a ridiculous title).  And there is now a wholly unintended political undertone to this bear as well, with Brexit and all that.  Now let's take back control of our Pi-boards.  Whatever that means.

Do you remember that servos require Pulse Width Modulation (PWM) signals for positional control?  Raspberry Pi's GPIO pins can emit these PWM signals, as we demonstrated before.  But let's be honest.  We are going to need to control a small army of servos.  Well.  Army of 12 to be exact.  And pretty much the survival of the entire teddy bear rave subculture will depend on it.  Therefore, it's probably best to get your hands on a bit of additional electronics, something equipped with a dedicated PWM chip, that can dish out and control its own PWM signals without relying on what will after all be an overworked Pi.

To this end, we've chosen an Adafruit PWM / servo HAT.  It's equipped with a PCA9685 chip that specialises in handling PWM signals.  You can control up to 16 channels (i.e. servos) per board using the Pi's I2C serial protocol.  You can stack many more boards too, if you're thinking about converting your affable Mr. Ted-E U into a fluffy, animatronic centipede.  You'll have to solder some headers to the board.  These didn't come pre-soldered, unfortunately.

Incidentally, we don't really have a need to stack our HAT onto the top of the Pi.  In fact, we'd prefer not to.  So here it is.  With its headers soldered crudely to point upwards.  We then use a limited number of cables to connect only the required pins to the Pi's GPIO pins.  Much neater this way, we feel.  And, more importantly, it allows us to continue to connect random gadgetry to our Pi (more on this later with our ventilation challenge), in whatever way we choose.  Mr. Ted-E U could soon be equipped with a (fish) smoke machine, or failing that, and less ambitiously, a jet pack.  Thanks for the reusable rockets, Elon Musk.  We expect a GPIO interface and a GitHub driver for them from you, sometime soon, so that we can adhere to Cascada's advice of evacuating the dance floor.  Quite literally.


Here are the pins we cabled up for the HAT.  We're sure we missed a few, but hey it works without things exploding.

Pi GPIO pinAdafruit HAT pinDescription
1 (3.3V)1 (equivalent physical position)3.3V to supply the chip with power
3 (BCM 2)3 (equivalent physical position)SDA - serial I2C data
5 (BCM 3)5 (equivalent physical position)SCL - serial I2C clock
6 (0V)6 (equivalent physical position)Ground (0V)

Also, don't forget to use a "reliable" power source to power the servos via the board.  Servos can draw a lot of current when they are holding position against external force, which Mr. Ted-E U will need to do if he's been basing his rave moves on the lifts from Dirty Dancing.  That's why we'll be using a dedicated 5V mains power supply to power the servos via the HAT, instead of a battery pack.  We'll only be using the USB battery pack to keep our Pi powered.

This is how it all looks, when the servos are connected up together.  Scattered around the spaghetti of colourful cables are the secret ingredients to Mr. Ted-E U's epic night out.  There's nothing more to it, electronically that is.  For now.  Which is just as well as we bored ourselves stiff with all this cabling.


Just in case you hadn't worked it out by now, the black cable from each servo is the ground (0V), red the positive voltage (5V in our case), and yellow the PWM control signal.

And better late than never.  The Adafruit 16-channel PWM / Servo HAT is carefully described in its accompanying document.  You should read it.  Really.  Beware though.  It looks like Adafruit have updated the Python libraries since the document was first created so most of the commands don't appear to marry up with what's currently on GitHub.

Now back to our magical servos.  Clearly, the plan is to use a Python program of some sort running on Raspbian OS to control the servos.  So let's quickly give this a go.

First, we need to enable I2C (if it's not enabled already from a previous project).  And that can be achieved through the Raspberry Pi Software Configuration Tool.  I2C, or Inter-Integrated Circuit, is a serial protocol we'll be using to talk to the HAT.

sudo raspi-config


Once you find the I2C option in the menu, you can enable it.  Make sure you acknowledge the Pi's giddy declaration that I2C has been enabled by pressing "Ok".  Otherwise, the Pi might think you're quite rude.


Then, according to the Adafruit documentation, we need two packages before we can start to play around with the Python library.  If you're lucky, you may actually already have them.

sudo apt-get install python-smbus
sudo apt-get install i2c-tools


Let's then see if we can detect our HAT using the I2C serial protocol.

sudo i2cdetect -y 1

Default I2C address of the HAT is 0x40.  You can stack many more HATs, to control a larger troupe of servos, in which case you would need to solder some jumpers on the HATs to make them appear at different addresses on the serial bus. But for now, as it's default, it should appear at 0x40 if it has all been cabled up properly to the Pi.


Is it there yet?  Good.  This finally means we can start to play around with the servos in Python by sending the HAT some seriously serial data. 

As with most things coding, it's best to give existing libraries a go first, because it means that someone else has probably thought about it already, and has done most of the work.  It's likely to have been tested by the masses too.  Conveniently, Adafruit has one right here.  It allows us to control the servos via the PCA9685 chip using a few simple commands.

Let's use pip to install it.

sudo pip3 install adafruit-pca9685


...which should eventually complete with a heart-warming message.


Now, let's see if we can control the servos we have connected, using Python.

The module we need to import is called Adafruit_PCA9685.  We'll then instantiate an Adafruit_PCA9685 object representing our servo HAT found at 0x40 and call it servo_controller_1.  And we'll try this first interactively using IPython.

ipython3

And once in IPython...

import Adafruit_PCA9685
servo_controller_1 = Adafruit_PCA9685.PCA9685(0x40)


Then, we'll set the frequency of the chipset's PWM signal to what the servo motors accept.  HiTEC documentation informs us that 20ms is the pulse width, which in Hz, is 50Hz.

servo_controller_1.set_pwm_freq(50)

HiTEC also states that their servos require a pulse duration of 0.9ms to 2.1ms - with 1.5ms the centre.  To work out what to send the PCA9685 via I2C (remember we're not sending PWM signals directly from Python here), there are some friendly calculations required.  Oh no.  Some maths.  Just when you least expect it.

Essentially, we want to work out a "tick value", which is based on a percentage of 4096.  And that percentage is the percentage of the pulse duration in relation to the PWM pulse width (20ms).  Confused?  Let's get confused even more.

For example:
  • Required servo PWM pulse duration for middle position is 1.5ms
  • 1.5ms is 7.5% of the required servo PWM pulse width (20ms)
  • 7.5% of 4096 is 307
  • So we want to send a "tick value" of 307 via I2C to set the servo to its middle position
We're not sure if this is all there is to it.  But we found it to work - so it's good enough for us.

Same can be worked out for any values in between the minimum and maximum servo positions.  Here's a table of what we think we need to send to represent the extremities of the servo positions:

Servo position / anglePulse duration% of width (20ms)PCA9685 I2C tick (% of 4096)
Min0.9ms4.5%184 (approx)
Middle1.5ms7.5%307 (approx)
Max2.1ms10.5%430 (approx)

Incidentally, "ticks" quite simply sound horrible; so we'll use the term "angle" or "position" interchangeably for the remainder of this post.

So, something like this should move the first servo (channel 0) to minimum angle, centre then maximum angle.  That's right.  Using the set_pwm() method of the PCA9685 class allows you to send the required I2C signals, without having to worry about what I2C is doing behind the scenes.

servo_controller_1.set_pwm(0, 0, 184)
time.sleep(1)
servo_controller_1.set_pwm(0, 0, 307)
time.sleep(1)
servo_controller_1.set_pwm(0, 0, 430)

Which it does.

It's worth noting that this doesn't necessarily equate to 0 - 180 degrees of movement.  You might want to investigate working slightly further out of the pulse duration range (<0.9ms or >2.1ms) to see if you can get any more angle out of your servos (chances are that you won't, and they'll just hiss unhappily).  As it happens, we're not that fussed.  As we don't think any of Mr. Ted-E U's joints should enjoy the full 180 degrees of movement.  After all, we're taking him to a rave.  Not a yoga class for new age contortionists.

Now let's test all our servos, one by one.  This simple bit of code will let you cycle through all 12 channels, and test the servos.

servo_channel = 0
while servo_channel <= 11:
    print("testing servo on channel", servo_channel)
    servo_controller_1.set_pwm(servo_channel, 0, 184)
    time.sleep(1)
    servo_controller_1.set_pwm(servo_channel, 0, 430)
    time.sleep(1)
    servo_channel += 1

It's not a bad idea doing this each time a used servo arrives through your letter box (as they routinely do in our household).  You'll be able to spot the dodgy ones quite quickly this way.  It's also useful to run it again later on when the servos are in place, to work out what degrees of movement should be permitted for each joint.


Well, well, well.  What we have now is the ability to control all of our servos using Python, via the HAT using I2C.  Which goes a long way towards making Mr. Ted-E U groove.

So what's next?  We are at a point where we need an actual donor teddy.

And it turns out that there are plenty of them looking for a new home immediately after Valentine's Day.  That's if you don't mind them coming with big red hearts, ribbons, and other tacky paraphernalia.  It's best to eye them up in person in a shop (but not too intensely to attract the concerns of staff and shoppers), to make sure there's plenty of space inside the stuffed mammal to insert all our gizmos. For this reason, buying them online maybe a little too risky. Most eBay sellers are simply reluctant to answer your questions about the girths of the soft toys they have put up for auction.

Here's the bargain bear we managed to pick up, from UK's favourite teddy-matronics parts distributor - ASDA - where we also bought some bed sheets advanced stage curtains that heavily feature as the backdrop in this post (yes, garish yellow and pink variants are always in the bargain bin - probably because no sane person would want to sleep in them).  Detach the heart and ribbon from the furry heartbreaker, and it looks no different to a normal bear (but with a slightly crooked and alarmingly disproportionate head).  Thick arms and legs are perfect for housing the servo motors and various plastic contraptions; and probably just about long enough to dramatise what will end up being his Para Para moves.  The enormous head is terrible for balance.  But is probably a net positive for comical value.

But most importantly, he looks sad.  Like he's got a broken heart.  He's not been able to attract the attentions of any admirers, that's why.  And we know exactly what will cheer him up.  A dramatic, 21st century bionic enhancement; one that gifts him the ability to frantically throw shapes on the dance floor at 3am. Or 5am. NOTE: Robots don't tend to require any sleep.


Of course, first, we'll need to perform some bear surgery, or beargery, as nobody calls it in the non-existent field of teddy-matronics.  The plan is to make an incision in his back and seal it with a sturdy zip, so that we can easily reach inside his anatomy.  It's a gruesome operation, involving all the usual surgical tools found in NHS theatres up and down the country: scissors, a zip, thread and a needle.  And disinfecting the utensils isn't even neccessary.

A stuffed animal was most definitely severely hurt in the making of this feature.  If you're squeamish (or a member of RSPCA, PETA, or any other stuffed animal welfare group), look away now.


Here's a more civilised photo of Mr. Ted-E U post-op.  See, that wasn't too bad, was it?  He looks just like most mammals found on earth.  Those that come with a convenient zip to allow the inspection of its internals, that is.  Unfortunately, this isn't the end of his ordeal.  He's been pencilled in for further operations in the surgeon's diary (but he doesn't know it just yet).


This is where it starts to get a little more involved.

Next, we need some sort of intricate skeleton that allows all our previous servos to be mounted, and to provide the desired range of movement.  We already have some servo bracket designs that allow both the mounting of the servos, and the pan / tilt movement of a joint.  They were designed in SketchUp, and 3D-printed using our FlashForge Finder 3D printer using PLA filaments.

All we need are some additional structures to connect these brackets together, and sit snugly inside the unsuspecting body of Mr. Ted-E U. 

We also decided that Mr. Ted-E U in his first outing is unlikely to be free-standing, as developing some form of self-balancing algorithm using additional sensors (like a gyro) would be a bit too taxing at this point.  Especially when Mr. Ted-E U's centre of gravity is way up near the top of his gigantic head (with no guaranteed brain power to go with it).  Therefore, we will allow the skeleton to be attached to a stand that will sit outside his anatomy - for now.  We can revisit all this, when we have all the basics working.  Or not.  And arguably, most human clubbers aren't self-standing by the time their night out comes to a close.

These are the sort of things we ended up with in SketchUp.  Below are the core components to hold together the servos.


And here we have some additional stuff.  For example, holders to attach the Pi and HAT to the frame.  And various other (over the top) contraptions to attach the skeleton to a stand.  You may also have noticed something that resembles a heart, and some things that suspiciously look like a ventilation system.  There's more on this later.


In summary, if we ignore all the distractions, we have a few "core" components here, without which Mr. Ted-E U simply won't dance.  We probably owe you some further explanation, as quite frankly, a majority of them are admittedly a bit weird.

PieceQuantityWhat on earth is it for?
Spine1The main backbone that will (hopefully) hold everything together
Hip Extension1As it turns out, Mr Ted-E U... how do we put it politely... carries a bit of weight around his hips.  This is to widen up his hips a little.
Shoulders / Hips4Attaches to the spine, and points servos downwards. What more did you want them to do?
Shoulder / Hip Brackets4Actually, it turns out that just pointing servos downwards isn't great and the screws quickly come loose due to gravity.  Here are some additional brackets for the hips and shoulders to make sure there's support.
Servo Brackets8 sets + 4 additional half setsHolds servos in place, and provides two dimensional movement (aka "pan and tilt"). Probably the most important gizmo to make the robot move.
Extenders4Let's extend the legs and arms using more 3D-printed PLA. Why? Because we can.
Forearms / Thighs4Multi-purpose extenders, so much so, that we can add a random spring in them for no apparent reason. They've got holes in them too, err, because they are so multi-purpose.
Feet2Legs tend to have some feet to go with them. Let's have some holes in these too, so that they can be attached to even more stuff. Like some skies for Mr. Ted-E U Goes to the Alps.
Pi Holder1A plate to hold the Raspberry Pi in place, on the back of his spine.
HAT Holder1...And something else to hold that Adafruit PWM HAT in place.
Hook1Some sort of hook to keep the entire structure bolted at the back to the stand, to keep the whole body upright.

Most of these pieces were printed with brims and supports, due to the overhang involved.  Infills were varied depending on the specific item being printed.  But we were able to get away with 15% infill (honeycomb) for servo brackets, but went for something more solid for the spine and shoulders (50%-100%).  Clearly, there is a trade-off between conserving PLA and keeping parts light in weight... and material strength.

We're intending to upload these STLs to Thingiverse, once this little raver recovers from his hangover, so that you can have an animatronic teddy bear sitting beside all the other unnecessary things that you printed off using your 3D printer, just because you could.  Remember that unicorn?  And that garden hose reel that took 5 days to print?  Only if you had a hose... or a garden.

While we wait a small eternity in a sweet-smelling PLA shroud for all these parts to be printed, there are a few things worth thinking about.

Naturally, you're likely to exhaust a few packs of M2 and M3 nuts and bolts during the build of this monstrosity.  Our 3D prints happened to require a few different types and lengths - because we printed using holes with radii of 1mm, 1.5mm and 2mm.  It's always handy to have a generous stockpile of these nuts and bolts (and perhaps even washers), as running out when you're on a roll is an absolute pain.  Seriously, don't ignore this advice.  Invest in bags of this stuff.  You won't regret it.

TypeLengthGenerally used for
M28mmAttaching stuff onto servo horns
M38mmAttaching together pieces of plastic
M312mmAttaching servos to brackets


Have they all printed?  Good.  Does the house stink of PLA?

It's time to assemble everything together.  And once we do, we end up with one big monstrosity.  A hideous coming together of servos and 3D-printed bioplastic that resembles an unnerving killer robot from the world of ガンダム (Gundam).   Although - clearly - not as professional as this one.  However, you'll soon find that we end up toning down its fear factor pretty sharply.  No creation can look menacing for long... when it is hidden inside a cuddly soft toy bear designed to be a loving gift for Valentine's Day.  Complete with big, googly eyes. Ahhh.

But not so fast.  Here's the scary skeleton from the front...


And its behind, in all its glory...


At this point, with all parts of the robot attached together and exposed in the open, it's pretty useful to go through our Python servo test routine from before, to ensure we understand all our degrees of movement, and note down the minimum and maximum values you want (or more likely, can have) for each servo.

For example, you don't want the arms to be bashing into the hips or legs.  Nor do you want joints to be bending in a direction that isn't humanly possible.  During this test, you're likely to need to attach and detach the servo horns to and from the servo brackets a few times, to make sure you have the required freedom of movement (because it's not necessarily guaranteed after Brexit, apparently).  And to make sure that servos in either side of the body are symmetrically set up.  IPython comes in handy, once again, to manually test the values you have in mind so that you can observe where they take the servos, positionally.

Also - now - there is likely to be a need for a badly constructed "containment field" for the potential global menace that could be the dancing teddy. We've assembled ours using left-over Ikea furniture, and some more screws and bolts from our quickly depleting stockpile.  Because quite clearly you've watched the films.  Evil aliens and robots don't stay in captivity for long (especially if the film is to be half-decent).  Let's give Mr. Ted-E U some hope of freedom (and world domination) by not really putting any effort into the build of this stand.

Hang on.  Look at the time.  The taxi will be arriving soon to whisk Mr. Ted-E U away.

So how do we make a teddy bear rave?  Let's return our attentions to Python and solve this last remaining, unsolved problem of the Pi-llennium Prize*.

*Completely made up.

We're going to make some pretty outlandish assumptions, so that we're not bogged down for weeks by the detail.  That's just as well, as we're by far the least qualified people when it comes to providing practical guidance on the art of dancing.  Therefore, for the purposes of describing the science of dance programmatically, we're going to (rather foolishly) assume that:
  • A "dance move" will always start at the beginning of bar 1 of music, and finish at the end of bar 4 of music.
  • Each bar will consist of 4 beats.  No, Mr. Ted-E U will not be suited and booted to dance to the triple time signature of the Waltz.
  • A "dance move" will be described in starting positions of each and every servo at the start of each beat.  A "dance controller" will be required to work out how to transition between these positions. Servos should be capped at minimum and maximum angles.
  • Beats-per-minute (BPM) will be used to drive the frequency of the beats, although we're pretty sure this won't remain accurate for the duration of a song due to the latencies involved.
  • Let's store all this data in a Python data structure:- a dictionary of lists.  List of each beat in the dance move (4 bars = 16 entries total).  Dictionary for the position of each and every servo.  All organised under the "move" that these positions apply to.  You'll recognise the three digit values when you come to see them... because these are essentially the "ticks" we were talking about earlier.
  • Multiple dance moves can be sequenced, into a "routine" using a tuple.  Now we're talking.
Confused?  Here's a diagram to confuse you even more.  It shows 1 bar of music (4 beats), and made-up positions of the right arm servos 1-3.  At the start of each beat, the servos will be asked to move into those positions.  This will repeat itself.  Over.  And over.  Again.  Thus creating the illusion of dance.


We said we'll store all these values in a list, within one big dictionary data structure, organised under the name of the "dance move".  Because it's a dictionary, we can actually add additional attributes to the move now, or at a later date, quite simply by introducing a new key.  For example, we've added a key called gradual to identify if servo movements between beats should be sudden, or gradual.

We'll park the theory here for now.

Let's get our fine fur-logical specimen ready to turn theory into reality.  We'll implant the monstrous skeleton consisting of 3D printed PLA parts and servos into Mr. Ted-E U's back, via the zip.  This procedure is so ahead of its time that even Blade Runner didn't dare to feature a replicant masquerading as a philosophical teddy bear (who may or may not be self-aware that it's a teddy bear, or a replicant, or a unicorn, or an electric sheep, or any other random entity simply thrown in to utterly confound the situation).


Wait.  We never did tell you what those funny things sewn into his hands and feet were for?  And all those additional bits that were 3D printed.  They are vents... clearly.  More on this in a minute (because it's actually quite important).

Here, we've removed excess filling through an extreme course of liposuction.  But Mr. Ted-E U will look totally deflated as a result.  We'll therefore be returning some of that filling stuffed in strategically placed fabrics in his head and tummy in order to give him back some of his curves.  These will be stitched in using fabric from an old shirt, so they don't move around and cause havoc.  We really don't want the filling getting entangled in the servos, nor do we want them overwhelming the somewhat exposed Pi and HAT boards.

But most importantly, don't block airflow, or provide any form of unintended insulation.

Servos have a tendency to heat-up during use, especially if they are coming up against force.  And we have 12 of them. You might not remember that PLA has a melting temperature of well over 200 degrees. But, more relevantly here, it also has glass transition temperature of around 60-65 degrees,  This means, if the insides of Ted-E U starts to approach this temperature, there is a real risk that his 3D printed internal organs start to deform.  And because heated air rises, parts towards the top of the skeleton are likely to start to deform first (in this case, the Pi holder and shoulders).

This is unfortunately what happened in this instance here, with an earlier version of the frame.  You can't go see the doctor for this problem.


Lesson learnt: never zip up the back (unless you have a great ventilation system), return as little as the stuffing as possible (especially around the servos), and don't block the airflow.

Use an extraction fan if you are taking this task really seriously, and make even more inlets and outlets in your rig to allow cool air to enter, and warm air to escape.  Also, make sure that all the joints have the ability to make the intended angles, without being impeded by other parts, cables, or the fabric in the donor soft toy.  Servos will heat up quickly if they are caught on something, and therefore doing more work to try and desperately move into the intended position.

Also, choreographically speaking, plumped limbs aren't great either aesthetically - because they start to cover up joints that we so painstakingly assembled.  As a result, his movement won't be as articulate.  In other words, Mr. Ted-E U won't be doing the Y.M.C.A, but the U.O.O.U. (which unfortunately isn't the name of a song with a famous dance routine, as far as we know).

Here is Mr. Ted-E U, with 3D-printed vents sewn into the back of his feet and hands.  You'll also notice that he has an ugly outlet at the top of his head.  We'll use a plastic tube (of the plumbing variety) attached to an electronic, USB-powered fan to extract the warm air once he starts to heat up inside.  This was perhaps THE moment when we too realised that this project had gone too far.


And the cable sticking out around his tummy?  That's for the bi-colour LED embedded in his 3D-printed heart, which is now stitched into his front.  We use it to flash the light green to the beat, and turn red when he's getting hot.

Once we stick the ventilation pipe deep inside the unsuspecting patient via the plastic outlet, we use a 1-Wire DS18B20 digital temperature sensor attached towards the top of his skeleton to monitor the temperature before every beat.  Once it starts to get warm, the bi-colour LED in his heart - normally flashing green to the beat - starts to flash in red.

Don't stop the music, DJ.  Not just yet.

Because at this point, we'll turn on the extraction fan attached to the end of the vent - via a relay connected to the Pi's GPIO pin - in an attempt to cool him down (a feature not quite yet available to the average rave attendee hotting up on the dance floor).  But if the tunes keep on coming, and Mr. Ted-E U is totally consumed by the music, he's in grave danger of overheating on the dance floor.  That's not a good look in a club.  Or an abandoned warehouse.  Or virtually in an app on Facebook.  Wherever raves are held these days.  So we'll stop him from dancing when he heats up too much. It's for the best.

We won't explain how this is all achieved in this post, as we documented how we can use a digital temperature sensor (DS18B20) to take temperature readings, and how to operate a bi-colour LED and fan (via a relay) during a previous adventure.  The post also details the cabling from the Pi's GPIO pins.  For now, we simply embed some aspects of that into this project, which will be clear when you look at the code.

This is how our extraction system has been deployed.


Together with this rather alarming tube entering our cuddly bear's oversized head:



It's worth unleashing our customary warning notice at this point.  As it's actually quite important.

Just like with humans, robot components have a tendency to heat up pretty quickly during a bout of crazy, rave dancing, but without the benefit of being able to sweat it out.  This is particularly true of servo motors, and of course, to a lesser extent, the Pi.  Therefore, always think about the airflow.  And don't do anything that doesn't allow warm air to escape outside.  Always check the temperature, manually or programmatically, and make sure servos are able to move into their intended positions without being impeded.

Therefore, a Raspberry Pi temperature sensor, checked somewhere in your Python dance routine, to stop the program when temperature exceeds a certain threshold, is well worth the investment.  Moreover, not only do you want to exit the program, but reset all the servos as well.

This will not only ensure that you don't suffer the disappointment of having to replace your deformed 3D-printed PLA parts, or even worse, damaged servos, but also reduce the risk of any fires.  Clearly, if Mr. Ted-E U is planning to attend a mid-summer rave in the Death Valley, you may opt to use different 3D printing material instead.  ABS, for example, has a glass transition temperature of over 100 degrees.  Or - probably more wisely - simply persuade him not to attend.

It goes without saying: always have Mr. Ted-E U dance under supervision, and make sure everything is disconnected, and servos reset, after he's had his moment of dance floor glory.


Right.  We can hear the taxi pulling up outside.  Let's get this party started.  It really is time to see what a bear hooked on Raspberry Pi looks like.

Because we don't (yet, and probably never will) have a self-balancing algorithm, we'll simply attach the skeleton to the inglorious plank of wood "containment field" via 3D-printed bits and bobs.  It's probably just as well, as we don't want Mr. Ted-E U launching towards us with his kung fu moves.  There are many embarrassing reasons why you might end up in A&E (we know, because we've seen them on TV), but being attacked by a robotic teddy bear may be hard to top.


Sorry for another public safety announcement so soon after the last one.

On a serious note, these servos can pack a punch.  Do not attempt to approach the dancing bear when he's found his groove.  Nor should you let any children near him once he's possessed by the tuuuunnneees.

In other words, approach this particular party-goer - cautiously - like you would any reveller on a Saturday night out in booze-tropolis*.  Innit.

*Replace with the name of an actual English town.  Or should that say any.


Quite clearly Mr. Ted-E U is now ready to rave.  The most observant of you may notice that the strategically placed inlet in his head is serving another purpose: it's actually also keeping his enormous head propped up.

Yes, this little post-op bear hides a deep, dark secret.  Be very suspicious when you next invite in a cuddly bear into your home.


This particular Uber driver doesn't seem to be too concerned about whether Mr. Ted-E U makes his grand entrance on time.  Just as well, as it affords us some time to think a little more about Python.

Now cast your mind back to how we were intending to describe his dance routine, and his moves.  It was to be defined through a dictionary data structure holding all the moves, and associated lists of servo positions.  This sort of data should *probably* be stored in a database of some kind.  But it's getting late in the day, the atmosphere is buzzing, drinks are starting to flow, and we've started to cut corners in an effort to get this bear ready for the night out of his life.

Firstly, we have created a standalone module - ted_dancemoves.py - which simply houses a class DanceData.  In it, we'll use a constant, AVAILABLE_MOVES, to categorise our moves and describe the servo positions in lists.  DANCE_ROUTINE will be a tuple, sequencing the individual moves of our end to end routine.  We also have a key here to make the dance "freeze" for the duration of the last bar... for dramatic effect (don't ask).

Also, we'll make two methods available in this class - get_dance_move() and get_dance_routine() - to allow the main program to retrieve this data from outside this module.

With some experimental servo positions used to populate the "moves", this is what this module will look like.

Finally, we need the main Python application that we run, which we'll call ted_dance.py.  Not only will we call the two methods in the ted_dancemoves module from here to retrieve our servo positions, and sequence of the moves, we'll define other stuff, like:
  • A main() function that retrieves the dance data from ted_dancemoves and sends it to an instance of DanceController for actioning.
  • DanceController is a class that represents an instance of our Adafruit HAT.  We'll get it to do a bit more than just interpret servo positions and send angle data via I2C to the relevant servo channels.  It should be able to work out how to do this all to a beats-per-minute (bpm) value, for example.  There's also a bit of code here to compensate for the time taken for the servo codes to execute, so that we sleep() for the remaining duration of the beat... rather then a fixed amount which is prone to drift.  This is all in an effort to keep Mr. Ted-E U in sync... which will ultimately be futile without some additional real-time beat-detection algorithms, or an external timer.  Remember; each delay experienced in a beat is compounded over time with this code.
  • Servo is a class that represents an instance of a servo.  We'll use this to provide a lower level mechanism for the DanceController to interact with the servos.  For example, we'd want to enforce min / max servo positions at this level, so that the DanceController can't instruct the servos to make a physically impossible angle.
Notice that we've imported rosie_temperature and rosie_fan modules from our previous outing.  We want these to allow us to take readings from the DS18B20 1-Wire Digital Temperature Sensor, and to operate the bi-colour LED and relay for the extractor fan.

This simple bit of code isn't likely to be advanced enough to allow Mr. Ted-E U to dance the night away.  Specifically, maintaining movements to a BPM will pose a major challenge the longer his routine lasts.  In other words, there's plenty of room for improvement.  But in an effort to demonstrate how this entire project hangs together, let's drag our creation unceremoniously onto the dance floor.

The ted_dance.py file in this current incarnation looks like this:


It's likely to take a small eternity to perfect the servo positions to fashion the outrageous dance moves that you last witnessed at a family wedding.  You'll also observe that you might need yet more servos to make better shapes.

But for now, let's run it to see what happens.

python3 ted_dance.py


The descriptions provided to the moves come in handy, as we see the program explain to us what crazy thought we had in mind when we came up with a particular ridiculous move.  We also see the beats shown (which is also indicated by the heart LED flashing), which demonstrates how hard it is to keep this performance in sync.  We also added temperature readings.  This way, we know when Mr. Ted-E U is getting Hot, HOt, HOT!


Here is the skeleton that bears it all, dancing (badly)...


But that's not that interesting (nor what we promised).  Here's the full creation in all its glory.

The song featured is Cand¥¥¥land by tofubeats (@tofubeats). Clearly, this little bear has had too much candy.

The hangover...

As we keep reminding you, there's plenty of opportunities here for improvement.  You could introduce more movement, using yet more servos.  Wouldn't it be great if his head could bop, or move sideways.  Or if he could have three-dimensional movement in his shoulders to dance the Macarena.

And further down the line, you could use Python beat detection software - like Aubio - and a microphone to get him to actually dance in sync to whatever music is playing at the time.  Yes.  An autonomous dancing teddy.  The holy grail of teddy-matronics.  Or aim even higher.  And use a sensor like a gyro and a balancing algorithm to make him dance, without support, after self-learning his moves from watching music videos on YouTube.


And rather inevitably, the robot frame started here ends up being recycled into being Rosie 2.0's brand new body - making this little experiment slightly more than just an extended detour to make a furry mammal dance using servos.


So there. You can now officially - and embarrassingly - claim to have seen a teddy bear dance.

You can either try to forget all about it, and move swiftly on with your life, or spend the next 6 months of your life enhancing his code to make him worthy of an actual trip to your local nightclub.

But since you've just spent a vast chunk of your life reading about how to make a cuddly toy dance using a Raspberry Pi, servos and Python, we suspect that you've just called your colleagues, family and friends to apologise in advance for "being too busy" for the next 6 months.

Comments

Popular posts from this blog

Tea minus 30

We're fast approaching Christmas time.  And if robots were to make one simple observation about the human species during the Christmas festivities, it's that they watch a lot of TV.  A LOT.  Often, accompanied by an inappropriate amount of greenhouse gas-producing food.  Stuff you don't normally eat during the remainder of the year - for good reason.

And most so-called shows on TV are boring to robots like Rosie.  After all, why watch a minor subspecies of the human race - celebrities - stumble awkwardly around the dance floor, dressed like a faulty, sparking circuit board?  Such branch of entertainment doesn't require robots to engage any of their proud circuitry.  Their processors remain idle.  Memory under-utilised.

But if robots are to be part of people's homes (and blend in), they need to look at least a little interested in some of this irrational nonsense.  Nobody likes a party pooper.  A killjoy.  And this is where a certain subgenre of TV entertainment co…

Beam me up, Rosie!

How do you get from A to B?

You can't, as As and Bs are just letters in the alphabet. But if A is your house, and B is a meerkat village at your favourite safari park, you'd probably use a device equipped with GPS.  Not to be confused with UPS, who will deliver you your chosen meerkat through the post. And why on Earth would Rosie Patrol need one? Precisely, it's because she is on Earth that she needs one. Because our planet is rather big. Big enough to get lost in. And we don't want to lose our friendly plastic boxes on wheels. And maybe, eventually when she's clever enough, she'll go and defeat baddies on her own. And return home afterwards for a well deserved Earl Grey tea.

Besides, why wouldn't we want to add another three letter acronym to Rosie Patrol's repertoire?
All superheroes need:One Raspberry Pi 3, running Raspbian OSComputer from which you are connecting to the Raspberry Pi Probably the most important bit: a GPS receiver thingmy. …

Code: read

Humans are said to have 5 senses in total.  Common, clearly isn't one of them.

But - jokes aside - computers all around us are growing ever more intelligent (so we hear).  They can play chess.  Drive cars.  Some might even do these things at the same time.  Without crashing (quite literally).

Likewise, we've been making steady progress equipping Rosie Patrol with some useful skills.  Skills needed to bring much needed law and order to the world.  She can move.  She can see.  She can sense.  And in our last episode, she began to read.  With a little helping hand from some (considerably) bigger computers at the mothership that is Google.

But can she really read?  You know.  Read out aloud?

True to our style, there is only one way to find out.  It's time to invoke Code: Red Read.  And take the power of reading to the next level (or page).
All superheroes need:One Raspberry Pi 3, running Raspbian OS.  Connected to the Internet. Computer from which you are connecting to the R…