You are currently browsing articles tagged code.

OpenSCAD apparently doesn’t have an easy way to make an arc or wedge, or any way to do a partial rotate_extrude. This presented a problem when I started to design my Parametric Encoder Wheel, because in order for it to look nice, it would need to have lots of extruded arcs or partial rotate extrudes in order to make the holes.

Encoder Wheel, OpenSCAD Arc

Creating an Arc with OpenSCAD

Here’s how I solved the problem. Currently this will render slots up to 180 degrees around, but extending it should be pretty easy. If you’re doing a lot of these in your model, be sure to use render(), or badness will occur.

 * Excerpt from... 
 * Parametric Encoder Wheel 
 * by Alex Franke (codecreations), March 2012
 * Licenced under Creative Commons Attribution - Non-Commercial - Share Alike 3.0 

module arc( height, depth, radius, degrees ) {
	// This dies a horible death if it's not rendered here 
	// -- sucks up all memory and spins out of control 
	render() {
		difference() {
			// Outer ring
			rotate_extrude($fn = 100)
				translate([radius - height, 0, 0])
			// Cut half off
				cube ([radius+1,(radius+1)*2,depth+1]);
			// Cover the other half as necessary
				cube ([radius+1,(radius+1)*2,depth+1]);

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.

Many of the useful tools and utilities you’ll find on this site are released as what I like to call CollegeFundware, which is basically shareware with a bit of a twist.

You may use the software for a reasonable period of time for evaluation purposes. But if you like the software or if you want to keep using it after you have evaluated it, you are required to license the software by donating some amount to a college fund. Feel free to donate as much as you like, and please keep in mind that no one is “getting rich” off your donations.  Choose an application…  Text Import Wizard  Parameter Wizard  Point Import Wizard  Spline Wizard  Primitive Wizard (Saw Mill)  Dovetail Jig 

Select an application, then click Donate Now.
[utility unavailable]
Donations are handled by PayPal and are secure. You don’t need to be a PayPal member to donate.

The cost of college increases at a rate about twice that of inflation, so when these little kids end up going to college, it’ll probably cost at least US$300,000 EACH for a decent public school, and about US$500,000 for a private university. I averaged these numbers to estimate US$400,000. So if I can get 200 people a month to donate US$10 each (or 100 at US$20 each, etc) then maybe I’ll be able to afford to send them to the schools they want to attend. Big goal? Yes, I know. (Of course if you happen to be wealthy and benevolent, you’re welcome to donate the full US$400,000. =)

Copyright Notices 

The software on this site is owned by Alex Franke. All rights in the product including copyrights, licensing rights, patents, trademarks, trade secrets, design rights, engineering rights, moral rights, and any other intellectual property rights belong to Alex Franke — even movie and book rights =). These rights are not transferred to you or anyone else when a donation is made or a product is licensed or registered. No part of the product may be reproduced, published, transcribed, disassembled or reverse engineered, transmitted electronically, mechanically or otherwise, stored or translated into any language in any form, by any means, for any purpose other than your (the licensee) personal use, without the express written permission of me, Alex Franke.

Affiliations (or rather the lack there of)

I am not affiliated with Alibre, Inc. I don’t work there nor and I paid by them in any way. I am however totally sold on their design products, which I believe are about the coolest things since sliced bread (not that I remember the advent of sliced bread), and I’d encourage everyone and their mothers to look into their product offerings if they’re even slightly interested in 3D modeling.

I am not affiliated with Microsoft, Inc. I don’t work there nor and I paid by them in any way. I sure wish Bill or Steve would donate to these college funds, though. =) Yes, Microsoft is big and has created a lot of billionaires, but I think it’s a darn good company, especially since they’ve started offering free development tools.

Limitations of Liability

The software is provided as-is, and under no circumstances (including negligence) shall I (or anyone I know or love) be liable for any damages, either direct, indirect, incidental, consequential, etc. There are no warranties or any kind, express or implied, including implied warranties of merchantability and fitness for a particular purpose. You assume the entire cost of all necessary maintenance, repair or correction or any problems or defects that might be discovered in the software, while using the software, or as a result of installing or attempting to use the software.

Another Way to Register

Don’t believe that this is actually going toward the kids’ education? In you want to register in a more direct way and can afford to wait a bit longer for the registration information (so it can be entered manually), then you can choose one or more gifts from the kids’ Amazon wish lists. Be sure to include your name, email address, and the product you want to register in the gift note when you place your order.

Amazon’s affiliate program can be big business, and many web sites rely solely on Amazon affiliate program referral frees for their income. It’s a good business model for because it helps drive traffic and sales to their site, and it’s a good deal for the affiliates because they get a small piece of the pie by creating links to products that are encoded with their affiliate IDs. 

But because affiliate information can be encoded into product links, there are also a lot of people out there who try to “hijack” affiliate revenue on web sites by posting links to products that use their own affiliate tags or IDs. 

This article will describe a couple of different methods for creating product links with encoded affiliate IDs, and will introduce a tool that site owners or content publishers can use to help thwart affiliate revenue hijackers by making it very easy for users to create appropriately tagged product links.

About Amazon’s Affiliate Program

First a little background. When you click on a link encoded with someone’s affiliate tag ID, then anything you add to your cart over the next 24 hours or so, and then later purchase, will be credited to that affiliate. An affiliate usually earns about 4-7% of the total purchase price. Usually 4% on electronics, but usually about 6%+ on tools, books and other stuff. It doesn’t change the price for you, or cost you anything, and the affiliate knows nothing about you personally — just that a particular product was credited to him. If you use a link that’s encoded with a different affiliate ID within the 24 hours, then that affiliate will start getting credit.

Using an Product Link Generator

Probably the easiest way to create affiliate tag-encoded links to specific products is to use an product link generator, such at the one below or even the one on Amazon’s affiliate network (although that one doesn’t do as much). 

The benefit of this link generator is that you simply supply an affiliate tag and an ASIN (product code) and click Create. And what you get back is the complete code for a link that includes lots of pertinent information (like price, savings, an image, and rating) and that, when clicked, will give referral credit to the affiliate whose tag you specified — as a direct link, as HTML suitable for adding to a web page, or as BBCode suitable for adding to a forum post. 

Prepopulating Your Affiliate Tag for Referral Credit

If you’re a content publisher or web site owner and an affiliate, you can provide a link to this affiliate link generator to your users that will prepopulate your affiliate tag. For example, if your affiliate tag is “ccdc-20”, then simply append “?afid=ccdc-2” to the end of the URL ( and your affiliate ID will be pre-populated on the form for your users. This will make it a lot easier for your users to create detailed product links that give you referral credit.  

Generating Product Links With AWS

There are also a couple of ways to create product links in code and on the fly. The first and most reliable method is to use Amazon Web Services (AWS) to generate the product link for you. To do this, you must register not only for the affiliate program, but also as a user for AWS. When you do this, you will be issues an Access Key that must accompany each AWS request.

wsAmazon.AWSECommerceService c
     = new wsAmazon.AWSECommerceService();
wsAmazon.ItemLookupRequest req
     = new wsAmazon.ItemLookupRequest();

// The ASIN to look up
req.ItemId = new string[] { "B012345678" };

// The data to fetch
req.ResponseGroup = new string[]
     { "Offers", "Images", "ItemAttributes", "Reviews" };

wsAmazon.ItemLookup lu = new wsAmazon.ItemLookup();
lu.AssociateTag = "My Associate Tag";
lu.AWSAccessKeyId = "My Access Key";
lu.Request = new wsAmazon.ItemLookupRequest[1] { req };

wsAmazon.ItemLookupResponse resp = c.ItemLookup(lu);

wsAmazon.Items[] items = resp.Items;
wsAmazon.Item MyItem = items[0].Item[0];

Creating Product Links On the Fly

If you don’t want to have to deal with setting up an AWS account and programming your way through the AWS specification, there is another still effective (but less reliable) way to create the product links. As of October 9, 2006, the following is currently the best (and safest) way to generate an Amazon affiliate link on the fly (by hand), according to the Web Services team at They say, “Associates who wish to manually construct URLs do so at their own risk.” But this method does allow Amazon associates to “get data in their reports about the number of times their visitors click through to [the given product] (which is necessary for qualifying for certain compensation premiums that are offered in some of our international locales.”

To use this method, start with the following string and insert the ASIN (Amazon product number) and the affiliate tag or ID you wish to receive credit for the referral.[Product ID]/?tag=[Affiliate Tag]&linkCode=asn&creativeASIN=[Product ID]

Replace “[Product ID]” with the Amazon product ID or ASIN, and replace “[Affiliate Tag]”with the affiliate tag you wish to receive referral credit.

This makes a great gift, t-shirt, mug, etc. for any computer or math geek, friend, child or baby! Write you name or message in up to 100,000 of the infinitely non-repeating digits of pi. Originally published: Mar 21, 2006.


This makes a great gift, t-shirt, mug, etc. for any computer or math geek, friend, child or baby! Write you name or message in up to 100,000 of the infinitely non-repeating digits of pi. PiShop is a free online application that allows you to generate customized image to use as a t-shirt transfer, banner, or whatever else you want to use it for. It’s free for personal use, but if you like it, I encourage you to make a little donation for my kids’ college funds! =) 

What You’ll Need

For t-shirts, onesies, bibs, and other garments:

  • Printable iron-on transfers
  • A onesie, hat, bodysuit, or other garment to receive the transfer
  • A printer to print the transfer (suggestion below)
  • The image to print (create it below)

Writing with Pi

Simply fill out the short form below and put a check mark in the box by “Mirror Image” if you want the image to be reversed for transfer paper. (Many printers do this automatically when you indicate that you’re printing on transfer paper.)

Type in your name or message; select a font, size and color.

Next click “Make Image.” The page will refresh, and the image will appear (sized to fit) below the Make Transfer button. You can save the full size version of the image by simply right-clicking on the thumbnail, then selecting “Save Picture As…” or “Save Image As…”A note about privacyI don’t keep (or even see) any of this information. It’s sent directly to a computer program that generates a transfer image and then immediately discards the data once the image is sent to you.

Making the Shirt

Depending upon the size of the shirt, onesie, hat, bib, sweater or other garment you want to make, you may need to resize the image using a word processing or photo editing program before you print it to the transfer paper. Once you get the size about right, print out a test page to make sure it will fit the garment.

Need a good printer? I use a Canon Pixma iP6600D photo printer shown below, and I’m continually astounded by the superb prints I get — all the way up to 8×10, which cost a fortune if you buy them online or at the photo store. Plus it’s quite fast and it prints of both sides of the paper, so it basically use it to print everything. (Use the “Pro” paper for photos you won’t regret it!)After you’ve printed your test page on cheap paper, load in the expensive stuff (the iron-on transfer paper) and stqart printing. Once it’s printed, I typically like to cut around the image and cut out large sections of unprinted transfer. This tends to make the final product look a little cleaner and more professional.

The transfer paper should come with instructions on how best to transfer the image from the paper to the garment.

Licensing & Registration

This application is Copyright (c) 2006-2008 by Alex Franke, and it offered as what I like to call CollegeFundware. This means you’re free to try it out for a reasonable period of time, but if you like it and want to keep using it, you need to contribute to my kids’ college funds =).

Visit the Software Registration page on this site for details on how to legally use this software after a reasonable evaluation period. Important: By downloading and/or running this software, you agree to the terms and conditions set forth on the the Software Registration page page. (It’s not that bad, really =)

When you register the product by contributing, any limitations the software may have will be removed, including registration reminder pop-ups windows. Registration may also “unlock” special features not available to unregistered users.

It’s always difficult to suggest a donation amount for registration. I recommend considering the value of the time you save by using the tool, and contribute an amount you feel is reasonable and appropriate. Below is a general guideline that may also help you decide.

  • $15-20 for private, personal use (e.g. hobbyist)
  • $20-50 for individual professional use (e.g. contractor)
  • $50+ if your company is writing the check

This is how I chose to solve the problem of making trig calculations with the PICmicro MCU.

Note that this does not use the CORDIC method because I imagine that would hog too much valuable computing time. This solution probably should not be used to try to get someone to Mars or anything — I’ll work on a more complete solution at a later date. Until then, I hope this will do.

First of all, I attacked this problem with a few basic assumptions:

  • 256-degree circle – It makes sense, when using a computer, to base everything on powers of two. Here I’m going to consider circle in terms of only 256 degrees. This is because 256 can be represented nicely by one byte and it’s close enough to 360 degrees that results shouldn’t be too far off base. Also, common angles can be easily represented as well, with a half-circle, quarter, eighth, sixteenth, etc, all settling nicely at a power of two. If it’s difficult to think of a circle in 256 degrees, just remember that the number 360 was completely arbitrary in the first place. (You can thank the ancient Babylonians for it, as well as for the number of minutes in an hour and seconds in a minute. They used a base-60 counting system.)
  • Unsigned magnitude, zero to 255 – Sines and cosines are usually represented by fractions. Since computers can’t tolerate fractions very easily, I chose to return results as a positive number from zero to 255, where zero is, well, zero, and 255 represents 1. Why only positive numbers? Because when you take the sine of an angle in a 256-degree circle, the most significant bit of the angle you’re looking for will quickly tell you if the result should be positive or negative. This is because quadrants 3 and 4 (angles 128-255) generate negative sine values. (As it turns out, the MSB for all these numbers is 1.) This allows me to use the full byte for sine values, effectively doubling the granularity of the result. 
  • One-quadrant sine-only look-up table – The sine values for any one quadrant can be used to determine any of the other trig values for any other quadrant. I’ll provide a refresher on trigonometric identities below. Suffice it to say that one quadrant of sine values is all we need.
  • Non-CORDIC Solution – CORDIC would take too long to implement with a negligable increase in accuracy for typical applications. This solution is a look-up table that essentially digitizes the first quadrant of a sine wave as shown below.

The code listed below was written for mid-range PIC MPU’s like the 16f84, but can be ported down with a few minor changes. (For example, you may need to use comf and incf to negate values in the lower-end divices.) It finds the unsigned sine of an angle in eight instruction cycles (32 clock cycles), or 8us on a 4MHz microprocessor. With a few extra instructions (about 13 total) you can determine the sign as well as the magnitude. Determining the not-as-accurate signed sine requires 17 instruction cycles and returns a value ranging from -127 to 127. It takes about 15 cycles to determine the 8-bit cosine magnitude and discover its sign, while the signed cosine requires 18 instruction cycles. If you see a more efficient way of doing this, please let me know. Because instruction cycles vary, I don’t recommend using this for bit-banging routines where timing is critical. Maybe later I’ll do a version that takes the same number of cycles regardless of what function its performing.Before you forget, please help spread the word about this site by referring friends and associates!

The sinw subroutine does not call any other routines. This should be helpful if you’re working with a device that has a short call stack. If I were to return a signed value for the sine, I would have needed to make an additional call on the stack. I believe the way I’ve done it works out nicer. As it is, only ten or so instructions are required to determine both the sine of the angle and it’s sign (positive or negative).

The code below is well commented and includes examples of how to compute both sine and cosine (signed and unsigned) using the sine look-up table. Also, in the comments I’ve listed all the other trig equations I can think of — you can use these to figure out tangents, cosecants, etc.

It might be helpful to remember when sines and cosines are positive or negative. In our 256-degree circle, each quadrant is represented by 64 degrees. So Q1 is angles 0-63, Q2 is 64-127, etc.

  • Q1 (0-63 deg) – Sine and cosine are both positive. Bits 6 and 7 are both clear.
  • Q2 (64-127 deg) – Sine is positive, cosine is negative. Bit 6 is set and 7 is clear.
  • Q3 (128-191 deg) – Sine and cosine are both negative. Bit 6 is clear and 7 is set.
  • Q4 (192-255 deg) – Sine is negative, cosine is positive. Bits 6 and 7 are both set.

Bit seven (the MSB) of the 8-bit angle indicates if the sine is positive or negative (zero or one, respectively).  Bit six indicates whether or not the sine wave is a mirror image of the preceeding quadrant. (Q2 is a mirror image of Q1 and Q4 is a mirror image of Q3.) This bit can therefor be used to indicate whether or not we need to read from the start or the end of the look-up table. The following rules always apply:

  • If bit 7 (MSB) is set, the angle is in Q3 or Q4, where sine is always negative.
  • If bit 7 (MSB) is clear, the angle is in Q1 or Q2, where sine is always positive.
  • If bit 6 is set, the angle is in Q2 or Q4, which are mirror-images of Q1 and Q3, so read the table backwards.
  • If bit 6 is clear, the angle is in Q1 or Q3, which can be read directly from the look-up table.

We only use the table to look up a sine value. Rather than trying to use the table to also look up a cosine, figure out what angle’s sine returns the same value and go to the table for that. This will ensure you can determine the correct sign (positive or negative) of the magnitude returned. To really drive this point home, let’s take a look at each case for the two most significant bits in an 8-bit unsigned angle:

  • 00 – Angle is in Q1, the sine is positive, and it can be looked up directly from the table
  • 01 – Angle is in Q2, the sine is positive, and it can be looked up by indexing the table backwards
  • 10 – Angle is in Q3, the sine is negative, and it can be looked up directly from the table
  • 11 – Angle is in Q4, the sine is negative, and it can be looked up by indexing the table backwards

Skip this paragraph if you’re not a beginner. Why does rolling (shifting) bits to the left or right magically double or halve whatever number your shifting? It works in a similar way for any counting system — just think about the numbers you’re used to using. If you “shift” the digits in the decimal number 123 to the left you get 1230 — effectively multiplying the original number by ten, which is the base of the decimal counting system. Likewise, shifting the hexadecimal value F3 to the left you get F30. F3 in decimal notation is 243. 243 times 16 (the base of hex) is 3,888, which in hexadecimal is F30.

Feel free to use this code, but be sure to leave the copyright information intact.

#define _version "0.01"

; Author: 		Alex Franke
; Copyright: 		(c)2002 by Alex Franke. All rights reserved. 
; Title: 		sin
; Description: 		Computes the sine of an angle given in degrees of a 
;			256-degree circle.
; Device: 		Microchip PIC MCU, p16f84
;			or other mid-range PIC MCU's
; Update History:	6/11/02	Created


; Registers
 CBLOCK	0x020
sinTemp, theta, temp, temp2


; Main

 org 0


  ; Set up
  movlw		84		; specify an angle value
  nop				; pause here to change value if desired for testing
  movwf		theta		; save that angle for use later

  ; now start the examples...
  ; Assume the angle you're trying to find is in theta and you want to find...
  ; ...its sine (0 to 255) and its sign (positive or negative)
  movf		theta, w	; copy to w so we can work with it
  call		sinw		; we now have the sine in w
  btfsc		theta, 7	; test the original angle to see if it's in Q3 or Q4
    nop				; ... if so, we know it's a negative, so handle that here

  ; ...its sine (-127 to 127)
  movf		theta, w	; copy to w so we can work with it
  call		sinw		; we now have the sine in w
  movwf		temp		; store result in temp register
  bcf		STATUS, C	; clear the carry bit if it's set -- we're about to roll
  rrf		temp, w		; roll temp result right to cut in half, store in w
  btfsc		theta, 7	; test the original angle to see if it's in Q3 or Q4
   sublw 	0		; is, so negate w 
  nop				; sine (-127 to 127) is now in w

  ; ...its cosine (0 to 255) and its sign (positive or negative)
  ; A cosine is basically a sine, but shifted to the left one quadrant. This means
  ; that a sine is a cosine shifted to the right. So the cosine of any angle is 
  ; equal to the sine at the same position one quadrant to the right, or 
  ; cos(x)=sin(90+x). So to convert to sine we add 90 deg (64 degrees in our 256-deg circle)
  ; to the original angle.  
  movf		theta, w	; copy to w so we can work with it
  addlw		64		; add pi/2 so we can just take the sine
  movwf		temp		; move new angle to temp because we test this later
  call		sinw		; we now have the sine in w
  btfsc		temp, 7		; test the original angle to see if it's in Q3 or Q4
    nop				; ... if so, we know it's a negative, so handle that here

  ; ...its cosine (-127 to 127)
  movf		theta, w	; copy to w so we can work with it
  addlw		64		; convert cos to sin
  movwf		temp2		; store in temp2 register so we can compare for negative
  call		sinw		; we now have the sine in w
  movwf		temp		; store result in temp register
  bcf		STATUS, C	; clear the carry bit if it's set -- we're about to roll
  rrf		temp, w		; roll temp result right to cut in half, store in w
  btfsc		temp2, 7	; test the original angle to see if it's in Q3 or Q4
   sublw 	0		; is, so negate w 
  nop				; sine (-127 to 127) is now in w

  ; ...its tangent, cotangent, secant, cosecant, etc
  ; Rather than going into a dissertation on how computers divide numbers, 
  ; let me just recommend using a good divide macro and any of the following 
  ; equations... 
  ;   tan( x ) = sin( x ) / cos( x )
  ;   cot( x ) = 1 / tan( x )		= cos( x ) / sin( x )
  ;   csc( x ) = 1 / sin( x )
  ;   sec( x ) = 1 / cos( x )
  ; These Pythagorean identities may also be useful
  ;   sin^2( x ) + cos^2( x ) = 1
  ;   sec^2( x ) = 1 + tan^2( x )
  ;   csc^2( x ) = 1 + cot^2( x )
  ; These will help with adding and subtracting
  ;   sin( x + y ) = ( sin( x ) * cos( y ) ) + ( cos( x ) * sin( y ) )
  ;   sin( x - y ) = ( sin( x ) * cos( y ) ) - ( cos( x ) * sin( y ) )
  ;   cos( x + y ) = ( cos( x ) * cos( y ) ) - ( sin( x ) * sin( y ) )
  ;   cos( x - y ) = ( cos( x ) * cos( y ) ) + ( sin( x ) * sin( y ) )
  ;   tan( x + y ) = ( tan( x ) + tan( y ) ) / ( 1 - ( tan( x ) * tan( y ) ) )
  ;   tan( x - y ) = ( tan( x ) - tan( y ) ) / ( 1 + ( tan( x ) * tan( y ) ) )
  ; And for doubled angles...
  ;   sin( 2x ) = 2 * sin( x ) * cos( x )
  ;   cos( 2x ) = cos^2( x ) - sin^2( x ) = ( 2 * cos^2( x ) ) - 1 = 1 - ( 2 * sin^2( x ) )
  ;   tan( 2x ) = ( 2 * tan( x ) ) / ( 1 - tan^2( x ) )
  ; And as we've used above... What's a cosine? It's on of several cofunctions:
  ;   sin( 90 deg - x ) = cos( x )	cos ( x - 90 deg ) = sin( x )
  ;   sec( 90 deg - x ) = csc( x )	csc ( x - 90 deg ) = sec( x )
  ;   tan( 90 deg - x ) = cot( x )	cot ( x - 90 deg ) = tan( x )
  ; And finally... What's an arcsine, arccosecant, arccosine, arcsecant, arctangent, 
  ; and arccotangent? They're simply the inverses...
  ;   arcsin ( sin(x) ) = x		arccos ( cos(x) ) = x
  ;   arcsec ( sec(x) ) = x		arccsc ( csc(x) ) = x
  ;   arctan ( tan(x) ) = x		arccot ( cot(x) ) = x

  goto 	Start

  goto $

; If bit 7 is clear, we're in quadrant 1 or 3
; If bit 8 is clear, we're in quadrant 1 or 2
;		bit 8 	bit 7
; Quadrant 1	  0	  0	read from begining of table
; Quadrant 2	  0	  1   	read from end of table
; Quadrant 3   	  1	  0	read from begining of table and negate
; Quadrant 4	  1	  1	read from end of table and negate
; Angles in quadrants 3 and 4 result in negative sines. Because returning
; a negative value from this subroutine would require an additional entry
; on the call stack (a call to the sine table to get the value before 
; negating it), we'll just leave it up to the user to negate the result
; if necessary. This saves us an additional call. 
; This table returns a value sclaed 0 to 255

  movwf		sinTemp		; Move input to temp variable to test it
  andlw		0x03F		; Clear the first two bits of input - number needs to be <= 64
  btfsc 	sinTemp, 6	; read from the begining or the end of the table?
   sublw	64		; from end, so w = TableSize - Input
  addwf		PCL, f		; Position program counter to appropriate result
  dt 	  0,   6,  13,  19,  25,  31,  37,  44
  dt	 50,  56,  62,  68,  74,  80,  86,  92
  dt	 98, 103, 109, 115, 120, 126, 131, 136
  dt	142, 147, 152, 157, 162, 167, 171, 176
  dt 	180, 185, 189, 193, 197, 201, 205, 208
  dt	212, 215, 219, 222, 225, 228, 231, 233
  dt	236, 238, 240, 242, 244, 246, 247, 249
  dt	250, 251, 252, 253, 254, 254, 255, 255, 255