Things are hotting up

I haven’t posted much about the 3D printer recently (or indeed about anything else). This is partly because I have been trying to work out what was the cause of poor print quality. I’ve finally worked out what the cause of the problem was. I’d been finding it increasingly difficult to print larger objects, particularly those which involved long continuous print movements. The symptom seemed to be a lack of material being extruded. I’d tried turning up the filament feed rate, but this only led to the extruder slipping as it tried to drive more filament through the print head. I turned up the temperature setting, to make it easier to extrude, and this worked over shorter movements, or at lower speeds. I could only get half-decent results by printing very slowly, with a feed rate of 120%.

The cause of the problem turned out to be very simple. The resistor used to heat the hot end simply could not provide enough heat to melt filament at the required rate. At low speeds, no problem. At higher speeds, insufficient power meant taht the hot end simply could not maintain the required temperature. Short distances were OK, because the hot end had time to heat up between extrudes.

The solution was to replace the resistor in the hot end with a cartridge heater. The J-head kit I bought came supplied with both options, and for some reason I can’t remember, I originally went for the resistor (there’s a picture in this previous post). Ten minutes of disassembly, rewiring and reassembly is all it took to fit the new heater. The hot end now reaches operating temperature much more quickly, and stays there very accurately, even if I turn the feed rate up and use a cooling fan. Goodness knows why I didn’t try it before.

New Arduino tutorial

At tonight’s Hull Digital Hardware Meetup, we will be doing the fourth tutorial on Arduino programming and interfacing. This one involves Things Beginning With The Letter ‘I’, so if you have narcissistic tendencies you may enjoy it. Or you may have completely misunderstood.

The tutorial notes are available on the Arduino page

Hot Pi

In my last post, I explained how to set up the Pi with the drivers needed to allow it to read temperatures from DS120B sensors. In this post, I’ll show you the code and setup required to make it start taking readings automatically at bootup, and store the information in a Mysql database for future use. I’ll also add a couple of LEDs to the circuit, so that the system can provide some feedback and also to pave the way for controlling a relay or two.

Here’s the updated circuit schematic (click on it for a bigger version).


There are a few things to note about this slightly more complex schematic:

  1. I’ve added another temperature sensor. Its pins are simply connected directly to the pins of the first one (and any subsequent ones). The one-wire protocol and the fact that each sensor has a unique ID means that they can share a common bus.
  2. I’ve added two LEDs, just so that the system can indicate some state to me. One will be replaced with a relay in future.
  3. I’ve added an Adafruit level converter (the blue pcb). This is there to protect the Pi: its GPIOs run at 3.3V, and are not designed to carry much current. overloading them will cause damage to the Pi. The cheap level shifter allows the 3.3V Pi pins to be connected to 5V input or output from other devices, and protects the Pi from accidental over-voltage. It’s not strictly necessary just to drive LEDs, but the relays I want to use later need 5V.

I’m going to use Python as the main language for running the system. The reason for this is that I don’t know it very well, and there’s no better way to learn than to dive in and try and do something with it. Of course, this also means that my Python code may well be what is technically-termed ‘Not Very Good’. Use it at your peril. To make it work, you’ll have o install a couple of other things. One is MySql, the database into which the program will write the recorded temperature values (you’ll also need the associated Python library). The other is pigpiod which is, of course, a Pi GPIO library, though the name always looks like pig-pio to me. Pigpio (also available in its useful daemon form pigpiod) is a C library which exposes all the GPIO to C programs. Not useful for Python, I hear you say. True enough, but it also exposes the same functionality through a TCP socket interface, and it’s dead easy to use this from Python without installing any special python libraries at all. We’ll deal with that in my next post.

Installing MySql

In Linux, it down’t get much easier than this:

sudo apt-get update
sudo apt-get install mysql-server

At some point, the installer will ask you for a password for the root MySql user. In any serious situation, this should be a good, secure, password. I just used the same one as I’m using for everything else on this device. It’s only a toy, after all. Once MySql is installed, you can use the command line client to create a new user and to make the ;temperatures’ database and the ‘data’ table in which the readings will be stored. NB: when you are using the MySql command line client, don’t forget the semicolon at the end of a SQL command line. Multi-line commands (such as the CREATE TABLE command below) are fine in SQL, and they don’t get executed until the parser sees a semicolon. It catches me out all the time.

mysql --user=root --password=My5ecurePa$5word

mysql> create user 'pi'@'localhost' identified by 'raspberry';
mysql> grant all privileges on *.* to 'pi'@'localhost';
mysql> create database temperatures;
mysql> use temperatures;
mysql> CREATE TABLE 'data' ('id' int(11) NOT NULL AUTO_INCREMENT, 
'timestamp' datetime NOT NULL, 'sensor_id' int(11) NOT NULL, 
'temperature' float NOT NULL,  PRIMARY KEY ('id'));
mysql> quit;

When that’s done, you will have a database with an empty table in it, and a user ‘pi’ which you can use to connect to it from python. For that’ we’ll need the python-mysqldb module. This can be installed thus:

sudo apt-get install python-mysqldb

We can check that this works with a small python script:

import MySQLdb as mdb
import sys

    con = mdb.connect('localhost', 'pi', 'raspberry', 'temperatures');
    cur = con.cursor()
    cur.execute("SELECT VERSION()")
    ver = cur.fetchone()
    print ("Database version : %s " % ver)
except mdb.Error, e:
    print ("Error %d: %s" % (e.args[0],e.args[1]))
    if con:    

Run this, and if all is well you will see something like

Database version 5.5.37-0+wheezy1

Or possibly an error. With unbridled optimism, I’m going to assume that you are not seeing an error. It’s now time to create the code which will actually read the temperature sensors and write the data to the database. Here it is:

#!/usr/bin/env python
import datetime, time, sys
import MySQLdb as mdb

def getTemp(chipid):
   tempdata=secondline.split(" ")[9]
   return temperature

   con = mdb.connect('localhost','pi','raspberry','temperatures')
   with con:
      cur = con.cursor()
          timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
          t1 = getTemp("28-000001a9b68a")
          t2 = getTemp("28-0000009bba2b")
          query = "INSERT INTO data(timestamp,sensor_id,temperature) VALUES ('%s',%s,%s)"%(timestamp,'1',str(t1))
          result = cur.execute(query)
          query = "INSERT INTO data(timestamp,sensor_id,temperature) VALUES ('%s',%s,%s)"%(timestamp,'2',str(t2))
          result = cur.execute(query)
          print ("%s %s %s"%(timestamp, str(t1), str(t2))
   print ("Goodbye")


There are two main parts to this code. The function getTemp(chipid) reads the virtual file created by the 1-wire driver discussed in my last post for a specific temperature sensor, and extracts the temperature data from it. There’s nothing clever about it, just python string processing. You’ll need to modify the code further down to use the chip ids of your own sensors, of course. The main body of the program establishes a connection to the database, then enters an unending loop inside which it gets the temperature from each sensor and writes it to the database with a timestamp using a simple SQL INSERT query. Adding a time.sleep(10) means that this process happens every 10 seconds. Assuming you run this without errors, you’ll find that your database will gradually be populated with temperature readings. You can check this using the mysql command line client again:

mysql --user=pi --password=raspberry

mysql> use temperatures;
mysql> select * from data limit 10;

| id | timestamp           | sensor_id | temperature |
|  9 | 2014-05-17 17:17:17 |         1 |        20.3 |
| 10 | 2014-05-17 16:45:10 |         1 |      22.187 |
| 11 | 2014-05-17 16:45:10 |         2 |      23.875 |
| 12 | 2014-05-17 16:45:21 |         1 |       23.75 |
| 13 | 2014-05-17 16:45:21 |         2 |      23.875 |
| 14 | 2014-05-17 16:45:33 |         1 |       23.75 |
| 15 | 2014-05-17 16:45:33 |         2 |      23.875 |
| 16 | 2014-05-17 16:45:45 |         1 |      23.812 |
| 17 | 2014-05-17 16:45:45 |         2 |      23.875 |
| 18 | 2014-05-17 16:45:56 |         1 |      23.812 |
10 rows in set (0.00 sec)

If you have got that far, and are seeing data in the database, that’s excellent. In my next post, I’ll show you how to install pigpio and use it to flash an LED to give confidence that the process is working without having to check the database all the time. The next step is then to create a webserver which will show the data without having to log on to the Pi. Keep watching this space.

Warming to the Pi and Python

I’ve had a Raspberry Pi since Christmas, but haven’t done much with it up till now.  That’s all changed since I moved house.  Getting to grips with a new central heating system, I find that (for reasons too dull to list here) I need to monitor and control it rather more flexibly than I can do with the standard timer.  I also don’t want to pay lots of money for a Nest controller, however beautiful it may expect itself to be considered.  My first thought was to use an Arduino – the problem I’m addressing does not need a lot of processing power, and I don’t want to spend a lot – but I came up against a problem which seems to me to be the Arduino’s biggest failing at the moment.  I want to be able to control the system over WiFi.  There are WiFi shields for Arduino, of course, but they start at £30, twice the price of the Arduino.  I could invest in a Yun which has WiFi on board, but that’s £70.  There simply seems to be no cheap way of getting WiFi onto an Arduino – a device which is crying out to be connected to the internet..  Rob suggested I could use a bluetooth adapter and control the system from a phone; that has attractions and is very cheap, but means I have to be quite close to use it (no controlling the heating system from work, for example).  This made me turn to the Pi.  At first sight it seems ludicrous to use a full Linux computer for this trivial task, but consider: the Pi costs £23 (or less, for a model A), and the tiny USB WiFi dongle was only £9.  That’s £32 for the whole thing.  Much cheaper than an Arduino and WiFi combination. 

The hardware requirements of the system I want to build are quite simple.  It must monitor two or more temperature sensors, and it must be able to control two or three relays capable of switching mains voltage.  Having a couple of controllable status LEDs would be good, too.  I don’t require any other user interface input or display in hardware, because I want to use a web interface.  The Pi is more than capable of handling all this, but it turns out that there is quite a bit of software installation and configuration to do.  All of it can be done over a ssh connection (I use PUTTY for this), which is fortunate because I don’t actually have a monitor with an HDMI input that I can use as a display for the Pi.

The temperature sensors I am using are DS120B types.  Rather than being dumb devices like thermistors (whose resistance varies with temperature) they have logic inside which allows them to communicate with a host over a three wire digital serial connection.  The manufacturer calls this ‘1-wire’, because the actual communication only needs one, but you also need power and ground, so really there are three).  This has several benefits: it means that many devices can share the same wire (as each has its own address), it reduces the likelihood of inaccurate readings caused by long wires, and it means that the host does not need an analogue to digital converter to read them.  It also means that the host must implement the 3-wire protocol in order to read the sensors.  Fortunately, cleverer people than I have already done the hard work, and there are Linux drivers for these and other three-wire devices.  The relevant ones are already present in the raspbian distro, and simply need enabling.  Simply?  Did I say simply?  This is Linux – nothing is simple until you know the magic incantations.  I need Linux to load the appropriate 1-wire driver modules when it boots up, so it’s necessary to edit the /etc/modules file, which contains the list of drivers to be loaded.  It’s necessary to have root privileges to edit this file:

sudo nano /etc/modules


The lines w1-gpio and w1-therm tell the system to load the one-wire driver for the pi’s GPIO port (GPIO4 is used for this) and also the drier for the DS18B20 chip.  You can also load them manually from the command line if you wish:

modprobe wire
modprobe w1_gpio
modprobe w1_therm

Once these modules are loaded, the system will probe in the background to see if there are any sensors it recognises on the wire.  It will then create a new folder for each one under /sys/bus/w1/devices, and pop the data it retrieves from each in a file in there.  Reading the temperatures is a simple as reading the values in these files.  For example, as I write I have two sensors.on my Pi.  If I look in the devices folder, this is what I get:


The long number ‘28-0000009bba2b’ is the unique id of the sensor (hard-coded into the sensor itself).  The 1-wire driver identifies these and creates links to each.  By browsing to the folder and looking at the ‘w1_slave’ file within, the temperature is revealed.  it’s the bit saying ‘t=21250’, which is 1000 times the temperature in degrees Celsius (21.25 degrees).  If you want the temperature in Fahrenheit, I suggest you go back to the eighteenth century.  If you are actually executing the commands, you may notice a short delay between the ‘cat’ and the output.  That’s because when you read the file, the system actually contacts the sensor and takes a reading.  This is perhaps slower than you might expect, but it’s fast enough for my purposes.  For completion, here’s a quick wiring diagram of how to connect up the senor to the pi. the only other component needed is a 4k7 resistor, to tie the communication wire to the 5V line.


The next step is to use python to read these temperatures and store them in a database, then get a web-based interface up to control the relays.  I’ll also need to make sure that everything runs automatically, with no user intervention.  Watch this space.  Unless you have better things to do, which I fervently hope is the case.

Richmond revealed

I was at one of Rob’s excellent rather useful seminars yesterday.  As it was about 3D printing, Rob asked me to say a little bit about my printer.  Having not prepared to do anything, I relied on some bits of video I found on my tablet.  Thinking about it, I realised that although this blog has quite a few posts about specific parts of the building process, there isn’t really a post just simply describing the printer.  So this is it.  I call it Richmond.


It’s inspired by Johannn Rocholl’s Rostock printer, but the design is my own.  I wish I could blame someone else for the design flaws, but I can’t.  The basic design features three columns made of extruded aluminium section (bought).  Up and down each column runs a carriage (the pink bits), with spring-mounted ball bearings to make it run smoothly and without wobbling.   Rob printed these for me.  Here’s a close-up of one.


The blue parts are modifications (printed by me) to add extra ball-bearings.  The original design simply had screw in the plastic which gradually wore loose.  At the right of the picture, you can see the fishing line which is attached to the carriage to drive it.  This loops around a motor-driven pulley at the bottom of the pillar and and idler pulley at the top, to make it move up and down.  The grey rods are carbon fibre, and join the carriage to the tool head.  The rods are in pairs, to keep them in a parallelogram shape – this means that the print head can move in three axes, but will never rotate.  The tool head looks like this from above: The translucent tube in the centre guides the plastic filament into the heated part.


The print head looks like this if you happen to be underneath it (which I don’t recommend, because it heats up to 220 Celsius):


The underneath view shows you the hot end – the part that melts the plastic and squirts it out through a tiny (0.3mm) hole.  The plastic filament is driven through the flexible tube to the hot end by an extruder, in which it is pressed against a rotating gear.  It takes a surprising amount of force to push the filament though the tube and the hot end.  Here’s the machinery that does it (with its operator):


As usual, these components were printed for me by Rob, but they are not my design.  Rather, I downloaded the designs from thingiverse.  There is no sense in reinventing the wheel, especially when so much effort has gone into making it work well.  The plastic filament is taken from a reel, which sits close by on a home-printed stand:


The filament drive is powered by a NEMA17 stepper motor.  Each carriage is also driven by one of these, mounted at the bottom of each column:


Each motor has a printed pulley on it (printed and then machined with my printed lathe, in this case) which drives the Spectra non-stretch fishing line to move the carriage.  The filament is kept under tension by an adjusting screw on the carriage.  How much tension?  Until it goes ‘ping’ rather than ‘boing’ when you pluck it, that’s how much.  As an aside, it also makes an interesting Aeolian harp if you take it outside on a windy day.  Each stepper motor moves as finely as 3200 steps per revolution, so with the pulleys I have this means about 55 steps per millimetre of vertical movement.

Also mounted at the base of each pillar is an adjustable mount for the print platform (which is just a circle of glass from a local glass shop).  These are ugly and badly designed, but they do the job for the time being.  When I redesign the base, they will go.  Using three supports means that I can ensure the print surface is as close as possible to being perpendicular to the pillars.  This is important for ensuring good prints, particularly so for getting the first layer of plastic to stick to the base.  If the base is not level relative to the  and y movement of the print head, then it’s likely that the first layer will vary between being too thin (resulting in nothing but an impression in the masking tape) and too thick (resulting in a strand of plastic not actually stuck to the base).  Bear in mind that this means the print plate has to be level to within plus or minus a tenth of a millimetre over its diameter, and you’ll see why this calibration has been such an issue for me.


The hardware is mounted on a box made out of plywood I had lying around, painted purple because I had a can of purple spray paint to hand.  On the front of the box is a basic controller interface – an LCD and a simple rotary/click controller. 


The LCD provides status information about the printer, and a menu system to allow various parameters to be adjusted without using an attached PC.  It is possible to fit it with an SD card holder, which will allow printing completely independently, but I have no need for that.  The display and controller are driven by and provide input to an an Arduino Mega controller inside the main box.  The arduino is fitted with a Ramps 1.4 shield, which provides the stepper motor driver electronics and the higher power switching for the hot end.  The arduino runs Marlin firmware, which generates the stepper motor motions required to translate standard cartesian G-codes to carriage movements for the delta configuration.  The firmware also controls the extruder, monitors the temperature of the hot end, and drives the LCD.  The power supply driving all this is also in the purple box.  It’s a scrap supply from a PC, which provides handy 5V and 12V outputs, at high enough currents to drive the motors and the hot end.

Looking back, it doesn’t seem that complicated.  Makes me wonder why it took me so long to build.

Turn again, Whittington!

As a devoted reader of my blog, you will know that I’m engaged in a continuing quest to improve the precision of my 3D printer.  The most recent improvement was to replace all the pivots in my original design, which were simply composed of screws passing through holes in plastic, with proper miniature ball bearings.  This has had a huge benefit – there is now very little play in the movement of the print head.  Printed shapes are much more precise than they were.

The next issue to tackle is one I’ve been aware of for a while, but have not had the means to fix.  First, a recap: the whole print mechanism is driven by three stepper motors.  Each stepper motor has a pulley mounted on its output shaft, which drives a belt made of stretch-free fishing line.  Each belt goes the length of a vertical column, passes around an idler pulley at the top, and is attached to a carriage, so as the motor turns, the carriage moves up and down the column (a picture may not be worth a thousand words in this case, but if I had had one to hand it would certainly have saved me fifty or so).  The amount by which the carriage moves depends on the number of steps the output shaft of the motor rotates and the diameter of the output pulley.  Knowledge of these two things allows the printer firmware to be calibrated for each motor with the number of steps required per millimetre of carriage movement.  Because this figure is set in firmware, it doesn’t matter what each pulley diameter actually is – I can simply measure it and do the calculation.  However…

The problem I found on measuring the pulleys (kindly printed for me by Rob) is that they are not perfectly circular – the diameter varies by about half a millimetre around the circumference.  Add to that the fact that when a pulley is mounted on the motor shaft there is a little added eccentricity, and you end up with a drive pulley whose radius varies by about 5% as it rotates.  Over long movements, this is not a problem – the eccentricity averages out – but for small movements this results in unevenness.  It’s particularly obvious on the first print layer, which is often thin.  It manifests itself as patches of thin or thick deposition, and it just won’t do!

The cure is obvious: I need pulleys which, when mounted on the motor shaft, are round.  The standard method of making round things is with a lathe.  I would dearly love to have a proper modelmaker’s lathe, but they are expensive.  I can’t really justify spending £400 to make three plastic pulleys. I tried printing some more pulleys myself, but the accuracy of my prints was no better than Rob’s (not surprising, given that the pulleys weren’t round). 

I need a lathe.  I have a 3D printer.  You are ahead of me.  I had a search online to see if anyone had published designs for a 3D printed lathe, and the only one I could find was this one,  by a guy calling himself Sublime.  It’s a great piece of work, but it doesn’t look precise enough for my purpose, and I don’t need the three-jaw chuck.  For the time being, I only need to turn pulleys.  So I stole some ideas from Sublime, and designed my own lathe.  Here’s a video of it in operation:

I’m happy to say that it works.  It’s far from perfect, but the pulleys I have turned with it now have a variation in radius of 0.1mm or less, which makes for much better prints.  Now it’s on to the next improvement: automatic calibration of the print surface.  Watch this space.

Success, of a sort

The recent modifications to my printer have made a huge difference.  Not only is it printing much more accurately, but I can print item after item without recalibrating.  There are further improvements to be made (aren’t there always?), but I’m now at a point where I can be reasonably confident of being able to print the parts I need to make modifications.  Here’s an example:


These two clamps are created so that I can mount a scavenged motor securely for my next project.  I modelled these in OpenSCAD, sliced them in Slic3er and printed them using Repetier-Host control software.  Everything just worked.  I haven’t mentioned Repetier-Host before, because I’ve only just become aware of it.  It’s a very nice front end for the printer, and manages Slic3r.  You can load and view a .STL file, slice it and print it from the same interface.  It’s slicker than Pronterface, which I had been using.  It’s definitely my software of choice now.  It makes it really easy to adjust the printing speed during printing – meaning that you can slow down the head for fiddly areas, and speed it right up for less important bits.

Flushed with success printing useful things, I thought it was time to try some frivolity.  Here’s a “Skull with pointed teeth”, from a model I found on thingiverse:


It’s about 5cm tall.  It would look better printed in white plastic, but I’ve only got blue.  I’m really pleased with this print.  Next time, I’ll make it hollow and mount a couple of red LEDs in the eye sockets…

Finally, I decided to try something more complex.  Printing objects with overhangs is not simple for this style of printer, because there is no surface deposit material on.  So I have not tried it before.  Slic3r has a setting you can use which will help to print overhangs by printing columns of expendable support material underneath.  These can then be cut away when the print is complete.  The example I tried is a minion from thingiverse (if you don’t know what a minion is, you should watch the film Despicable Me at once).  Here’s a picture of it mid-print:


It’s hard to see the shape, because of all the support material (the vertical columns at the front), but you can see the honeycomb-shaped fill of the main part.  When the print is finished, the poor minion looks like this:


Ten minutes with a scalpel, cutting away the scaffolding, and he looks like this:


He’s a long way from perfect, but given the size (about 6cm tall), it’s not too bad.  His arms are only about 3mm thick, and they could not have been printed as part of the main figure without support.   Again, it doesn’t help that he is translucent blue rather than yellow.  Perhaps a paint job will improve him.  A light sanding certainly would.

You will be upgraded!

You will become like us.  Yes, I like Doctor Who (as if that was unlikely).  This isn’t about Cybermen, though, it’s about a significant upgrade to my 3D printer.  As initially designed and constructed, many of the pivots in the printer are simply screws passing through holes in the PLA printed parts.  Over usage, these holes have become enlarged, so that the screws are loose.  This means that apart from the danger of them falling out, there is unwanted movement in the printing mechanism.  This leads to inaccuracy in printing.  So, as part of my plan to gradually improve the accuracy of the printer one step at a time, the next step is to replace the pivots with proper bearings.  Naturally, my initial designs, printed by Rob, do not allow for the insertion of bearings.  That would be far too easy.  No, the pivots are part of the carriages which move up and down the columns, and are each printed in one piece.  I have to design new parts which will fit on to the old carriages.  Why can’t I just print new carriages?  Because the printer’s not accurate enough yet.

I discover that I can now print small items (and in particular, things which are not very tall) with quite good results.  This means that I can finally use the printer to print some parts for itself to upgrade it:


Those are bearing mounts.  I’ve sourced a load of tiny ball bearing races off eBay (7mm od, 2mm id) for the ridiculous price of 20p each, and I’m going to replace each of the pivot screws on my carriages with them.  They are really tiny.  Really, really tiny.  I’ve already lost one.


The bearings will be located in the parts in the first picture, which in turn are mounted on the carriages using the original pivot holes.  I’m also replacing the pivot bars with newly printed ones.  If all goes well, my prints will be better.  It all fits together like this:


I’ll have to go through the whole calibration routine again once I’ve fitted the new parts (which is a bit annoying, as it’s actually working quite well at the moment), but I’m confident it will be worth the effort.

Engage reheat!

Yesterday, I wrote about the bad consequences of letting printed PLA get too warm – in summary, it softens and bends.  In the case of my 3D printer, it resulted in the print head getting out of alignment.  Thinking it over, it occurred to me that I might be able to fix the problem by reheating the plastic a bit and straightening it out.  To my surprise, it worked.  I boiled some water, put it in a bowl and immersed the distorted component.  After a few seconds I pulled it out and flattened the distorted area.  Easy.  It worked for both of the components I blogged about yesterday.

A little more experimenting shows that the water temperature can be a lot less than boiling (cool enough to dip hands in, which is convenient) and still soften PLA quite effectively, giving it a few seconds of pliability before it cools to stiffness again.  Even more interesting is the shape memory effect that I really wasn’t expecting.  Before I played with the critical parts, I took a simple printed bar of PLA, and dunked it in hot water.  While it was flexible, I bent it into a circle, and let it cool.  Then I dropped it back in the hot water.  It uncurled itself and resumed its original shape.  I’ve since done this with more complex parts, even screwing one into a ball.  I’ve put a video of this on YouTube.

It’s an entertaining but probably completely useless phenomenon.