Tuesday, June 16, 2015

Digitize all those binders full of notes

Ever find yourself referring to your old notes and school work?  Why not cram that giant stack of sketchy, error-riddled paper into a pdf or nine?  Just think of all the advantages!
  • they would be more portable - you could put them on a usb stick or a phone
  • they would be easier to reference while doing design work on the computer
  • they would take up less space and collect fewer dead bugs 
  • they might not get damaged by the leaky roof or eaten by termites
  • they could be shared with people who want to learn that they can't read your shitty handwriting
Maybe you could even have the prescience to approach this task before you're two years past graduation!

Just some books and binders

Over my many years wasting my life with a bad drawing habit, I've learned one thing from flatbed scanners: graphite pencil marks on paper are reflective.  This means that for particular illumination angles, scanned or photographed pencil handwriting/drawings may be washed out very effectively.  Long ago, I simply abandoned scanners for drawing purposes because of this.  I decided to simply use my second-hand smartphone as a camera.  I grabbed some scrap metal from the pile next to the bandsaw, and after some sawing and hammering and hot glue, I created a tripod mount for the phone.  I set up a light tent and made a staging easel out of a pizza box.  After ten minutes of page flipping, I have a hundred pictures of upside-down pages that I can hardly read with my D-grade eyeballs. 

Rectification and contrast enhancement

Now, how to process the images?  For most purposes, processing of scanned books or handwriting can be done with a simple procedure:
  • desaturate original image
  • make a copy
  • blur the copy with a large kernel
  • blend the blurred mask with the original in a Divide mode
  • re-adjust levels as appropriate
This works well and produces a high-contrast image.  Keep in mind though why it works.  This is essentially a high-pass filter method.  Only the low spatial frequency content survives the blurring operation and is removed in the blend operation.  This removes the effects of uneven lighting or slight paper contours, but if the page content is not restricted to narrow lines, we'll run into problems. 

Excess filtering on pages with graphics

Let's say some of the pages have printed figures or tables; the removal of low-frequency content will tend to leave only edges of any solid dark regions.  In the binders that contained occasional printed graphics, I used a different method for processing printed pages.  Since most of my handwritten notes are on yellow paper, I simply processed non-yellow pages differently.  If I know there are no graphics, I can just ignore the testing routine.

The color-testing routine finds the average color of an annulus of the page so as to ignore content and page placement inaccuracy.  One convenience of this is that images that are processed with the high-pass filter method can be re-colorized if desired.  I personally don't find this to help with visual contrast, so I didn't use it.

#!/bin/bash
# process photos of coursework pages from binders
# uses slower method of contrast mask generation and overlay 

#581 1773x2283+45+543 180
#487 1758x2286+54+546 180
#488 2220x1716+321+36 270
#221 1785x2325+51+531 180
#GDn 1755x2394+24+657 180
#471 1803x2319+33+540 180
#537 1779x2286+45+552 180

pdfname="ECE537_Integrated_Photonics"
cropsize="1779x2286+45+552" #the rect parameters for cropping
rotateamt="180"    #how much to rotate after cropping

indir="originals" #this is the local directory name where the original images are
outdir="output"   #this is the local directory name where the script will shit out the processed pages
outqual=85   #percent jpeg quality
hconly=1   #always assume pages are handwritten (used when there aren't any printed graphics pages)
retint=0   #percent retint for yellow pages
retintmode="multiply"

# ###########################################################################
if [ $hconly == 1 ]; then 
 echo "high contrast mode"
else
 echo "auto contrast mode"
fi

page=1
for infile in $(ls -1 $indir/*.jpg); do
 outfile="$outdir/output-$(printf "%04d" $page).jpg"
 jpegtran -crop $cropsize -trim -copy none $infile | \
 jpegtran -rotate $rotateamt -trim -outfile temp.jpg
 
 if [ $hconly == 0 ]; then 
  # get average page color excluding border and content
  imgstring=$(convert \( temp.jpg -threshold -1 -scale 95% \) \
    \( temp.jpg -threshold 100% -scale 80% \) \
   -gravity center -compose multiply -composite - | \
   convert temp.jpg - -alpha off -gravity center -compose copy_opacity -composite -resize 1x1 txt:)
  RGB=$(echo $imgstring | sed 's/ //g' | sed 's/(/ /g' | sed 's/)/ /g' | sed 's/,/ /g' | cut -d ' ' -f 6-8)
  R=$(echo $RGB | cut -d ' ' -f 1)
  G=$(echo $RGB | cut -d ' ' -f 2)
  B=$(echo $RGB | cut -d ' ' -f 3)
  isyel=$(echo "($R+$G)/2 > $B*1.3" | bc)
  #echo $imgstring
  echo $R $G $B ">> $page is yellow? >>" $isyel
 fi

 if [ $hconly == 1 ] || [ $isyel == 1 ]; then
  # if page is yellow, do 100% contrast enhancement and partial page re-tinting 
  if [ $retint != 0 ]; then 
   convert -modulate 100,0 temp.jpg - | \
   convert - \( +clone -filter Gaussian -resize 25% -define filter:sigma=25 -resize 400% \) -compose Divide_Src -composite - | \
   convert -level 70%,100% -quality 100 - temp.jpg
   convert temp.jpg \( +clone -background "rgb($R,$G,$B)" -compose Dst -flatten \) -compose $retintmode -composite - | \
   convert temp.jpg - -compose blend -define compose:args=$retint -composite - | \
   convert -quality $outqual - $outfile
  else
   convert -modulate 100,0 temp.jpg - | \
   convert - \( +clone -filter Gaussian -resize 25% -define filter:sigma=25 -resize 400% \) -compose Divide_Src -composite - | \
   convert -level 70%,100% -quality $outqual - $outfile  
  fi
 else
  # if page is not yellow, retain most color and do a 50% contrast enhancement
  convert -modulate 100,80 temp.jpg - | \
  convert - \( +clone -filter Gaussian -resize 25% -define filter:sigma=25 -resize 400% \) -compose Divide_Src -composite - | \
  convert - temp.jpg -compose blend -define compose:args=50 -composite - | \
  convert -level 25%,100% -quality $outqual - $outfile
 fi

 #echo $infile
 page=$[$page+1]
done

rm temp.jpg
convert $outdir/*.jpg $pdfname.pdf


The blurring method entails a size reduction and expansion.  This has two purposes: First, it speeds up blurs with a large kernel (in this case, by about a factor of 3); second, it helps reduce vignetting effects that would otherwise be caused by a simple "-blur 0,100" operation.  If a simple blur is used, it would help to crop the page oversize, then trim it down after contrast enhancement or after the blur itself.

-blur 0,100 -filter Gaussian -resize 25% -define filter:sigma=25 -resize 400%
Difference between simple blur and resize+blur methods

Of course you can guess that I'd do this in bash.  This is about as ad-hoc as they come.  It's not even externally parameterized.  I was thinking about doing this with Matlab, but I decided that I'd rather pull my hair out trying to do image stacks in ImageMagick.  Tell it where the files are, how they should be checked and compressed, and the script will grind them into a pdf for you.  I highly doubt anyone would ever actually use this ugly code, but I'm posting it anyway because I have nothing else to do. Still, I'm not dumb enough to post my horrible notes in whole.

Monday, June 15, 2015

Measuring thermal resistance

In the course of all the dumb things I do with electronics, I have often been forced to ask if some on-hand adhesive would be adequate for mounting heat sinks.  Often this is a matter of ad-hoc retrofitting rather than better design practice.  An example might be putting small milled heat sinks on a Raspberry Pi or replacing a small GPU heat sink with a trashy integral fan.  Maybe I need an insulating washer for a Multwatt-15 package, and all I have is mica for a TO-220.  Will an aluminized mylar antistatic bag work well enough?

"Don't worry, this is just temporary" --me, ca. 2009

Beyond that, what about more typical design guidelines?  Figures for typical case-sink thermal resistance for a common TO-220 package vary widely.  Whose numbers should I have confidence in using -- or should I just assume the worst numbers I can find?  That hardly seems better than guessing.

Asking the internet for the thermal properties of anything other than a legitimate TIM is pretty much futile.  Even those figures listed for half of the common materials at the bottom of the market are probably questionable anyway.  Is that $0.99 white goo from ebay really 1.5 W/mK?  After stumbling on enough clickbait advertisements non-quantitative or questionable computer cooling articles or product reviews wherein heat flows are measured in minutes of videogame, I figured I might as well just do it myself.  That's not to say my efforts were all that accurate.  Consider this more as an inexpensive method in development than a set of authoritative results.


So how to measure thermal resistance of a TIM?  There are a number of ways. A smart way might be like the above image.  Say we use heated and chilled volumes of water pumped through heat exchangers.  If we can measure the inlet and outlet temperatures on the heat exchangers, as well as the volume flow rates on either side, we can quantify the heat flow that actually passes through the thermal interface.  Sure, heat is being being lost in the hoses and into the air, but so long as we know the temperature differentials and the mass flow rates (implied by volumetric flow), we can eliminate those unknowns.  This could be a static configuration, or maybe we could switch the inlet from chilled to heated and extract the thermal resistance from the transient response.


That's a really cool idea, but I don't have a bunch of flow meters and pumps and I don't feel like putting that together just to test some goo once in a while.  Certainly, there are a lot of other methods that are all documented and standardized.  It seems that in most cases though, fabrication of either heaters, sensors, or interface surfaces becomes difficult, expensive, or at least tedious.  I don't want to have to hand-finish any more surfaces than necessary. 

Let's try something that's cheaper lazier simpler.  Consider the above diagram involving an electric heater and a heat sink.  In this configuration, it's simple enough to find the input heat flow, but how can the flux through the interface be quantified if the cold side is just a heat sink and ambient losses are unknown?  My primary assumption is this: if the stray losses on the heater can be made negligible, then the input power is approximately equal to the heat flux through the TIM.  Then, for the fixture area:


Maybe that's a bit too hopefully simplistic.  Maybe we can try to come up with an approximate loss ratio by using a simulation model.  Or better yet, if we can run the heater in the absence of the heat sink, we can get a rough figure for the heater-ambient thermal resistance, i.e. the resistance of the stray loss path.  If that information were available, the resistance of the conduction path then becomes:


By the time the numbers congeal in my mind, I already have visions of an assembly method.  Before we bother getting out of the chair, let's see if any of this seems reasonable.  With a few minutes of effort in FEMM, I threw together a questionable simulation of such a fixture.  The primary flaw is the fact that I didn't model any sort of convection transfer at the solid-air boundaries.  I just set a fixed boundary temperature at the extremities of the heat sink. It'll be close enough.  There are only a few things I want to know here:
  • What is the temperature gradient like around the interface?  
  • Will sensor placement be critical? 
  • Is the flux density uniform across the interface plane?
  • What's a ballpark figure for the stray losses from the heater?
Along with the goofy boundary condition selection, the axisymmetric model often forces approximations of shapes that aren't cylinders coaxial to the z-axis.  The heater resistors are modeled as a single cylinder with a geometry that approximates the degree to which cross-bored holes will occlude the cross-sectional area of the heater bar.


These quick checks suggest that for a relatively small heater power (23W), only a modest amount of insulation should be required to keep losses quite low (1-5%), even when jacket temperatures are at ambient.  So long as attention is paid to geometry, sensor placement shouldn't be terribly critical either.  Let's cobble together some rickety bullshit!

Heater bar, resistors, thermal overload, spring, scrap aluminum
Milled CPU heat sink
Heater bar and spring guide in insulator case (nested peanut butter jars)

The assembly is fairly self-explanatory.  The heater bar is machined from aluminum; the heat sink is fabricated by modifying a CPU heat sink.  The frame is assembled from scrap aluminum.  The heater has an integral spring and the compression screw uses a stop so that pressures are repeatable.


The resistor leads are insulated with wire insulation trimmings.  The resistors are bonded to the heater bar using STARS-922 "heat sink plaster".  This is a semi-setting heat sink compound.  It congeals within a few minutes, but doesn't form a tough film like an RTV silicone would.  This makes it easier to replace parts if necessary.  At the time, I was not sure of the properties of this material, but I wanted to be able to press the resistors out if necessary.  Besides, experimentally determining unknown properties was kind of the whole point behind building the fixture, wasn't it?

WOULD YOU LOOK AT ALL THAT STUFF

Once things are together, there are a couple things we can try to test.  The generic ebay thermocouples can be characterized to eliminate any static offsets they might cause.  The heater losses can also be checked to some degree.  If the exposed face of the heater is insulated, the bar can be gradually brought up to a nominal operating temperature to find its resistance to ambient.  Combining this figure with preliminary TIM tests suggest that stray losses are well within 3%.  For a good thermal contact such as a metal-filled grease, stray losses should constitute only about 1-2% of the input power.  It's nice when simulations jive.  With thermal resistance of the loss path known, the more accurate method for calculating interface resistance can be used.

We can also try to figure out the spring constant and set the stop at a reasonable interface pressure.  Due to a mismeasurement, I ended up adjusting this in the middle of things; not everything is measured at the same pressure.  For the most part though, the differences are negligible.  As a reference, typical TO-220 mounting forces from Philips suggest a pressure range of about 80-600 kPa. I'm testing at the low end, but I'd have to use different springs and brackets to go much higher. 

I've tested a few things so far, and the results are fairly expected.  When translated to suit transistor packages, the resistance figures seem appropriate.  What's interesting (and disconcerting) is that the areal resistance (K*m^2/W) doesn't quite jive with any of the specifications for the products used.  Of course, they're generic ebay grease, so I'd sooner accept the experimental result.  The kapton tape is the film alone with its adhesive removed.  The grease used with the insulator films is the ZP brand white grease.  Permatex Ultra Grey has the highest filler content and density of any of Permatex's RTV gasket products (afaik).  The orange high-temperature product is one of the lowest-solids materials they offer. 

I could've made a table, but nnnnope
Thermal resistances when translated to common semiconductor packages

I'd like to try to work out some volumetric conductivity (W/(m*k)) figures, but I've had difficulty getting repeatable results.  I need to come up with a better method of determining or enforcing TIM film thickness.  I'm not that terribly concerned with volumetric conductivity, though.  For most electronics applications, I feel that it makes more sense to leave the otherwise unknown film thickness buried in the metric. 

I'd like to try testing a bunch of other things, but these are just the common sorts that I had on hand.  If anyone wants me to test something, let me know.  Hah! Just kidding.  I know nobody will ever read this.  In case you don't exist, here are some perishable links to the materials used:
It should be noted that some materials like the metal-filled greases and acetoxy-cure RTV silicones have electrically important properties that bear consideration.  Some day I might show my method for testing that.  I also hope to have some of the mechanical properties of the STARS-922 tested soon as well.

Saturday, June 13, 2015

The Journey Never Ends

Well, that didn't take long.  It seems I have validated my doubts about the longevity of the ballast resistors I used in my motor starter project, though that is not to say that the resistors were all that had failed.

Ahh, memories

A while after being successfully installed, the motor start ramp became noticeably shorter.  At the time, I wasn't in the mood to even guess what had gone wrong, knowing that it would eventually get worse.  Indeed, within a few days, the resistors open-circuited and left the motor to start hard after the timed delay.  Upon inspection, two of the resistor legs were opened, and the third pair was intact ... but the corresponding SSR channel was shorted.

I had mentioned building three of these SSR's to use in an undervoltage start configuration and that I had subsequently watched them get violently destroyed when a relay collision dumped the branch SCC through the nine triacs.  One of those nine triacs actually survived and was re-used in the resistor starter configuration where it eventually failed.  Although I still question my snubber design and whether these triacs are genuine, the resistor-start configuration of the relay involves much lower voltages and switch stresses.  With no real evidence in support, I'll just assume that most recent triac failure was a product of the prior severe overcurrent.

That brings us to the resistors.  I clearly had little confidence in these things from the start, but they should have only been operating at about 20-25% of their allowable short-time overload rating. Did the SSR failure overstress them?  My rough calculations say no; shunting one leg during start would only increase average power in the remaining resistors by about 30%.  That's based on the false (but convenient) assumption that doing so did not also decrease the time required to reach steady state.  The increase should be negligible in comparison to the margin.


Let's take a closer look at the resistors.  When I decided to open these up, I honestly expected to find a 3W four band metal film resistor in a silicone blob.  I was surprised to find what looked like a wirewound element of decent construction.  The wire is 26 AWG, approximately 3.9 ohms/m.  My guess at an alloy would be alloy 294, maybe.  The ceramic former, end caps and terminations are all very sturdy.  The plastic end plugs are of a hard composition and are very tight in the extrusion.  Much like my other experiences with some of these cheap components from china, it seems there isn't an overarching theme of inadequacy.  Every bit of the part seems quite appropriate and well made -- all except one bad idea or decision made with complete disregard for part functionality.  In this case, the encapsulating cement ruined what was otherwise a useful part.

Blurry attempt to capture the porosity and coarseness of the cement sand

One might expect to find a wirewound resistance element like this encapsulated in a very fine-grained alumina cement made for the purpose.  The properties of interest might be its electrical conductivity (low), its thermal conductivity (high), and its maximum operating temperature.  Contrary to the goal of increased thermal conductivity, the resistor is packed with a porous and friable cake of coarse sand.  I honestly can't tell if there was originally any binder used or if the sand had just been weakly sintered from the heat of what must have been a yellow-hot resistance wire. The remaining material serves better as an insulator than anything else.  Fetching a questionably applicable thermal conductivity for packed sand of 0.4-0.5 W/m*K, rough calculations place the element temperature near the melting point after the first second's delivered energy.  All of the resistors showed this pattern of overheating (scaling, sagging, shorting wires), suggesting that the failures of the resistors and the triac were unrelated after all. 

At this point, I'm questioning my sanity and double-checking prices on soft-start modules.  No, they're still unaffordable.  It's interesting how much time and failure is still cheaper than a motor starter.  I guess that only works when your time is worth nothing.  Working with the assumption that the part failures were merely coincidental, I figured I'd rebuild it again with parts that weren't shit.  I rebuilt the relay using actual ST BTA26-800CW triacs from Mouser, and I replaced the chassis mount ballasts with three massive 6 ohm corrugated element resistors.  These resistors are not only 300W, but they have a 1000% 5 second overload capacity.  Compared to the prior configuration, these are so ridiculously oversized, they barely get warm.  Surprisingly, I only got these because they were the cheapest option.  I did have to machine some bushings and make some brackets though.

The resistor equivalent of a bigger hammer

With a few tweaks to the relay (I added a contact state indicator and adjusted trigger currents), everything seems to be working fine again.  I have no reason to think that the new ballast will be an issue.  Hopefully everything stays working.