Filament Width Sensor Prototype Version 3

by flipper Sep 7, 2014
Download All Files

Thing Apps Enabled

Please Login to Comment

I changed from a i3 box frame, to an hypercube (still in process), and i'm planning to set up 2 extruders with 1 nozzle.
Will work the sensor for both extruders (for the one is active) if i put it between the nozzle and the Y piece for exchange filaments?

Hi there,

I have upgraded to a Hypercube Evolution machine with Marlin Bugfix 2.0. I also upgraded to a Re-Arm 32-bit board with Ramps 1.4. My problem is that the LCD just shows 100% all the time. I have hooked it up to the TXD0 pin which is suggested in the advanced configuration file.

It looks like my prints are consistent, maybe a bit under extruding, how am I going to find out if the filament width sensor is actually working or not.

When I had it out of the printer it did give me the correct volts for the filament that I tested with.

I did not do any level shifting as the volts is between 0 and 2V and the analogue pins on the Re-Arm is 3.3V tolerant. I am also not sure if the 1.75V, for example, is going to report back the same voltage in 3.3V analogue port as a 5V analogue port would. What I mean is, would you still see 1.75V on both ports from the firmware?
I am powering it with 5V.


Hi there,

I have upgraded to a Hypercube Evolution machine with Marlin Bugfix 2.0. I also upgraded to a Re-Arm 32-bit board with Ramps 1.4. My problem is that the LCD just shows 100% all the time. I have hooked it up to the TXD0 pin which is suggested in the advanced configuration file.

It looks like my prints are consistent, maybe a bit under extruding, how am I going to find out if the filament width sensor is actually working or not.

When I had it out of the printer it did give me the correct volts for the filament that I tested with.

I did not do any level shifting as the volts is between 0 and 2V and the analogue pins on the Re-Arm is 3.3V tolerant. I am also not sure if the 1.75V, for example, is going to report back the same voltage in 3.3V analogue port as a 5V analogue port would. What I mean is, would you still see 1.75V on both ports from the firmware?
I am powering it with 5V.


Hello All ! I got issues with the sensor.I make it with pcb and all from the list but It is not working.So I use usbdm but I do only see 1 file called usbdmflashprogrammer.exe , Its not recognizing sensor.Nor the sensor has any light at any time..I remake again but this time I think board is getting worse.I have extra parts so What do you suggest?

Hi Musthy,
Just from your pictures:
1) there are a lot of SMD mount component to solder pad alignment issues. This can cause unexpected broken connections and unexpected shorts between the IC pads.
Definitely check that the adjacent pins on the processor IC are not shorted together! Powering the board on in this state may have damaged the IC.
2) the required manual calibration switch S1 is missing.
3) check the IC, sensor, and LED component orientations are correct.
If the processor IC is mounted in the wrong orientation then you may have damaged it.
If the SMD LED has been soldered in backwards then it will remain dark but should still be ok.
Not sure about how the sensor module would fare if installed and powered in reverse orientation.
4) you need to at least install the usbdm usb drivers for the laptop or desktop OS you are using ensuring that the usbdm is correctly detected by the installed driver. See the usbdm website "http://www.evbplus.com/freescale_usbdm_osbdm/usbdm_osbdm_bdm_multilink.html".
5) download at least the Freescale_8_bit_code_040415.zip from the thingiverse thing files tab. This zip file has the sensor processor firmware .....S19 image you require.

I just checked your reply.How to check If Its shorted ? I will start the project again.Thank you !!!

To check for shorts between the IC pins use a multi-meter in continuity/resistance mode testing for continuity between adjacent pins of the IC.

I hope my suggestions will help make this project even better:
1 Using a 1$ red laser instead of a LED will create a sharper shadow on the sensor to get better definition and accuracy.
1.1 An infra red laser diode (780nm,1$ on Ebay) will detect clear plastic better than the regular 650nm one.
2 If the laser beam is to narrow, remove the lens and use the naked laser diode.
3 If lightning is too dim, a slightly larger lens may be used to focus the beam on the sensor.
4 If lightning is very week, add two red laser side by side to highlight the filament edge.
5 Printing the plastic cover with a black filament will minimize the parasite glare into the sensor.
6 Having a little more distance between the laser and the sensor will make the shadow sharper.

I wish I had your electronic and programming skills!!!

Alex from Québec, Canada

Can you -or any comment reader- use a cheap arduino OV7670 CMOS (under 3$ on Ebay) instead of the 128 linear pixel used in this project?
The OV7670 CMOS have a resolution of 640 pixels and each pixels are 0.0036 mm X 0.0036 mm
I don't have the knowledge to do it, but it would dramatically increase the resolution as a cheap price tag.
Is it possible to only use a single row of pixels instead of the full 640x480? It will save on computing power to avoid loosing refresh rate.

Very great thinkering!!!
Alex from Québec, Canada


I started reading the comments and just decided to write my comment,

I would like to try this all out but I’m by far a electronics expert. Could you please instruct me on what I need to get, buy, print? Also I need to know how this all works and how I go about installing it!

Thanks much for your help!!

I'm totally new to electronics. I'm thinking on printing this PCB and solder it myself.
Do I need to flash anything to it? Like an Arduino? Or it is just "solder", plug and play?

Hi i would like to buy it. Is it possible?

The TSL1401CL sensor is out of stock. Can you recommend any substitutes for the part? I was thinking of going with the TSL3301CL.

See my post a couple posts down please.

According to the TSL1401CL sensor's datasheet, each pixel is 55.5µm. If we consider the total uncertainty of the sensor to be 2 pixels and 2 gaps, then we have a total uncertainty of 127µm. Filament with a diameter of 1.85mm (tolerance of 100µm) is large enough to block your printer nozzle. That is why even the cheapest filament guarantees a tolerance of 50µm. This sensor has no value unless its uncertainty was, at the very least, less than 100 µm. Am i missing something?

It uses a subpixel algorithm to get more accuracy. My guess is that its accurate to 5um. There is some discussion of it in prototype 2. Here is the explanation and a link to a paper with details.

The subpixel approach improves apon a more basic approach. The basic approach is to essentially count the number of 'dark' pixels in the array to estimate the shadow size (proportional to the filament diameter). This requires thresholding the pixel values to come up with a definition of 'dark'. Its a little more complicated, because you want to search for an edge - the transition between a 'illuminated' pixel and a 'dark' pixel. And then search for the other edge dark to illuminated.
The subpixel approach takes the basic approach (count of the dark pixels) and adds corrections for each edge. Since the filament edge shadow does not fall exactly on a pixel boundary, it requires looking at the 3 pixels on the edge (definitely dark, grey, definitely illuminated). The algorithm uses a quadratic fit of the 3 pixel values to estimate a more precise edge. This is done for both edges, yielding a subpixel correction amount for each edge (something between 0-1 pixel width). Then add up the pixels counted in the basic approach and the subpixel amounts from each edge and you get a better width approximation.

Here is a link to the paper I used for the math: http://dev.ipol.im/~morel/Dossier_MVA_2011_Cours_Transparents_Documents/2011_Cours1_Document1_1995-devernay--a-non-maxima-suppression-method-for-edge-detection-with-sub-pixel-accuracy.pdf

Pictures in the paper do a good job showing whats happening.

Excellent! I neglected the fact that each pixel returns an analog value. This dramatically improves my presumed uncertainty.

From what I gathered by your response, you obtained the subpixel width by linear interpolation. Taking the grey pixel value and comparing it to the adjacent definitely dark and definitely illuminated pixels.
As you pointed out, there is uncertainty caused by interpolating the edge pixel. A solution to this could be to use a lense to magnify the shadow, such that the edge pixel is a smaller division of the total shadow.
On a side note, there is a uncertainty based on the scenario of the shadow edge falling between the 8µm gap between two pixels. A solution to this could be to align the filament and the sensor at an offset angle, such that the filament is always being sensed by at least two pixels. This would obviously require some alterations to your code.

I would like to create a derivative of your project. I look forward to your feedback on the considerations mentioned above.

Comments deleted.

Hi Flipper, thanks for the good work. I'm connecting the sensor and puller motor and have some question:

Is one sensor enough to control oval filaments?
Should I put 2 sensors perpendicular to each other to create the circular cross section?

the tsL1401CL on mousier now comes up with min order 1000 and 23 weeks lead time, i see theses also on digikey but 3 different types, which one is needed https://www.digikey.com/products/en/sensors-transducers/specialized-sensors/561?k=TSL1401CL&k=tsL1401CL&pkeyword=TSL1401CL&mnonly=0&ColumnSort=0&page=1&quantity=0&ptm=0&fid=0&pageSize=25

Those are all the correct part. They are all the same part since they have the same manuf part number. The difference is the packaging and min order quantity that digikey provides. Try https://www.digikey.com/product-detail/en/ams/TSL1401CL/TSL1401CLCT-ND/3095283 for buying a single one.

That part is no longer manufactured but the good news is that they have around 20,000. Last time I checked 6 mos ago they had 16,000. There is a replacement part that will require a small change to the pcb design. Unfortunately for now, it can only be bought in qty of 1000.

Comments deleted.

Now it is impossible to buy 856-TSL1401CL, is it possible to replace it with something !?

I had this filament width sensor connected to my AirWolf AXIOM Dual (RAMBo) and it worked fine. I have gotten rid of that machine and upgraded to a UM3E, which at this time is closed-source.

QUESTION: My "old faithful" printer, a ROBO3D R1+, has a semi-custom RAMPS v1.4{.5} board, which was manufactured for ROBO3D and it's missing a lot of pins and traces that weren't required for this printer. Can I use the I2C header pins VCC, +5V and GND for this filament width sensor?

It sounds like you would be able to power the sensor with the +5v and gnd. I would use a meter to see if its 5v. You still need to find an analog input that's not set up for a temp sensor. The temp sensor inputs have bias resistors, which affect the filament sensor readings. I have a similar problem with my new Prusa MK2S, which is open source but no separate analog input on the mini rambo board. It does have an unused temp sensor input, tho. I am testing a little op amp circuit (voltage follower) to allow me to attach to an extra temp sensor analog input. So far the prototype is working. This might be an option for you if you can locate a temp sensor input that is unused.

Thanks Filip for the extremely informative and prompt reply. I have a “standard” RAMPS 1.4 board arriving in today’s mail and I’m going to swap it out in the ROBO R1+. There’s a full write-up on performing this procedure and it seems rather straightforward. This way I’ll have all the normal pins, headers, etc. for future upgrades.

Hey, as anyone tried to use this on a creality cr-10 by chance?

Hello, I have a trigorilla board (sold by Anycubic with their DIY kit) which doesn't have all of the the ramps pin, it has got only servos (D4, D5, D6, D11, D12) AUX (D42, D43) UART3 (D15, D14) and the T input (A12, A15, A14 and A13). A14 and A13 are the only one used ftb.

Which pin can I use instead of the A5/D59 which for me is missing in AUX2?

Thanks a lot in advance!


A CTRL+F didn't find anything that I could see, but I know with optical sensors, colours such as black or translucent filament may have a difficult time getting detected (certainly with optical endstops at least!), would that be the case here also?


Black is not a problem. Clear filaments, such as clear PET will not work. Also translucent red will be a problem.

flipper, great work, I just got a board a few days ago and it's up and running! A couple of questions for you:

  1. Currently I see the width reading in my LCD and when I enable width sensor with M405, the flow ratio goes up to 246% and my extruder starts spinning like crazy. I have a titan aero using 1.75mm filament and the sensor is reading accurately. Any ideas what's going on here...

  2. I have Linear Advance enabled in Marlin (1.1.4) and I leave the R factor at 0 for "auto mode" im not sure how this works, but if I leave it to calculate the r factor automatically, does it pull the filament width from the sensor?

Thank you!

The first prototype for the filament sensor was built in April 2013 and has evolved to the current design over about 1 1/2 years. Its held up pretty well and gives a level of robustness and precision that even surprises me. Only 1 has been returned as not working, and I use that one on my own printer because it was working fine. The design is starting to show its age, though.
The line image sensor used in this design is no longer being manufactured, and so I am reviewing some options on how to proceed. I still have a decent inventory at the moment. There is a replacement sensor, so the design change is not a big deal. The challenge is its sold in batches of 2000, which is 10x more than the yearly sales.

Some options:

  • Drum up sales of the filament sensor - so far sales have been direct to users, and no printer manufacturers have been interested, but that could change.
  • Sell a breakout board for the replacement image sensor, to recoup costs of buying larger quantities. Not sure if there is enough demand here.
  • Redesign for another image sensor. There are ccd modules that are getting cheap, but this would be a significant redesign.
  • Other??

I want to be able to keep supplying these things for all the makers out there, since there is really nothing like it for under 100 bucks. I am looking for input on this - please send me any suggestions...

Hello. i am thinking of building this, but when looking for the mcu on ebay (mouser wanted 6times the chip price to ship) there are quadzillion version of the chip. For example i found MC9S08SH8CTG TSSOP16, but i can't find any that have the 8SG8 in it. Does it have to be a 40Mhz version, and the exact cpu core?

I took a look at the XNP site, which shows comparisons between product lines - it say "S08SH Family is pin, tool and software compatible with S08SG, offering greater design flexibility."

I would give it a try. Worst case you would need to recompile for this change if it did not work because the pinout and peripheral version numbers are exactly the same.

I am trying to get this working on my ramps 1.4 with Marlin 1.1.3 firmware and I seem to have an issue.

  1. Although the sensor is reading and I can see the diam change which seems close to my measuring with verniers. The % doesn't show any change just sits on constant 100% but any video Ive seen shows this reflects the variation.

2.The system just froze 20% into a 4 hour print... would this is a buffer full situation? Do I need to change the default.

I have the measurement_delay_cm to 15 and the max_measurement_delay to 20

How would I setup this to record an error... I have Pronterface and can run my printer from that?

I found an issue in Marlin 1.1.3 with the ring buffer for the filament sensor going in an infinite loop under rare conditions. I suspect this issue has been there for a while, and was in my original code as well. Its been fixed in 1.1.4.

Thanks Flipper I will give it a try.

Hi Flipper,

Is the problem with the filament width sensor running out om memory, as mentioned by "ghirotre" below, solved yet? The reason I am asking is that as far as I know I have the latest Marlin Firmware and I get that my controller boots randomly when I use the filament width sensor. It would be a real sorrow to let my LCD go for the sensor to work.



Nic, The filament sensor does not have a memory problem. The problem is with Marlin, depending on how many features are configured, is beginning to use more RAM than is available in a Mega2560 arduino board (8kb). I've found the bed leveling uses a lot of RAM, the LCD, as well as the filament sensor buffer. The code for the buffer uses some data compression to use bytes rather then words, which already saves space. You can reduce the buffer size, at the expense of some reduced control of the filament width.

Sorry Flipper,

I did not mean the width sensor itself, I just meant the problem you were talking about below. I have last night saw the printhead starting to retract every second and not doing anything actually after increasing the buffer to double the size. It seems it does not matter if I make the buffer smaller or bigger, I get problems at some stage. Can I ask what you mean by reduced control of the filament width.

I also saw that thinkyhead on the Marlin forum said the latest bug fix release has freed up quite a substantial amount of memory. Just have some doubts about the bug fix release, but I suppose it is not going to hurt to try.

But otherwise feel proud of your work. I never had such consistent prints, and I now actually have control over my printing. I can see the smallest changes actually manifesting itself in my prints. Does not matter if you use $1000 per roll filaments or relatively cheap filament you get the same prints over and over. I love it.



Hi flipper,

I'm currently trying to flash the MCU using the USBDM with the HCS08_FlashProgrammer software, and I keep getting the "Connection with target has failed. Please cycle power to target. Retry connection?" and after eventually selecting no, I receive "Programming of the target flash failed! Reason: Target SYNC timeout". Do I need to connect the PCB to power as well? I get the same response from the program whether I connect the USBDM to the PCB or not, and my computer seems to recognize that the USBDM is installed correctly - I've never worked with any of this equipment before, so any pointers are welcome.


It looks like I've fixed my problem myself, but I'll leave this up here in case anyone else has the same problem. I connected the 5V and Gnd pins to the corresponding terminals on the PCB and managed to find the correct orientation of the connector from the USBDM to the PCB, and it flashed immediately and works well so far.

Hi flipper,
I finally broke down and bought another USBDM and have successfully flashed a board.

I must have shorted the old one so now instead of supplying external power for flashing, I'm going to use the internal TVCC supply to flash with.

Thanks for all your help.

I am glad you were able to identify the culprit. Usually that is more than half the battle in these projects.

Hey Flipper,
I have finally found enough time to get my extruder in working order, the sensor works great with a stepper motor and basic stepper code.

I am wondering why I'm getting 1.54-1.57 for my filament diameter. I am using the 1.57mm rod that you supplied. Would it help to use a 1.75mm rod? I thought the code in the sensor just calibrated to 1.57 and adjusted filament diameter to 1.75

Hi Filip,
I have posted a topic on your websites forum, however I have not had an response.

The filament sensor board does not have a USB interface so doesn't do what you want to do.

Hi All,

I just printed the case, installed, then calibrated this sensor on my Axiom Dual and did the Marlin changes as per this site: https://github.com/MarlinFirmware/Marlin/pull/1141/files -- Perhaps I am missing something, but on my LCD (VIKI2) the "Var" value shows 100% continuously, even while the "Dia" varies between ~2.65 to ~2.78mm during a print. Any advice?

ColoRich, I've been traveling so could not get to your message. - Be sure to use the latest marlin, branch 1.0.x since there is a fix for the graphical LCD: https://github.com/MarlinFirmware/Marlin/pull/2264. I don't have a graphical LCD myself, but I believe others have used them successfully.

I'm having the same problem here with 1.75mm filament! But my guess is that we are doing something wrong in Marlin configuration.

UPDATE: I have enabled sensor with M405 and factor is chaning, but not correctly. I got 96% factor when filament is 1.77 and 94% when its 1.75mm. Marlin configuration is setup to 1.75mm filament (at sensor configuration) and my slicing program is set to 1.74mm with 1.0 extrusion multiplier.

Hmmm, I left mine stock in Marlin for my 3mm filament. Where did you enter the M405 script? I added the M405 to my start .gcode in Simplify3D. Still nothing.

Here's my "Start .Gcode" script for S3D:

M42 P6 S255 ; lights on
M107 ; start with the fan off
G28 F200 ; home all
M190 S[bed0_temperature] ; set bed temp
M104 T0 S[extruder0_temperature] ; heat left nozzle
M104 T1 S180 ; heat right nozzle for cleaning and leveling
M109 T0 S[extruder0_temperature] ; heat left nozzle
M109 T1 S180 ; heat right nozzle for cleaning and leveling
T0 ; switch to left nozzle and retract filament
G92 E0
G1 E-15 F1200
T1 ; switch to right nozzle and retract filament
G92 E0
G1 E-15 F1200
T0 ; switch back to first nozzle for auto leveling
G1 Z0 F1200 ; raise bed for nozzle cleaning
G1 X12 Y228 F7000 ; position nozzles before brush
G1 Z-2 F1200 ; lower nozzles to brush
G1 X148 Y228 F1000 ; clean nozzles
;G1 X12 Y228 F1500
G1 X148 Y228 F1500
;G1 X12 Y228 F2500
G1 Z0 F1200 ; raise bed to Z0 to avoid contact
G28 X0 Y0 ; home x and y
M204 S300 ; set accel for probing
M203 Z4 ; set z max speed for probing
G29 ; autolevel
M204 S3500 ; set accel back to normal
M203 Z20 ; set z max back to limit
G1 Z5 F200 ; raise nozzle up 5mm
T1 ; switch to right extruder
G92 E0
G1 E15 F600 ; extrude filament back into right nozzle
G92 E0
M104 T1 S0 ; turn right extruder back off
T0 ; switch to left extruder
G92 E0
G1 E15 F600 ; extrude filament back into left nozzle
G1 X16 Y175 F6000 ; move to left extruder prime location
G1 Z0.5 F1200 ; lower Z for prime
G1 X16 Y200 E30 F300 ; prime left extruder
G1 X16 Y205 F9000 ; wipe
G92 E0
M400 ; clear buffer
M405 ; activate filament diameter calibration
;M117 AXIOM Printing... ; Put printing message on LCD screen

I've just added M405 to start script, like you. Actually, mine is almost perfect. I've setup my simplify3d to 1,75 diameter, but my sensor is setting a factor of 96% when reading diameter is 1,77.....should be something close to 98 or 99%, or am I wrong flipper?

The factor is based on cross sectional area of filament not diameter. So ((1.75)^2)/((1.77)^2). Also there is some precision lost in the marlin code due to integer divide. So 96% sounds right.

Filip, can you suggest any reasons why mine is not varying from "100%" even with the "Dia:" changing? If it matters, I bought mine from your website last week.

Hey flipper,

Is there an easy way to retarget this flash program to use MC9S08QG8?

I tryed to just changs the code by replacing, however I got 66 errors.

My code is written for the SG peripherals based on specs in the data sheet. Even though the part numbers are close,they may use different peripheral versions so the code would have to be changed in that case. Also, this processor is 3.3v, while the SG is 5v. Its doable, but not easy. You would have to start with a new project built for the QG8 (so that the right initialization code and .h files are built) and then copy and paste in the code from the project into it, and make any changes due to peripheral changes.

Comments deleted.

I've built the device and am trying to flash it but I keep getting errors when trying to flash.
I am using CodeWarrior for MCU, Version: 10.7 Build Id:160721.
I am doing the following steps:
1) Select Flash File to Target
2) Create New Connection profile
a) Name "USBDM"
b) Template - None
c) Target - New
d) Create new connection
d.1) Name - Filament_Sensor_Board
d.2) Template - None
d.3) Target Type - MC9S08GB32
e) Preferred BDM - USBDM JB16-0001 v 4.10.2
f) Target Vdd Supply - Off
g) Connection Control - Automatically reconnect
h) Internal Clock Trim - Disabled
I) Security Options - Default unsecured configuration
J) Erase Options - No erase done

I then initiate the flash and the console log is as follows:
/=== CodeWarrior GDI protocol log ===
GDI DLL: C:\Freescale\CW MCU v10.7\MCU\bin\Plugins\Debugger\protocols....\support\hc08\gdi\usbdm-gdi-hcs08.4.dll

GDI: DiGdiOpen()
GDI: DiGdiGetFeatures()
GDI: Identification: USBDM HCS08, Version: 1.2.6, MeeAvailable: false, NrCpusAvailable: 1
GDI: DiGdiAddCallBack(cb_type = 0x4000)
GDI: DiGdiInitIO()

GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : net.sourceforge.usbdm.connections.usbdm.setTargetVdd, Value : 0, R) => DI_OK
GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : net.sourceforge.usbdm.connections.usbdm.cycleTargetVddOnReset, Value : 0, R) => DI_OK
GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : net.sourceforge.usbdm.connections.usbdm.cycleTargetVddOnConnect, Value : 0, R) => DI_OK
GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : net.sourceforge.usbdm.connections.usbdm.leaveTargetPowered, Value : 0, R) => DI_OK
GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : net.sourceforge.usbdm.connections.usbdm.maskInterrupt, Value : , R) => DI_ERR_NONFATAL
GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : net.sourceforge.usbdm.connections.usbdm.automaticReconnect, Value : 1, R) => DI_OK
GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : net.sourceforge.usbdm.connections.usbdm.useResetSignal, Value : 0, R) => DI_OK
GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : net.sourceforge.usbdm.connections.usbdm.usePSTSignals, Value : , R) => DI_ERR_NONFATAL
GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : net.sourceforge.usbdm.connections.usbdm.useAltBDMClock, Value : 255, R) => DI_OK
GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : net.sourceforge.usbdm.connections.usbdm.connectionSpeed, Value : , R) => DI_ERR_NONFATAL
GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : net.sourceforge.usbdm.connections.usbdm.powerOffDuration, Value : 1000, R) => DI_OK
GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : net.sourceforge.usbdm.connections.usbdm.powerOnRecoveryInterval, Value : 1000, R) => DI_OK
GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : net.sourceforge.usbdm.connections.usbdm.resetDuration, Value : 500, R) => DI_OK
GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : net.sourceforge.usbdm.connections.usbdm.resetReleaseInterval, Value : 500, R) => DI_OK
GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : net.sourceforge.usbdm.connections.usbdm.resetRecoveryInterval, Value : 500, R) => DI_OK
GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : net.sourceforge.usbdm.connections.usbdm.defaultBdmSerialNumber, Value : USBDM JB16-0001, R) => DI_OK
GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : com.freescale.cdt.debug.cw.CW_SHADOWED_PREF.HC08 Debugger.processor, Value : MC9S08GB32, R) => DI_OK
GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : net.sourceforge.usbdm.connections.usbdm.trimTargetClock, Value : 0, R) => DI_OK
GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : net.sourceforge.usbdm.connections.usbdm.eraseMethod, Value : 0, R) => DI_OK
GDI: Mtwks Callback(MTWKS_CB_PROJECTACCESS, Section : , Entry : net.sourceforge.usbdm.connections.usbdm.securityOption, Value : 2, R) => DI_OK

I then get a message box stating:

USBDM - Target Connection Failure
Enabling BDM interface on target failed.
The target may be secured.
(Use stand-alone programmer to mass erase if necessary)

Please cycle power to the target.

Retry connection?
Yes No

I power cycle the board and click continue after which the log shows:
targetConnect(): Target is secured

And a message box appears stating:

Device appears to be secure and may only be programmed after a mass erase which completely erases the device.
Mass erase device?

I select Yes and the console displays:

Performing target initialization ...
Device MC9S08GB32_FLASH
Erasing .............
Erase Command Succeeded.
Device MC9S08GB32_FLASH
Flash Operation. ...
Auto-detection is successful.
File is of type Elf Format.

Device MC9S08GB32_FLASH
Programming ....

And then another dialog box:
USBDM - Target Connection Failure
Enabling BDM interface on target failed.
The target may be secured.
(Use stand-alone programmer to mass erase if necessary)

Please cycle power to the target.

Retry connection?
Yes No

Again I power cycle the board and click Yes at which the console displays:

Error: Program Command Failed. Operation timeout. Security area should not be programmed with a value that leads to irreversible secure
. Protect violation error. Error in command sequence.

What am I doing wrong? I am pretty proficient with Arduino flashing but I have no experience with these boards.

Thanks for reading.

You need to change the target type, which tells the flash programmer what MCU you are programming (kind of like the Board selection in Arduino). You should set it to MC9S08SG8

In your listing above, it appears to be set to Target Type - MC9S08GB32, which is the wrong MCU.

First time programming the MCU might take a few trys of power cycling.

Thanks, I fixed that mistake but now I try to flash and get:

fl::target -lc "LC for Simple Flash (5)"
fl::target -b 0x80 0x200
fl::target -v off -l off
cmdwin::fl::device -d "MC9S08SG8_FLASH" -o "8kx16x1" -a 0xe000 0xffff
cmdwin::fl::protect all off
Beginning Operation ...
Performing target initialization ...
Error: Connect Failed.
Can't connect. Target BKGD pin timeout(HC/RS/S12Z GDI Protocol Adapter)
Error: Connect Failed.

I toggle power and try again but it will never connect.


Here is what I would try:

  • check for shorts on the board, especially if you soldered it yourself. Maybe the BKGD pin is shorted?
  • I did a google search to see if anyone else has seen this error - this might help - https://community.nxp.com/thread/308760
    -Do you get the same error with the board disconnected?
  • Try programming it with the "HCS08 Programmer" application and not the IDE connection to see if that works. This application is in the folder where USBDM lives. I noticed that thingiverse lost the instructions doc for my thing, but I uploaded it again. In the instructions I describe more detail on how to do this.
  • Based on your previous post it looks like you had communicated with the MCU as a MC9S08GB32, since I am seeing 'erase command succeeded' meaning communication occurred and flash was erased. I am wondering if this might have caused irreversible damage, since that one has 32kb flash and the one in the filament sensor has 8kb. You might need to replace it on the board.

I've build and flashed my board.....but when I try to calibrate using 1/16 drill rod (1.57), I always got 1.38V instead of 1.57v. I alread checked LED position (to make sure it's straight), connections, supply (tried with stabilized 5v power, and now it's testing on RAMPS), always same result. I have included two PTFE tubes on in and out of fillament to make sure that's really straight and not bended.....always same result: 1.38v on calibration. What am I doing wrong?

Flipper, any idea on this problem? :(

When you say calibrate do you mean put in a piece of 1.57mm drill rod and press the calibrate button for a few seconds until the LED turns back on? Normally, then you should see close to 1.57v on the output since the sensor assumes the input is 1.57mm and scales the output to match. If you do that, and get 1.38v, then I am wondering if there is too much load on the output pin. Does it show 1.38v with the output just hooked up to a voltmeter?

Also if you get sporatic results, try taking out the LED and turning it 1/4 turn and putting it back in. sometimes the LED light exhibits a pattern with lighter and darker lines which the sensor reads incorrectly. If you turn the LED, it eliminates this problem. Also, your LED should fully illuminate the image sensor with even light. LEDs have different beam widths and so this might be causing some of your problems.

Flipper, I think I made it....I've changed the capacitor and resistor of output and used my lab power supply totest with 2v. Now I can read 1.56v with 1/16 drill rod, which I consider fine. The problem is that my RAMPS (which is working fine) provides 4.77v on indicated pin. It's now a problem for most of circuits, but since yours are calibrated for 5v, I guess this is my problem now. While connected to RAMPS, I'm getting 1.47v ~ for the same drill rod....it's about 10mV less than ideal. I've checked the input voltage at yout board (before any caps/resistor) and it's reading 4.77v. So, It's possible to change the code to compensate for this? What is your recomendation?

UPDATE: Any filament or rod that I use for calibration, always read 1.47v after calibration successfull (press and hold button until led turns on). Also, Always same value (1.47v) for steady LED or blinking LED.

Yes, calibrating procedure are right, LED turns on correctly.....the only problem is that I see 1.38v on multimeter (directly, not in RAMPS). I've checked my multimeter and it's right, it's reading 1.38v on both of my multimeters. About LED: I'm using RED high bright and I've changed position to make sure that light is right on the center of sensor....i've changed a few times to test it. I'm using 1/16 drill rod to calibrate.

Hi, i have made your model and buy your board.
It is working good with my printer p3steel and wade extruder.
But i have a big problem.
If I active your sensor in marlin and before print command M405 my print stop randomly.
If I comment in marlin filamemt sensor the printer is all ok.
I have an Arduino mega with ramps 1.4 and set up 14cm distance from the sensor to hotend and 20cm in memory.

I have had a similar problem with a teensy based controller running out of ram space with an lcd, bed levelling, and filament sensor features enabled. I ended up giving up on the lcd. I think the mega has more ram but it might be the same problem. You could try lowering the memory usage to 15cm to use less memory. To test if it is a memory problem you could temporarily reduce the memory buffer and the distance from the sensor even more. You could also temporarily drop the lcd support to see if that helps -to diagnose the problem. What version of marlin are you using? You should log this issue out on the marlin github site so that it's properly tracked. I will take a look at the code.

Is there any recomended color for LED on tower? White?Yellow?Red?

It was designed for a red led with a 2.2volt drop since the linear array sensor is more sensitive to red light. White and blue work too but since they have a higher voltage drop they don't get to full brightness.

Hi Flipper

I want to use your sensor with 3th party filament extruder (Filabot). Pulling the filament from nozzle and with your sensor optimize the diameter. Is there an available similar setup to what I want?

I am not aware of any one customizing a Filabot with this sensor. Unfortunately I don't have any experience with the Filabot.

Thank You for your answer
And can be used your sensor, as standalone loop?
Just measuring output from ANY filament maker, and driving the stepper motor to get the right diameter?

Hello Flipper, I want to use a 2mm diameter to calibrate the sensor, I install the freescale ide,
I modify the main code, but I don't know how to compile the source
can you help me please ?

I assume you have the eclipse based IDE. Take a look at the quickstart guide, starting from Section E - debugging your application.


It shows how to build and debug. Do you have a programmer like this one?


It works with codewarrior IDE and has been used by others to program the firmware on the sensor board.

yes I have this programmer
thank for helping

Flipper other than the 3 mother boards listed in the Config.h file of marlin... is there a list or forum post or any source with details of other 3D printer motherboards that people have successfully configured your sensor?

I have been commissioned to build a high end 3D printer in house as a teaching project, so money is not an issue and I want to see what my options are.

As far as I know there is not. Its generally a matter of finding an unused analog input on the board and then changing the pins.h file in Marlin to make the new pin available to the rest of the code.

Thanks fr the reply. I will be trying to set this up on a Aus3D Rumba+ board in the next month... I'll report back my settings if it works out.

Hi flipper,
Is there a chance to sell some of this sensor in the future ?

Yes I will have more available in the store in a week or 2.

Hello Flipper
I have built this sensor and calibrated it using a 2.99 mm rod and when I measure the voltage output out of the sensor (with the rod inserted and steady) it shows the correct measurement (it oscillates between 2.98 and 2.99 V) showing that it works just fine and everything should be alright with calibration, the board and the printed case.
However I'm using it with the filament extruder V5, the LCD readings are oscillating so much anywhere between 2.64 mm to 3.83 mm. I measured the aux 2 pins of the ramps board and its supplying 5V as well and the signal going into the RAMPS board is the same as the one measured right at the sensor terminals (2.98 - 2.99 V).
I don't have much knowledge of programming but I'm trying to figure it out, I suppose some oscillation is expected but not of that magnitude.
Do you have any clue what it might be ? or what should I look for or add into the mackerel code ?
Thank you for your time.

Hello Flipper.
I thought i would build this and try it out, but i can't find the correct "MC9S08SG8CTG" on ebay, ali-express or mouser. There are a lot of other modelnumbers, like : MC9S08SE8CTG or MC9S08QG8CDTE. Some have 20pins, some 16, some 8, very confusing.
But which one are compatible?

Looks like the model number changed. Its S9S08SG8E2CTG.

I have installed mine onto a PICA revB board (http://community.reprapwilson3d.com/t/i-designed-a-new-rendition-of-ramps-called-pica/167) which runs a forked marlin 1.0.4 by mjrice (https://github.com/mjrice/Marlin) I am running 1.75 filament and although I have calibrated it and set all my parameters I am getting 2.2 as my dia when connected to the MB using pin 12 which was a temp in pin.

If I disconnect the Out pin I get the proper size aprox 1.5v on my multimeter but as soon as i connect it i get 2.2v. I have run a print and watched the filament being measured but in the 2.33 range. the factor is always 100% and never changes.

I am in contact with the board maker (Mjrice) and waiting a reply but is there anything else I should try in the meantime... anything obvious from what I am describing here?

It sounds like either the pin on the PICA is not configured as an input or it has too low input impedance. The sensor board expects an input impedance greater than 5k ohm or so.

fiipper thanks for the reply I'll put this to mjrice and see if he can come up with a "work around" for me.

Does anyone know if this is possible with a MKS based Board? If yes: how it´s been cabled ?

hmmm I know that, optical mouse has a tiny camera. is it possible to use that sensor?

Great project and I received a board from you to experiment with.

I'm working on a prototype design and I want to firmly mount the sensor enclosure onto my carriage in a single print (potentially)

Is it possible to get the source files for the "For Printer" version of the case? I can figure out something if that's not something you're comfortable with.

I'm also trying to understand the "//measurement delay in cm. This is the distance from filament sensor to middle of barrel" and the "middle of barrel comment". Is this the nozzle tip or the middle of the extruder hobb? My inclination is the former but if you happen to know I'd appreciate it. I'll edit this if I find the answer

Mike, have you gotten this filament width sensor to work with your ROBO R1+? As you probably know, the connection pins in Filip's instructions don't exist on the ROBO "custom" RAMPS board. Please, let me know if you found any alternative connection point(s) for the 3 wires. Thanks.

I saved the CAD files out in the "Thing Files" See the two zipped folders. One is labelled printer. The CAD files are for a program called Cubify Invent. It might be similar to Alibre.

As the solid filament enters the 3D printer extruder heated barrel it liquefies somewhere in the extruder barrel before coming out of the nozzle. It is at that transition point (right before it melts) where the filament cross section acts as a piston and pushes the liquid plastic in the barrel and out the nozzle. The cross sectional area of the filament at that point is effectively the size of the piston and so is the key variable we want to measure. My guess is that this occurs somewhere in the middle of the barrel before the nozzle tip.

Awesome thanks. Are you aware of anyone using your device as a filament runout sensor? Seems to me you could use a parallel circuit to look for low voltages (<1v) and go low triggering the filament change alarm in marlin

Yeah, I thought about that too. Seems like the Marlin code would be pretty straightforward.

Here is a new simpler filament extruder controller made by Anthony that uses an arduino board and a low cost motor driver to control a brushed DC motor. http://www.thingiverse.com/thing:1454222. He is looking to use it to re extrude plastic bottlecaps.

ulletjes filament extruder

Good afternoon!
I have successfully assembled filament sensor that outputs a voltage proportional to the diameter - 1 mm - 1V.
But there is a problem in Marlin.

The "MEASUREMENT_DELAY_CM" works with a value of up to 5 cm.
Moreover, during operation, the delay time randomly varies from 1 cm to 5 cm.
And I have a "Bowden" - 69 cm !!!

Marlin - 1.1.0-RC3 - 01 December 2015 (the only version, which once earned the sensor).

Please, help!
I apologize for bad English.

This is great! I am very excited for this project. The possibilities of using this with self extruded filament made this a big winner for me.

We've built our own boards exactly per the specifications. Out of the 3 we made, one doesn't work. BUT two of our boards have the green indicator lights and are detected by the USBDM-1-JS16. We can erase, but when we try to load with get the message: "Verify Failed" Verfication of the target flash failed. Reason: Program Data Not within target Flash Memory

Can someone help us as to what is going wrong?

I have never seen that message. Maybe you selected the wrong target device in the programmer? Should be MC9S08SG8.

Stupid questions: how does this handle oval filament profiles? How does it handle clear or semi-clear filaments?

I tried clear PETG: currently not working for printing.

Hello! Mr.flipper,Can you tell me how to change the calibration data in the source program,Because it is difficult to find the things diameter which is 1/16 in, 1.57mm, Thank you! I am looking forward to your reply ~!

The latest version of the firmware available here does this already - look for Freescale_8_bit_code_032015.zip. With this firmware, the sensor can use either a 1/16 in drill rod OR a 3mm rod for calibration. The firmware can detect the difference at calibration time.
If you want to change to other rod sizes besides 1/16 or 3mm, look for the following #defines in the code:

//These defines set the two types of calibration rods that are possible to calibrate the sensor with

define CALIB_STANDARD_A 6329 //calibrate using a drill rod of .062 in diameter (1.57 mm) set to (1.57 mm)(15.748 pixels/mm)(256 fp)=6329

define CALIB_STANDARD_B 12094 //calibrate using a drill rod of 3mm set to (3.00 mm)(15.748 pixels/mm)(256 fp)=12094

define CALIB_STANDARD_THRESHOLD 9211 // Threshold for automatically determining the size of the calibration rod based on inherent sensor accuracy.

The comments give the formulas to convert the rod size into pixels into the fixed point number format used in the firmware (floats are for babies :^) ). Note that the rods need to be substantially different sizes so that the sensor can detect the difference based on a threshold.

Hello,Mr.Flipper ! Thank you for your reply , but I have little problem.......which file can change those parameters ? And I still have another problem,according to the 【LYMAN_MULIER_FILAMENT_EXTRUDER_V5_MANUAL_R1.pdf】,the Filament Width Sensor have two mode, ratio‐metric mode & absolute voltage mode, I try to press the button to change the mode ,but nothing happened ,whether it is because my standard parameters is fault ? this is weird ,can u tell me? thank you ,Mr.Flipper ^-^

The file is Filament Sensor proto2\Sources\main.c. Yes there are two modes by pressing for 1 sec or less. I am not sure why its not working for you. I am guessing it might be a hardware issue, assuming the flash programming worked fine. Is the LED on the board working? It should flash after pressing the button for a second or so.

Any Repetier Firmware possibilits?

Congratulations. Very nice project.

I am sure it is possible, but I think my head will explode if I try to figure out how Repetier firmware works in addition to Marlin. It took me about 6 mos to figure out Marlin enough to make changes, and its a constant effort to stay up to date on the Marlin code base. Here is how I would approach it though:

  • find the code where the extruder temp is read from the A to D converter and use the same design to read the filament sensor on a free A to D channel.
  • find the code where each gcode extruder command is converted into the stepcount for the move and insert a factor based on the filament diameter like (expected_dia/measured_dia)^2 so that the stepcount sent to the move planner is modified.
  • find where the gcode text commands are interpreted and add some new mcodes so that you can turn on/off the filament control and modify its behavior.

If you can get that to work, then refine by adding the ring buffer to handle the filament transit distance (distance from where the sensor measures the filament to where the filament melts in the barrel).

I removed all smoothing code from the mackerel firmware and then placed a piece of filament in the sensor. The reported width always fluctuates 0.11mm (3.20-3.09) Is there a way to improve this?

It's mentioned somewhere in this thread that the sample rate is 100hz but the output is only updated 1/sec. However when extruding (for example) 40mm/s then averaging those 40mm might mean that it is possible that a long piece of filament with a diameter larger then 3.1 will not be reported (averaged out) but when using that filament it will block the 3d printer extruder. Is it possible to improve the 1/s update rate?

Found the source of the 0.11 fluctuation (I think). Ordered some parts to test my theory.

The 100hz sample rate I could not find in the source , I could only find a 5Hz sample rate. ctrate =2 (that is the time period between samples in 100ms) ?

For those that want to test that 0.11mm fluctuation. I have connected the sensor to a aduino and wrote a very short sketch.
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
delay(10); // delay in between reads for stability
I collected around a 1000 samples while a piece of filament was placed in the sensor. This is the result:


The black line is a 32period moving average.

I think what you might be seeing is the ripple in the output due to the D to A converter. The circuit uses a simple pulse width output and some filtering to produce an output voltage. The output has a .1v ripple at 16.6kHz. See the two photos of my scope traces:

I would use some additional low pass filtering to reduce this ripple before sampling at the rates you are using.

The ctrate parameter affects the overall sample rate. The code comment is incorrect, the max sample rate is 256 Hz for the interrupt counter, so a ctrate=2 would give a 128 Hz sample rate. There is a simple lowpass filter in the code (an exponentially weighted moving average) that has a filter param widthfilterparam = 5. That is 5/256=.01953. See http://gregstanleyandassociates.com/whitepapers/FaultDiagnosis/Filtering/Exponential-Filter/exponential-filter.htm On this site a param a is used where a=1-.01953 to relate back to the filter in the code. This results in a time constant of roughly .4 sec. You could change the widthfilterparam to a larger number to reduce the time constant. This will result in a faster sensor output.

Thank you! That info pointed me in the right direction :-)

Might still not understand it completely but if the time between samples is 2/256 and widthfilterparam =5 is it then not 10/256 (0,0391) ?

Minor questions

  • did you profile the main routine? In other words is it fast enough to be executed within the 1/128 second? If you did not profile it, no problem I will try to do it.
  • why the lowpass filter? Did you see weird values sometimes? With other words is there really a need for the filter?

The parameter widthfilterparam does not affect the time constant linearly - see the link for the formula that relates the widthfilterparam to the time constant. If you don't want to mess with formulas, you can change it and see what happens - the range is 255 - will provide no filtering, 1 - provides longest time constant.

I did not profile the main routine, but I did some tests where I added debug I/O so that a high pulse was output when the main loop finished and also when the interrupt started and confirmed that the main loop ran with time to spare within the interrupt cycle.

Lowpass filter was there to avoid customer support issues where casual users might assume there is a problem if they see the output vary constantly. I suspect that some filtering is needed but it probably can be reduced.

If the sensor is 400dpi, that works out to 15.75 pixels of resolution per mm, or 0.0635mm/pixel. Is there some sort of supersampling that takes place to increase the resolution? Because it seems that 1 pixel of resolution means it is either 3.00mm filament or 3.0635mm or 2.9365mm which would be a pretty giant difference for just one bit which I'd expect is within the domain of error in the sensor.

Testimonials of users indicate the device works, but how can just 1 pixel effectively tuning the extrusion multiplier 2.1% one way or the other be accurate?

Yes, as inornate says it uses interpolation between the pixels, which gives an accuracy of about .02mm with the sensor in practical use.

But the shadow casted by the led on the sensor doesn't cover the full sensor so only a small part of the 128 pixels is used to measure the diameter, so the smaller the shadow the larger the error. I think it would be improve the data if there was an option to increase the distance between the filament and the sensor depending on the thickness of the filament, it would improve the precision of the measurement.

Some screw system to increase/decrease distance and the calibration routine notifying the user as soon as 90% of the sensor is covert by the calibration rod shadow. Two issues with this

  • The calibration rod must be equal to the desired filament diameter
  • If the filament is more then ~ 11% larger then the desired diameter the sensor will not be able to measure the real diameter. However that 11% would already make the filament unusable for 3d printing as it will block the nozzle.

Wow, that's incredible! I mean the results clearly speak for themselves, but I was just curious how it could work given the precision of the sensor. Thanks for the explanation, and really great idea!

There're sub-pixel interpolation feature.
I migrated this code for Arduino, and for sure there it was.

What is the difference between Absolute and Ratiometric? If Ratiometric is not sending an absolute voltage amount equal to the measurement, how is it communicating the value to the printer controller? I can see that with absolute, you are using the bandgap to determine the actual source voltage so it can set the PWM correctly. Is ratiometric assuming the source is 5V, and not something close like 4.8v?

The printer controller's A to D input is ratiometric. In other words, it measures the input voltage relative to the supply voltage. So if the filament sensor is set to ratiometric, it is also relative to the supply voltage, in effect cancelling out the impact of varying supply voltage, or a supply voltage different from 5v. For example, In ratiometric mode, the sensor outputs 50% output for 2.5mm and 100% output for 5mm. If the supply is 5v then its 2.5v and 5.0v out. If the supply is 4.8v its 2.4v out and 4.8v out. At the input of the printer controller, an input of 50% is interpreted as 2.5mm and an input of 100% is interpreted as 5mm.

Hello~ Mr.Flipper , why I can not found the BKGD port in the PCB board ? How the firmware upload to the chip ? By the way ,happy children day ~! :p

See the holes for a 6 pin header below the push button switch. A header can be soldered in to connect the programmer. Alternatively, you can use spring loaded contacts to program (what I do).

hello,I have a problem about Lyman FILAMENT EXTRUDER . I had connected the thermistor,but it cant work .On the LCD, it display 0°C. And my thermistor is MF58 100K, I m also set the thermistor mdel is 9 in the Configuration.h . But it is still cant work. Can u tell me why ?Please T-T.And i m also want to know how to set the setpoint temp,Can u tell me? Please ,Thanks

I posted an updated firmware. The only difference is that now you can calibrate the sensor with either 1/16in (1.57mm) drill rod or 3.00mm drill rod. The sensor can tell the difference automatically. The new firmware is called Freescale_8_bit_code_032015.zip

Thanks for making and sharing your design. I've seen the work you and Wane Kinne have done with the dual sensor V5 filament maker. Do you have plans to release the modified firmware with the PID tweaks? I'm building a V5 and would like to make it a dual sensor with Teflon die.

Yes, the code is out on github. It is a version of Mackerel that supports a second filament sensor ('blob' sensor) positioned right after the extruder. It has a second PID loop that is adjustable via the LCD menus. The LCD will now show the blob size where it previously showed the min/max (you should see ‘b3.5’ there indicating blob size) This is very experimental with limited testing. Note that it will wipe out your existing settings saved in eeprom and will start with default settings. You might want to jot down any existing settings you changed before installing it. This is because I added all the new PID params to the eeprom to allow them to be saved.

I've found that this control might be helpful for controlling the extruder, even without a teflon die. Also, there is a repetitive pulsing in the extruder output that matches the screw RPM. I've wanted to update the code so that it is able to change the extruder speed within each rotation to compensate and smooth out the pulses.

The filament sensor (puller control) is hooked up to the original place on the RAMPS. The blob sensor now needs to be hooked up to a new input. Attached is a picture of where to hook it up (called RAMPS wiring and instructions with blob sensor.pdf. Note that its hooked up to AUX-1 and pin configuration is different.

Hello Filip, could you take a look to this post on the reprap forums on how the auto adjusting feature in Marlin works? http://forums.reprap.org/read.php?70,475206,504449#msg-504449

See my comments on that site.

Comments deleted.

I dont understand how you can get usable data when you only measure the width in one direction.

Is there some math voodoo going on we dont know about?

And In practice are there any improvements to your prints?

Some before / after pics would be interesting.

It just assumes the filament is round like a circle.

I'm not the designer but it has improved my prints with some filaments. As an added Bonus, I can print some of my filaments with the same gcode without any adjustments.

Hi, I just ordered 2 of these and have installed the first one on my printer. Everything seems to be working except when an item is printing the status of the sensor flashes on my LCD so fast I can't see what it says. I'm using the full graphic controller. My flow rate also stays at 100% no matter what size the filament is. I can manually feed and see the mm range of 1.69 to 1.76 but flow rate stays @ 100%. Set at 1.75mm in my slicer. I've change the start code to include M405.

//When using an LCD, uncomment the line below to display the Filament sensor data on the last line instead of status. Status will appear for 5 sec.


That last line doesn't seem t be working as I see the status of the print itself and only see sensor status for brief flashes. To fast to even read.



Did you get this figured out? I am also having the same problem with the Var being stuck at 100%...


Flipper a great job what you have make.
But can some one tell me where to buy the mc9s08sg8ctg in Holland.

Hello, Flipper. Many thanks for your excellent work on this project. I've printed the housing and received your pre-built kit via Storenvy, which was a real time-saver. The device works swimmingly, with one caveat (isn't there always one?) that I would appreciate your insight on. I can measure a minimum diameter of my series of gage pins of 0.93mm before the reading drops to zero. Anything smaller than .037" or so seems to disappear to the sensor. Again, I'd appreciate any guidance you could give me on getting this reading down to lower diameters. Ideally, I'd keep on seeing down to around 0.25mm... Thanks, Flipper.

The firmware is set up to output 0 volts for any signal less than 1mm. That is to avoid spurious output when there is no filament in the sensor. I am not sure if 0.25mm will cause spurious outputs.

Is there an easy way to get ramps 1.4 to have gcode fan control and this filament sensor, any progress on multiple extruders?

You should check the Marlin github site for your first question. I am not aware of any multiple extruder setups.

Thanks for the reply and great work again!!! I already checked and it's gonna require some code changes to use marlin's current method (don't have time personally) for automatic control if at all with my current ABL servo (will be gone soon I am moving to a induction sensor also then I could just use http://www.geeetech.com/reprap-ramps14-rrd-fan-extender-p-683.html) but honestly I don't even think I need the gcode fan in its current implementation since my i3 with ANC, ABL, firmware retracts, good calibration, and the filament sensor giving me near perfect extrudes seems to have made it so I can easily print working gears at really sparse to no infill;(my 2 year daughter can break them apart since it is 1 layer on the bottom with a very slight distortion) and even the NASA wrench is now working with ease...I'd even switch filament 50 times; and still know the print will still be spot on to near perfect. I'm using it with my custom unreleased bowden setup with 52CM of ptfe between the sensor and center of the nozzle and it still works very well at even 350+MM/s extrudes (didn't paint the case either).

Is there any patent challeges about this idea ?

There are no patent challenges.

I posted an stl file with a slight design change for 3D printers using 1.75mm filament. The hole that the filament passes through is reduced in this part. Its called "Sensor top plate printer 1.75mm version v3.stl".

Where can i get V3b of the software?

The latest version of the software is already posted in the Thing Files - Freescale_8_bit__code 06012014.zip http://www.thingiverse.com/download:759615 . There is no version 3b.

Does it output filament diameter in analog voltage or is it a digital output to the printerboard in the printerversion?

Its an analog voltage output. The printrboard (or RAMPS) reads the signal using its A to D converter.

I ported an Arduino version of this sensor.
Check out http://www.thingiverse.com/thing:636420 and any feedback would be appreciated.

Filament Width Sensor with Arduino Pro Micro and TSL1401CL

I was looking into making one of these but in the files you have uploaded here the pcb files for seeedstudio are for version 2.0, is this the correct files for v3.0?

Yes they are correct. PC board is on its own versioning scheme.

I order PCB but I've made a mistake and sent the wrong file v 1.1 :(
I have now a PCB version 1.1 Can it work with v3 ?

Both boards have the same outer dimensions, so they fit in either case. The only difference is the newer design has screw terminals. The design you have has solder terminals on the board.

Oh i see its kind of like v3b :P , thank you.

Can't wait for a version that takes into account the fact that filament is never exactly round.
Maybe you could use two leds at 90 degree that emit different wavelenghts and use filter with the sensors so they see only one wavelenght each. Dont know much about the subject (or if its even possible) but I'm sure there is someone with the proper knowledge out there that could give us a few hints.

How fast can it read the diameter? Will it be able to accurately measure filament up to 50ft a minute?

The sampling internally is about 100Hz, but the output has some averaging at roughly 1 sec time constant.

Hi Filip

Is there any problem with printing the housing out of Black ABS and therefore I can skip step 4

4 Paint inside of tower and top plate sensor area with flat black craft paint


I would think black ABS would work fine.

3D prints dont appear shinny beacause of all the layers but if you look closely each layers are indeed shinny. Wouldnt this cause issues?

Here is a guy who made one using black abs: http://www.binaryspace.co.za/?p=345 If it behaves erratically, you can always paint the black abs with flat black paint.

I'm using black PLA and have no issues. I made a Arduino Mega version with display, see http://www.thingiverse.com/thing:668377

Filament Width Sensor - TSL1402R + Arduino Mega (Work-in-progress)
by zasf

Can this be made to use 1.75mm filament

Sensor board would work with 1.75mm filament, but the enclosure case would have to be modified. You would need to reduce the size of the hole from 3mm to 1.75.

I'll take a look into programming the MCUs before they are soldered. I think there are special holders for that to attach the programmer to the leads. These MCUs are moisture sensitive so I need to check how to handle them after them come out of the pouch with desiccant. Maybe they can be re-dried somehow.

As for calibration, I think I can make the firmware detect the calibration rod (english or metric), because the difference between the 1/16 in. (.157 mm) and say a 3mm rod is large enough to detect from the raw sensor reading. I can get 1/16 in. drill rod with .0003 in. (.008mm) tolerance for pretty cheap ($1 for 1 meter length). Is it possible to get 3 mm drill rod with good accuracy (.01mm)?

You can find a precise 3mm rod in almost every retired (and new) DVD-drives. I found one with 2.995mm ...

Nice thanks, for the info.

Thanks for continuing the development. I really like that you added a buffer functionality, it is now possible to use it with a bowden extruder system.
An idea: Is it possible to use either an imperial calibration (as it is now) or a metric one? Most people in europe will have metric drills lying around (1mm, 2mm, .. ) but not imperial ones.

As Green Rider said, it would be really nice to get at least the programmed MCU and the PCB from somebody (although I can order the PCB myself, the programmed MCU not so much).

Dear flipper,
This is a very nice project and I would love to add it to my 3D printer but, buying a programmer and learning to use it with an MCU that I have never used before is too much work for one time project.
If you will make a kit with PCB,parts,MCU(already programmed), I think people would buy it (I will).

Think about it :)

I took your advice and made a few kits. You can buy them at: http://owi.storenvy.com/

I bought your kit but i am also making a few more for my dual head and my Filament extruder, my question is in order to flash the MCU all i need is the USBDM correct? Just want to be sure i dont need the Dragon12.


I received my Sensor today and hooked it up, I calibrate it and it reads 1.55mm all good right ,,, when i slide a 3mm piece of filament it reads 99 or less, it is like it is reading backwards. any suggestions?

Yes, you just need the USBDM-1-JS16 and hook it up to the 6 pin port on the sensor board labelled BKGD. This page http://www.evbplus.com/freescale_usbdm_osbdm/usbdm_osbdm_bdm_multilink.html has instructions. You will follow the instructions similar to 'Programming example #1" using steps 2-6. Use the HCS08 Flash Programmer (not HCS12 flash programmer as shown). The processor used on the sensor is an 8 bit 9S08 called 'SG-MC9S08SG8'.

The dragon board is a 16 bit HCS12 dev board which you don't need. I guess the USBDM can also be used to program that.

Comments deleted.

I am not getting a reading from the output, When i try to calibrate it will not. I have done all your tutorials and it still will not work. Any help will be greatly appreciated.

Sorry for the delayed reply - my internet went out for a few days. I have some questions to help us diagnose the problem. What application is it for a 3D printer or a filament extruder?. Are you using a voltmeter to read the output or a controller board? I assume you did print out a case and paint the inside with black paint? I assume your filament is not translucent? Is the LED in the light tower illuminating? One thing that may happen is that if you calibrate and not have the metal rod held down on the sensor it will incorrectly calibrate (will overflow) Then you will get spurious readings. This can be fixed by just recalibrating. Also it may be dust, too. Use a cotton swab to gently clean the sensor on the board. Let me know your answers and we should be able to get to a solution.

This is for a 3d printer.
I changed the board to 34 and hook it up like you show but i have no power at Aux2 for 5v, so i moved it to another location and i have lights.
My filament is black, when i calibrate i don't always get a reading of 1.55, as i write this it is stuck at 4.98 and this is after i calibrate it several times. I us the printer readout and a meter.

No worries i understand people work and have lives, I do.

If the output swings between 0 and 4.99 (or 5v) that means the calibration process was not right. When you press the calibration button, it takes a measurement of what ever is in there and then calibrates that to a 1.57v output. If it reads a 0 (or a low reading) for any reason it creates a very large calibration factor making the output swing between 0 and the maximum. This is because the factor = 1.57/0= infinity (or a large number) . Some reasons the calibration process could fail if: - the calibration rod is not flat against the sensor, There is light reflections in the case (no paint), there is dust or dirt on the sensor, the LED light is not uniform on the image sensor because it is blocked by something. One test you can do is do the calibration on the 3mm filament. Then you should see a reading of 1.57v or so when the 3mm filament is in there. If you try other filament slightly larger/smaller, the output will change from 1.57v. (eg 2.8mm yields 2.8/3.0*1.57v=1.46v) If this works, then we know the board works, but it is a calibration issue. Another test you can do is take the pc board out of the case and in a darkened room, lay the calibration rod on the sensor and hold the LED to shine down on the sensor and try to calibrate that way. You can then lay filament on the sensor and see if you get good readings that way. Then it might be an issue with the 3D printed case.

OK i finally had time to play with this, it turns out you were right the housing needed a little more filing and fine tuning. The unit works flawlessly now. Thank you for the support.


Thank you for clarifying this. Great work.