Saturday, October 25, 2008

Using a DC motor as a servo with PID control (part 1)


PID motor control with an Arduino from Josh Kopel on Vimeo.

MORE HERE IN PART 2

EVEN MORE HERE

I found that the newer ink jet printers often use a combination of a DC motor and an optical encoder to take the place of stepper motors for print head positioning (linear motion) and paper feed (rotary positioning). The pieces often come out (after some effort) as a whole, and they seemed like a natural to experiment with.

The motors themselves are pretty nice if you just want to make something move and control its speed, and in combination with the encoder, I thought I could use them as a free alternative to a hobby servo. I knew there had to be some information out there about using a feedback loop to position a motor, and of course there was. It turns out that the classic way of doing this is through a PID servo controller (Proportional, Integral, Derivative). At its simplest this method can be thought of as a way to use the difference between where the motor should be and where it is (error), plus the speed at which the error is changing, plus the sum of past errors to manage the speed and direction that the motor is turning.

Ok, so I have to say at this point, that I am not an engineer. I did take an engineering calc. class or two, but that was more then 25 years ago, and I never much understood it even then. So all I really have to go on is my intuition about how this is working, a few good explanations, and some example code. As always , Google is your friend. If you do have a good understanding I would welcome your comments!

The first resource I found was this exchange on the Arduino forums and then followed through to an article that really explained what was going on here at embedded.com.

After reading the embedded.com article a few times I put together some simple code, and was amazed to find that the thing worked almost perfectly the first time.
The key elements of the code look like this
int val = analogRead(potPin); // read the potentiometer value (0 - 1023)
int target = map(val, 0, 1023, 0, 3600);// set the seek to target by mapping the potentiometer range to the encoder max count
int error = encoder0Pos - target; // find the error term = current position - target
// generalized PID formula
//correction = Kp * error + Kd * (error - prevError) + kI * (sum of errors)

// calculate a motor speed for the current conditions
int motorSpeed = KP * error;
motorSpeed += KD * (error - lastError);
motorSpeed += KI * (sumError);
// set the last and sumerrors for next loop iteration
lastError = error;
sumError += error;
What is going on here is:
1. read a value from the potentiometer through an analog to digital input (0-1023)

2. map that value so that it lives in the range from 0-3600 (the count from one full rotation of the motor). We need to scale like this so we can make an apples to apples comparison with the current position reported by the optical encoder. The current position is being calculated in another function (an ISR) whenever an interrupt is generated by the optical encoder (more on what this is all about here).

3. create an error term by subtracting the value we want to go to (target) from where we are (encoder0Pos)

4. multiply the error by a constant (proportional gain) to make it large enough to effect the speed. This is the Proportional term, and gives us a simple linear speed value. Basically it says that the further we are from where we want to be, the faster we need to go to get there. The converse is true, so that we will slow down as we approach our destination. Of course, if we are going to fast to begin with, we may overshoot. Then the Proportional will switch signs (from - to + or visa versa) and we will back up towards our target. If the speed is really off then we end up zooming past many times and oscillating until we (hopefully) get to the target.

5. add the difference between the error NOW and the error from the last time around. This is a way to figure out how fast the error is changing, and is the Derivative term of the equation, and you can think of it a bit like looking into the future. If the error rate is changing fast then we are getting close to where we want to be FAST and we should think about slowing down. This helps dampen the oscillation from the position term by trying to slow us down faster if we are approaching the target too quickly. Again, we multiply the value by a constant to amplify it enough to matter.

6. lastly add in the sum of all past errors multiplied by a constant gain. This is the Integral term, and is like looking at our past performance and learning from our mistakes. The further off we were before, the bigger this value will be. If we were going too fast then it will try to slow us, if to slowly, then it speeds us up.

7. set the lastError to the current error, and add the current error to our sum.

The resulting motorSpeed value will be a signed integer. Since the Adafruit controller takes an unsigned int as its speed value I do a little more manipulation to figure out the direction and get a abs() value for the speed, but that part is all pretty easy.

As I said, it seems really simple for such a complicated process. It turns out that the geared motor from the ink jets is much easier to control that some other mechanical systems. The physics of its gears, and the performance curve of the simple DC motor mean that you can be pretty far off on your tuning and it will still end up in the right place (eventually). If we were trying to do extremely precise positioning, or make it all work really fast, or handle huge inertial loads, then it would need to be a lot more robust. I am still working on "tuning " the configuration (i.e. slowly changing the 3 constant parameters one-by-one until it works best) and I will write more about that later.

In the mean time here is the code [SORRY! It looks like the code has vanished, and I cannot find a copy. DO NOT DISPAIR! Instead go here http://www.arduino.cc/playground/Code/PIDLibrary]. Bear in mind that it is designed for use with the Adafruit controller and library. You will also most likely find that it does not work well with the constants I have chosen*. In that case you will need to do some tuning yourself. Stay tuned (hah) and I will show you how I did it.

*discerning readers of code will notice that the Kd constant is 0 meaning that this is actually a PI controller. I found that while the Derivative made the motor settle into position faster, it also injected an enormous amount of noise and jitter. This is due in part to the cheap, noisy, and non-linear potentiometer I am using. I need to do some more experimenting before I can really call it a complete PID.

Oh yeah, if you are taking apart an ink jet you may find these Optical Encoder datasheets to be valuable. These are specific to Agilent parts, but I have found they all share pretty much the same pin-outs.
http://pdf1.alldatasheet.com/datasheet-pdf/view/164530/HP/HEDS-9710.html
http://pdf1.alldatasheet.com/datasheet-pdf/view/163090/HP/HEDS-974X.html

Monday, October 20, 2008

useful bits

useful bits
useful bits,
originally uploaded by jak.
finally started tearing into the ink jet pile looking for useful parts and working on examples for the class. The first victim was a fancy HP all-in-one model. It consisted of a scanner and color printer and had sd and flash card sockets built in.It turned out to be extremely easy to tear apart. There was exactly one size of torx screw involved and only about 15 of them used. The rest is just intricate plastic snap together, which obviously means snap apart as well. I had to exercise some caution in not breaking the little tabs to make sure I would be able to reuse some of the connecting parts.

The main goals were to strip out the paper feed mechanism with its associated rotary encoding wheel and optical encoder, and get down to the linear print head driver with its position sensor/encoder strip. Along the way I also uncovered a small motor and encoder wheel in the ink waste tray, and the stepper motor for the scanner head. this last was especially nice as it came out with its gears, belt drive, and linear bearing axle in one unit. I took some not very useful pictures to document the teardown: http://www.flickr.com/photos/mrigneous/sets/72157608191419120/

I already have the paper feed motor running off the Adafruit motor shield and am working on how to connect the quadrature encoder to measure angle and direction of motion. The encoder device itself is dead simple to use as it is on its own little breakout board and only requires 4 wires +, GND, and two channels of signal (so only 2 i/o pins on the arduino). The challenge I am facing is figuring out which pins are used by the motor shield, and if they are the ones that support the interrupt(s) I need to manage the encoder. I will post more pics and code as I get that worked out. If I am successful (fingers crossed) then the same should be usable for the linear mechanism of the print head. In the end I hope to have a general purpose set up for reusing printer internals.

I also took apart an old lexmark printer and it had a very simple stepper controlled print head. The Motor shield really shines here as it took me all of five minutes to get the stripped down print head shuttling back and forth with microstepped accuracy and smoothness. I took a little video (not much plot, but there ya go).

Wednesday, September 17, 2008

get back in there

Somewhere a grindstone is spinning and my nose hurts just thinking about it.
It has been a good solid 2 months of non-stop home renovation, code sprint, client support, and acclimatization.
We finally have a working kitchen, a bedroom above ground, and a sense of where things are in the neighborhood.
I have been really enjoying the process.
I think.
Perhaps I am just numb.
In either case I am looking forward to some new developments.
I made contact with the good folks at 911 media arts center (http://www.911media.org/) and we are going to be offering an Arduino class in November. They did an introductory class a few months ago and it apparently went very well.
So my goal is to push one of my favorite agendas and get some creative re-use into the mix.
We are going to be tearing down old printers and using the guts to build our projects.
I think I will order motor shields from adafruit.com and supplement the parts kit with a few extra sensors.

Over the next few weeks I need to start testing bits and pieces of printers to get a toolkit of code/method for folks to use as a starting point.
I am especially interested in using the optical sensors that provide linear and rotational position sensing in most ink jets.
The sensor spits out a quadruature encoded signal from a very accurately ruled piece of film (either round or a long strip).
I am hoping we can use it to make some interesting feedback mechanisms.
I really can't wait to get going on it but I need to clear off a little corner of the garage.
That alone could take a while...

Friday, August 08, 2008

slowly working our way out of the basement

The flooring installer comes tomorrow.
I cannot contain my excitement.
To be able to stroll through the house without being able to see light coming up through the sub-floor... this is progress!
Drywall dust still cakes every surface, and there are long tails of romex extruding from every naked electrical box, but still it is PROGRESS.

On the plus side the basement is not so bad.
Or at least that is what we keep telling ourselves.
The weather has been fabulous.
Paying work has been falling from the sky.
Rae got a really really cool job (at a chocolate factory no less!).
And I got to present at dorkbot.

Yes, things could be much worse.

If only I could start getting the garage shop set up.
Why, life would be peachy indeed.

Tuesday, May 20, 2008

made it

It took eight nine days to drive 3,358 miles (it was not the most direct route). Nine days in the car with my beloved and all the stuff we thought we would need for the next four months. Stuffed. In. The. Car.

In the end I have to say it was a great way to get here (Seattle). A plane ride would have been way too abrupt. Given the hyper-kinetic activity of the last few months (sell house, sell cars, sell possessions, pack house, say goodbye, leave) we needed some time to adjust to all the big changes. We needed time for a few melt-downs and some transcendent vistas. We got both (with the Spam museum as an added bonus). We got to see some of our far flung friends and family. We got to talk about the future and everything else we often don't have time for. In the end, we got to Seattle. We are now ensconced in our little apartment while we unscramble our brains and figure out what needs doing when. Tomorrow the house hunting begins with the inimitable Austin Chester (real estate agent extraordinaire). I am looking forward to it.

For a few pictures I give you Rae's flickr feed. I just want to point out that I took some of those, but not any of the really good ones.

Saturday, March 15, 2008

the long road to Seattle

All my electronics tools are packed away. The work bench is taken apart. I am painting my office (last room in the house!). Two weeks left to get prepared. We list the house April first (fools!).

Then and only then will I be able to get downtown and start packing the studio.
Of all the things you can do as an accumulator, moving across the country might just be one of the most painful. There is only so much you can take with you, and the rest has to disappear. I am planning a major studio sale (stay tuned junk fans) and intend to bequeath whatever might be of use to the hacktory, but in the end I know I will have to throw some stuff out. And that my friends is just not something I want to think about right now.

The only thing that keeps me from despair is Rae's promise that Seattle will have fun junk too. I trust her. Junk happens.

Wednesday, February 20, 2008

exhaustion

Ignite Seattle was a blast!
Everyone who spoke was really good, and there were a few true standouts.
I can't wait for the video to get posted, although I dread seeing myself.

I really want to thank Brady Forrest and the good folks at O’Reilly for putting it on and giving me the chance to expound on MakePhilly.

Now about the title...
We have been in Seattle since Saturday and by the time we leave on Friday we will have:
  • seen 15 houses with our realtor
  • had (a combined) 6 job interviews (or a reasonable facsimile there of)
  • and driven untold miles looking at neighborhoods.
  • delivered 1 Ignite Seattle talk
  • visited relatives
  • caught up with friends
I need to go home and sleep for a week.
I am getting very excited about moving though!

Monday, February 18, 2008

crazy

So Rae and I are in Seattle on reconnaissance for our move this spring.
Looking at real estate, trying to do some professional networking, trying not to go insane from the expanding possibilities.

I found out last night that I landed a talk for the upcoming Ignite Seattle on Tuesday (that by the way is tomorrow). Very exciting!
My topic is "fun without function" and I am going to present the codification of our experiences with makephilly and the maker challenge. I am really looking forward to this!
It has been a while since I spoke to such a large crowd, and now is the nervous part. I know I can talk for 5 minutes, the real challenge is how to say it all in JUST 5 minutes. That and how to choose the best pictures (thanks flickr).

Friday, October 26, 2007

what is it?

I do a lot of scrounging.
Admittedly I just like taking things apart, so the motivation is not always to get useful parts.
But once you have a large junk box full of old circuit boards you just know that one of them is carrying the part you need.

Conversely, I often find myself staring at a board and wondering "what the hell is that thing?"
I have a pretty good basic knowledge of electronics, and I think I can identify the general class of a part without much help, but there are always mystery items which need some research.
I like research.
What better way to waste time then by learning something?

Along the way I have collected a few links which I use to try and figure these little mysteries out.

Here are a few:

The impressive sounding FCIM Component Identification Tool it is at least 12 years out of date, but then a lot of the things I am scrounging from are old too. The site is hard core Web 1.0, and a little hard to navigate, but they show LOTS of useful info on package types, general usage guidelines, and part numbers.

For a newer resource that includes lots of surface mount (SMD) codes try TKB-4u (The Technical Knowledge Base for You!) which lists lots of codes, and some basic info on identifying those tiny parts.

There are more lists of SMD parts at TALKING ELECTRONICS as well as useful information on op-amps, voltage regulators, opto couplers, and some basic older ICs.

For semiconductors, once you have found the part number you will also need to know how to use it, and for that you need a data sheet. Data sheets are like gold. They have the pin out, all the power specs, timing data, and often a reference circuit you can use as a starting point for your own designs. Finding a data sheet for an older part can be difficult, and many of the site which claim to have them want to charge you for them. Some time ago I discovered All Data sheets and have rarely had to look anywhere else.



Friday, September 28, 2007

blue LED POV and the Diecimila hack



the dyslexic pov device

I really wanted to make something cool with my new toys before the last make:philly meeting. I knew there was not much time, so I settled on a POV device. I figured that would be easy to show off, and would be a good way to interest people in the hacktory arduino/freeduino class. As it turned out, the hardware was the easy part. Here you see my attempts to get it to spell MAKE. Obviously I still had some work to do...

tiny blue leds

I found these great little smd leds on a junked keyboard pulled from the trash. Soldering them down with their individual current limiting resistors was a challenge. Unsoldering them from the keyboard was a nightmare! In the end I only ruined one. I really want to build a hot air rework unit.

Diecimila hack

Along the way I came across this post. Pure freakin' genius! I used an smd cap instead (because I had it and I am addicted to soldering tiny things), but other then that I can't add anything useful other then to say it works like a charm.

Sunday, September 02, 2007

Doing it the hard way



the Bare Bones "Arduino" from modern devices

I ordered 4 bare bones arduino kits from Modern Devices. But in a moment of false economy decided not to order a USB < -- > TTL cable for them. Instead I decided that I would use some of the parts from the SMD grab bag I got ages ago and make one myself. My old laptop has a serial port, so I did not have to contend with USB, and it is "old tech" so there is lots of info out there.

rs232 < -- > TTL cable schematic
Finding a suitable schematic was as easy as looking at the serial Arduino schematic and finding the rs232 input area. I rounded up all the parts, and used a peice of prototyping board designed for SMD parts from OnePas (http://www.onepasinc.com/). I also dug up a DB9 connector in a plastic box that had enough room for the tiny board I ended up with.

a magnifier is your friend
I have a desk mounted magnifier lamp (which had been in storage unused for 30 years!) and it turned out to be an absolute necessity. Soldering the parts down was surprisingly easy, but working without a design provided the usual set of challenges and opportunities for cursing.

crammed in there
In the end I got it all put together, but I simply could not get it to work. Two days of fiddling, finding mistakes, testing with the scope, trying different computers, and learning the intricacies of rs232 protocols left me no closer to a working cable. In a funk I ordered a USB cable from mouser, and almost gave up.

finished
One final investigation finally revealed the problem. DB9 connectors are number as you look at the BACK not the FRONT! Switch one wire and suddenly the thing works like a charm. One of those things you just need to know.

It is probably the most expensive cable ever built, but I am quite happy with it.

Wednesday, July 25, 2007

down the rabbit hole again

Why is it that every site requires a return to the beginning?
I am working on a new Drupal site for Rae's cousin who runs a small management consulting firm in Seattle.

It should be dead easy, right?
Just drop in a few modules, do some simple theme work, post to the host, and go get lunch.
Right.

Instead I am looking for a JQuery plugin that does dropdown menus cleanly, trying to remember if there was a reason I had not used the asset module last time around, fighting with CSS, and generally feeling unmotivated.
I suppose having a well thought out process and a set of standards would help.
Maybe next time.

Tuesday, July 17, 2007

oscilloscope

After a few months of research and obsession I bought a scope.
I was getting frustrated with the levitator and thought that having better tools would help.
No, I am lying.
measuring my abilities as an antenna

new toy.  very happy.
Really I just wanted one (and have wanted one for a very long time).
I certainly don't need to prove to anyone what a geek I am, but if I did this would be the way.
For $250 I got a 15 year old tektronixs 2246 from ebay. For those not up on their obsolete test equipment that is a 4 channel 100 mHz scope with built in multi-meter and various other measuring cusors.

With heart in mouth I waited the week it took to get here, wondering the whole time if I had thrown my money away on a door stop. Oscilloscopes are pretty complicated machines, and although I had learned that this was supposed to be a fairly rugged and reliable one, I was sure it was going to be broken. Fortunately it arrived in one piece with all functions seemingly intact.

Now I just have to figure out how to use it.

Wednesday, March 21, 2007

got my blog back!

Somewhere in the heart of the google empire lives an evil gnome whose job it is to make things as complicated as possible.
This malicious individual got hold of my blog, noticed that I had not posted in a year or so, and decided to punish me by making it impossible to log in.
Well I showed them!
After many repeated attempts to gain access with every email address and password I have ever used, and after trying, exhausting, and cursing every help channel they offer (which did not take long).
I finally had a breakthrough!
Somehow my blog had become registered under an email address that does not even exist (to my knowledge), and I only discovered it by looking at the http headers being sent when I tried to log in.

In any case it is fixed now, and I have managed to migrate to the new blogger, and although I may not post for another year, I feel much better!

Friday, May 05, 2006

many more meters

So, it may seem as if I have a lot of meters, and perhaps I do. The funny thing is that in comparison to other things I collect, I don't have that many at all. These came from our excursion to the reningers flea market last weekend. Many aisle were walked, and much haggling ensued. At the end of the day I came home with a haul which these nice finds were just a small part of. I bought minnow traps, sand sieves, light fixtures, mould forms, and beat up bocce balls. Rae claims these shouldn't really count towards the weekly big magnet quota since they don't come from the studio. I feel that since they will end up at the studio, I am justified, and am merely capturing them in transit.

In either case it was a grand weekend for collecting. After returning from the countryside we went to get food at the co-op and stopped at a tag sale near by. I asked one of the ladies about a bunch of electronics and odd industrial looking stuff, and she responded by saying "you want that stuff? Please, take it"

Don't have to tell me twice. Turns out to be old mine safety equipment. CO dosimeters, noise dosimeters, odd measuring equipment, basically a jackpot. It is in pieces all over my desk now, and I am having a blast trying to figure out how it all works.

Monday, April 24, 2006

They thought it was their kid, but it was just a fluke.

Because some jokes are just too silly to resist. Even if I am the only one who will think it is funny.

Milli and Micro the Ampere family

Two classy old weston meters I got for a song on ebay (yes you can do that through paypal).
I can't imagine what I will do with them, but if I ever figure it out I know where to find them. Or not.

In the background is my mag-lev project.
If I ever get it cleaned up perhaps I will post about that too.

Sunday, April 16, 2006

Week 2 (gear puller?)

At first I thought this was a valve spring compressor, but after closer examination I am not so sure. Perhaps a device for separating gears on a shaft?

In any case my friend Tom gifted it to me when we visited his lovely family in MI a few years ago. He had apparently saved it for me knowing that I would love it... and I do.

Forged steel about 7" by 2.5"

Sunday, April 09, 2006

where to begin

Not really fair to count this shot against the weekly goal I guess, but I wanted to show the source. This is the "studio" I rent, which serves more as a storage space these days. After a brief flurry of artistic activity a few years ago, I went back to building web sites. So the output from the studio has dropped to (almost) zero. That has not stopped me from collecting though. Slowed me down a little, but only because I only get here to deliver things once a month or so, and R sees the stuff (and gives me a hard time) if my car gets too full.

A Big Magnet

Many years ago I was a graduate student studying metalsmithing at Cranbrook. One day, one of my fellow students looked at my work area in dismay, and pronounced "It looks like there is a big magnet under there and all that shit just sticks to it."

I accumulate things.

Sometimes I make stuff out of them, but mostly not.

I think I have accumulated some really interesting stuff, and I intend to take pictures of one thing each week and post it here. I could go for a really long time at one a week, so maybe it will be more frequent, but probably not. We will see.

-jak