Design Automation Techniques (session 2) with SolidWorks 2009 and 2010, Excel and VBA - Presented to Greenville (SC) SolidWorks User Group September 15, 2009 @ CU-ICAR
First of all, are you in the right place? We’re here to talk about design automation with SolidWorks. So whether you use a commercially available Solution Partner product like this…
Or like this…
Or maybe you’re using one of these…and if you’re not, feel free to check them out in the partner pavilion. I hear that they have lots of free stuff. Maybe they’ll even raffle off one of the people from their booth.
Or maybe you run your automation from in here…
Or maybe you do it right inside here…
Or maybe you’re hardcore and you use this…Or maybe you don’t even know what this is…
Either way folks, I am here to tell you that you have come to the right place.
This is what we’re really talking about. We know how to design with SolidWorks and to use it as an interactive tool to build strong designs, but I do want to stress here that this session is listed in the DESIGN AUTOMATION technical track, and we are concerned about how to use SolidWorks in the context of a design automation. This is important because the folks at SolidWorks spend countless hours, days, months, (years even!) developing better and faster ways for you to interact with SolidWorks. With automation, you want to try to make it so that people DON’T interact with SolidWorks. So there are some tricks to it, and that’s why you’re here…I hope.
So what I’m really saying is that when it comes to calculations, SolidWorks is just faster than I am. My general rule of thumb is “Thinking…bad. SolidWorks…good.” I’m not saying that an engineering education is a waste of time. I mean my years trapped in New Jersey were actually quite valuable. Where else would I have learned such invaluable skills as:
The social and personal importance of competitive sports, alternative uses for common household items (I think this is how MacGyver started), the importance of nutrition and the availability of over-the-counter productivity products, and cooking techniques that would make Rachel Ray curl up in the fetal position. It’s not that when I’m designing an automation, I don’t need to think. That’s what I get hired for. People certainly don’t pay me for my good looks…[Don’t laugh at that/Thank you for not laughing at that.] There are some times when it’s just not worth racking your brain when SolidWorks can do it so much faster and easier.
When people do engineering process automations, they’re primarily looking for one of a few things. Most often they want to drive SolidWorks to get drawings or models for production, sales, approvals, what have you. Oftentimes, they’re looking to guide people through the process to guarantee that they don’t specify (or sell) something that just won’t work or cannot be manufactured. That’s typically done by simply limiting their choices to combinations that you know work or provide limits to work within. Sometimes, people use the automation to actually capture engineering knowledge and have the system apply it to determine the feasibility or performance of a design. In these cases, the automation system is taking the questions that would typically be asked of Engineering, “What’s going to be the output torque at the shaft for these inputs?”, “How much is this thing going to weigh?” or to get costing and therefore pricing. This frees up Engineering to get back to what we do best, very creative rubber band fights, switching the regular and decaf in the executive coffee machine, making snide comments about the sales and marketing folks. Oh yeah, and designing new products.So in these three areas, we can have some math to do. And in some cases, that’s pretty easy. “How big is that? OK, length times width divided by a full sheet gives you the sheet usage percentage times the material cost and there you have it.” But in other cases, we can get geometry that’s tough or laborious for us to generate repetitively, even with SolidWorks. Sometimes, determining form, fit and function require a bit of SolidWorks knowhow. And calculations can often involve complicated components like moments of inertia, clearance distances, or weights that are tough of figure out.
Here are some of the types of applications where you might want to utilize SolidWorks for calculation purposes inside of an automation. And we’ll go ahead and look at these further.
So the first type of examples for where we can leverage SolidWorks in an automation is when we have complex geometry or geometric systems that need to be solved. SolidWorks does these very quickly and efficiently. Quite often, in my implementations, we simply drive a sketch in SolidWorks to get our answer. In many cases, like a linkage, or a truss, there’s no reason to even build solid geometry. In these cases, we drive the geometry of the system and in return, we get back something that we were missing about that geometry. Whether it’s the travel of the damper in the bike linkage for a given frame geometry or the total length of the serpentine belt, we want to talk about how to give SolidWorks what we know and get out what we need to know.
Manufacturability is coming up more and more as people realize that they can do this up front. DFM has been around for years, but how often in the quoting process do you consider which machine you’re going to run a part on or what the standard stock sizes are? DFA teaches us to look for tool clearances and ensure that the design is shop friendly, but can we really do that right up front? Absolutely. If we can look at it to make that determination, SolidWorks should be able to look at it for us and let us know.
Here’s another one that I just would not want to figure out long hand. How far apart are these two features/faces/bodies. Do they interfere? If so, then I need to know now, so I can tell the user it can’t be built before some salesperson runs off and sells it. I have clients that design by putting these two parts between this far and that far from each other. How do you do that in SolidWorks? You either place it in the assembly, leave it under-defined, and drag it with a clearance check, or you sit there and slide the sliders in the modify boxes until you get a solution that works. The problem is that you just can’t drag in an automation. So we’ll look at the use of iterative solving with SolidWorks.
This goes along with complex geometric problems. You can use a combination of automation power and intelligence and some of the tools like equations and relations in SolidWorks to solve problems that would be otherwise next to impossible.
Validation is the primary role of Engineering in the presales process. When sales is selling a product, they don’t need us to design it. They just want to be able to say, “Well, Rachel said the design was fine.” We, on the flip side, want to avoid the inevitable problems that we’ll have to solve, figuring out how to shove 48 cubic yards of manure into an Altoids box. By automating this and bringing it up front, we identify the problem areas immediately and either eliminate bad designs, or get REAL engineering intervention to solve custom problems into the process much earlier. But this isn’t confined to problems. People also need or want to know predicted performance for a system before it’s even designed. Cervelo P4 Time Trial/Triathlon bike. It needs to be light. How light, 6.8 Kilograms. That’s the minimum weight for a Tour de France bike. Yes, I said minimum. So they have a target. But they also need to reduce frontal area and drag and they also need to maximize stiffness. If they know the rules, they can let SolidWorks figure out the what the performance characteristics are going to be before they build my custom frame.
TDAM has always been one of the selling points of SolidWorks and when it comes to automation, we love it too. How big of a box DO you need for 48 yards of mulch? What’s it really going look like when those parts intersect? Why bother figuring out where the same hole goes twice, just because it’s on two different parts. Again, we’re interested in making it non-interactive, so that we can let our programs do the talking, but there is still a lot of TDAM that we can leverage.
OK, let’s see how to do all of this. One disclaimer…All of the code (and yes, it’s available for your reading pleasure) will be made available at the end of the presentation (call it my insurance that you’ll stay) and it is all in Excel VBA. Why VBA? It seems to be the most pervasive way to code. Just about everyone has Excel. Plus, if you can code in C#.NET, then reading the VBA will be a piece of cake for you. Plus, I’m not a real code monkey. I’m a mechE.
Second disclaimer: You’re not going to see all of the code in this presentation and I’m not going to break it all down for you. I’m here to talk about applying fairly high-level concepts. I will show you details on some sticking points, but if you want to learn syntax, you can also go to see Jerry Winters do his sessions and check out the API Help file in SolidWorks. One problem here is that I just got done telling you how I’m using Excel VBA, which is essentially VB6, for this presentation and the help file in SolidWorks 2009 has been completely revamped to discourage you from using VB6. It is almost exclusively focused on .NET syntax with VB6 as a bit of a footnote. All of the VB6 examples, however, are still in there, but the syntax and descriptions are a lot less helpful. If you know anyone at your company that still has a SolidWorks 2008 installation, I would recommend that you steal the API directory in there and archive it. You can run the CHM file right from Windows Explorer and it’s a lot more VBA friendly.
And disclaimer #3. You’re not going to see me do any coding live. I’ve been to every SolidWorks World. And I have yet to see a session where the presenter codes live and it works. They waste a ton of time looking for where they types “END OF” instead of “END IF” and then the code still doesn’t work and there’s that awkward time when you’re thinking “Just give up and move on.” Then there’s the SolidWorks crashes. Well my code isn’t going to crash. You can bet on it. This is pure PowerPoint. And I KNOW that excites you. OK, now on with the show.
So here is our first example. Southern States Superior Spring and Scissor Lift Systems manufactures custom designed lift systems for companies all over the world. The client provides the application information including the size and weight of the load, the starting and ending heights and whether they’re going to pay with cash or credit card, and the Southern States Superior Spring and Scissor Lift sales specialists specify safe systems to satisfy specific situations. Internally, engineering needs two things. First, they need good, complete information for systems that can actually be manufactured. Secondly, they need to determine the linkage lengths so that they can determine linkage and pin sizes to avoid shearing and other modes of catastrophic failure. And by catastrophic, I mean catastrophic to the engineer’s career. So how do you approach such a situation?
Well, this is how we do it. And incidentally, this is how we do every design automation involving SolidWorks. It’s a fairly simple process of collecting your inputs, passing them to SolidWorks, retrieving info back from SolidWorks and continuing along your way. Let’s look at it in a bit more detail.
First we collect the inputs. Again, this is one place where Excel shines. If you’re using a commercially available solution partner, then that will be the vehicle for creating your user interface. If you are NOT using a solution partner product, I wholeheartedly encourage you to go speak to them in the partner pavilion. I believe that most of them are there and the word on the street is that they’re giving away lots of free stuff and I think one of them is raffling off one of their employees. So that may or may not be worth something. But definitely hear them out, they are generally a lot faster than doing it in pure code and a lot more maintainable.If you DO want to do it in Excel, however, please go to www.razorleaf.com, click on the presentations link and download the presentation from last year on doing automation in Excel. There’s lots of good information in there and it’s reasonably priced. OK, fine. It’s free. And for the moment, I don’t even think we ask for your name. So we’re trying to educate the community, not build our marketing list.Lots of good info in that session that I will NOT go over, but the one thing that I WILL stress is that you should always name your cells. If you do, your Excel formulae will be much more readable and your code will as well. If you don’t know how to do it, just click here and type away. You can also go to Insert->Name in older versions of Excel. In Excel 2007, it’s called the Name Manager and it’s on the Formulas ribbon.
Once you have your input data, or even as you’re collecting it, you can do some calculations. Anything arithmetic or logical that your brain can handle, do it here. The primary benefit is that it will generally get calculated live and can provide instant feedback that can validate the inputs and prevent users from entering in bad numbers. And even if they cannot be done live, this portion of code should be the area that converts units and otherwise processes the values to be SolidWorks-ready.
Before sending values to SolidWorks we need to invoke its holy name. At this point, we start working with what can almost be called object-oriented programming. I say almost because if there are any .NET programmers here, they would come up afterwards and lecture me for a full hour about how VB6 does not fully implement polymorphic instantiation of friend classes or something like that. But the point is that we’re dealing with objects here. For a primer on Object Oriented Programming to the extent that Excel handles it, check out the aforementioned presentation on the Razorleaf web site.Now connecting to SolidWorks is fairly easy, and in fact there are several ways to do it. I’ll only show you one because it’s the best and I don’t want you to call me to help you troubleshoot code that you wrote using the others. Again, we’re dealing with object here, so the first thing that we need to do is to link to the SolidWorks Object Definitions (which are called classes) and they live in the SolidWorks Type Library. So grab them from TOOLS->REFERENCES in your Visual Basic for Applications environment. If you’re working in .NET, you still need to grab references, but they are the newest SolidWorks Interops. The one that you will need is the SolidWorks.Interop.SldWorks Namespace. And you’re going to want to throw a letter I in front of all of the classes to get your interfaces. VBA folks, you will also want to grab the SolidWorks Constant Library as well. That will make your life easier.Once you have your references, you need to create an object to hold the SolidWorks application and dim it as SldWorks.SldWorks. Not as OBJECT. Not as Variant. Put that Option Explicit up there and make sure that you fully qualify everything. To instantiate your application, you use the Windows CreateObject function. CreateObject is cool because it will start SolidWorks only if it’s not already open. If it is open, it will latch onto the open process. Once you have the SolidWorks application object, you need the second component, which is the SolidWorks ModelDoc2 object. You have some functionality within the application, like the ability to open a file, but the majority of the functionality lies in the ModelDoc2 object and its children.
Before sending values to SolidWorks we need to invoke its holy name. At this point, we start working with what can almost be called object-oriented programming. I say almost because if there are any .NET programmers here, they would come up afterwards and lecture me for a full hour about how VB6 does not fully implement polymorphic instantiation of friend classes or something like that. But the point is that we’re dealing with objects here. For a primer on Object Oriented Programming to the extent that Excel handles it, check out the aforementioned presentation on the Razorleaf web site.Now connecting to SolidWorks is fairly easy, and in fact there are several ways to do it. I’ll only show you one because it’s the best and I don’t want you to call me to help you troubleshoot code that you wrote using the others. Again, we’re dealing with object here, so the first thing that we need to do is to link to the SolidWorks Object Definitions (which are called classes) and they live in the SolidWorks Type Library. So grab them from TOOLS->REFERENCES in your Visual Basic for Applications environment. If you’re working in .NET, you still need to grab references, but they are the newest SolidWorks Interops. The one that you will need is the SolidWorks.Interop.SldWorks Namespace. And you’re going to want to throw a letter I in front of all of the classes to get your interfaces. VBA folks, you will also want to grab the SolidWorks Constant Library as well. That will make your life easier.Once you have your references, you need to create an object to hold the SolidWorks application and dim it as SldWorks.SldWorks. Not as OBJECT. Not as Variant. Put that Option Explicit up there and make sure that you fully qualify everything. To instantiate your application, you use the Windows CreateObject function. CreateObject is cool because it will start SolidWorks only if it’s not already open. If it is open, it will latch onto the open process. Once you have the SolidWorks application object, you need the second component, which is the SolidWorks ModelDoc2 object. You have some functionality within the application, like the ability to open a file, but the majority of the functionality lies in the ModelDoc2 object and its children.
A quick plea for you here to please, please use good style when you’re programming. Comments will make your life infinitely easier when troubleshooting and debugging and will make it easier for those after you to maintain the code so they won’t call you when you’re on vacation or in the middle of an important presentation. Anticipate what bonehead issues your users will cause and what could possibly go wrong with your interactions with SolidWorks. When it comes to automation, SolidWorks is not all that forgiving. So test what’s going in and what’s going out to make sure that it’s what it’s supposed to be. Avoid those division by zero and type mismatch problems. Data types are especially critical with Excel because it likes to decide what data type things should be. And to simplify debugging, you can use a debug library (I’m sure there are some available on Google) or use the DEBUG tools within VBA to help log what’s going on.
OK, so once we have, with good style, a SolidWorks app and a SolidWorks ModelDoc2 object, then we can start passing information to SolidWorks. Another disclaimer here…in the interest of being able to fit things on the slides, I did NOT put any error trapping or testing in here. You definitely want to test your SolidWorks application object to make sure that it’s there. Check your ModelDoc2 object to make sure that it exists, and check your ModelDoc2 object to make sure that it is the correct type. ModelDoc2 supports parts, assemblies and drawings.To drive parameter values in SolidWorks, the syntax is quite simple. Your ModelDoc2 object has a Parameter property and you just assign a value to it. Since that property includes the name of the parameter, it’s very important to name your SolidWorks dimensions and features within the model. It’s also important not to CHANGE those names once your code is written. The same goes with your Excel. You can see that we’re using the syntax RANGE(“cellname”).VALUE. Simply naming the cell makes life sooooo much easier…no sheetnames no column numbers, no activating anything.Another thing to remember is that the SolidWorks API works in meters, and so must you. You can do that by easily multiplying or dividing by a factor. I, personally, think that’s very sloppy. I don’t like numbers in my equations unless they’re absolutely necessary. A better option is to build a quick function that converts inches into meters. One input and one output. If you want to go one step further, you can make the units in the UI in-cell pulldowns and then create a single function where you pass the value, the original units and the target units. It’s only going to be a couple of lines of code, but it will be very useful.You may also want to take advantage of some of the SolidWorks functionality to make this process easier. If you have five dimensions that are always going to be the same value, use a LINK VALUES, then drive one. Geometric relations like symmetry and midpoints are great ways to reduce your inputs. You can also use SolidWorks equations, but I greatly prefer link values over equations for equalities and I tend to put equations inside the automation. If there is a possibility that you may need to output or use the ending value in another calculation, put the equation in the automation.
OK, so once we have, with good style, a SolidWorks app and a SolidWorks ModelDoc2 object, then we can start passing information to SolidWorks. Another disclaimer here…in the interest of being able to fit things on the slides, I did NOT put any error trapping or testing in here. You definitely want to test your SolidWorks application object to make sure that it’s there. Check your ModelDoc2 object to make sure that it exists, and check your ModelDoc2 object to make sure that it is the correct type. ModelDoc2 supports parts, assemblies and drawings.To drive parameter values in SolidWorks, the syntax is quite simple. Your ModelDoc2 object has a Parameter property and you just assign a value to it. Since that property includes the name of the parameter, it’s very important to name your SolidWorks dimensions and features within the model. It’s also important not to CHANGE those names once your code is written. The same goes with your Excel. You can see that we’re using the syntax RANGE(“cellname”).VALUE. Simply naming the cell makes life sooooo much easier…no sheetnames no column numbers, no activating anything.Another thing to remember is that the SolidWorks API works in meters, and so must you. You can do that by easily multiplying or dividing by a factor. I, personally, think that’s very sloppy. I don’t like numbers in my equations unless they’re absolutely necessary. A better option is to build a quick function that converts inches into meters. One input and one output. If you want to go one step further, you can make the units in the UI in-cell pulldowns and then create a single function where you pass the value, the original units and the target units. It’s only going to be a couple of lines of code, but it will be very useful.You may also want to take advantage of some of the SolidWorks functionality to make this process easier. If you have five dimensions that are always going to be the same value, use a LINK VALUES, then drive one. Geometric relations like symmetry and midpoints are great ways to reduce your inputs. You can also use SolidWorks equations, but I greatly prefer link values over equations for equalities and I tend to put equations inside the automation. If there is a possibility that you may need to output or use the ending value in another calculation, put the equation in the automation.
And now it’s time for your first “Sherpa Tip”…
I can’t really stress the simplification idea enough. It amazes me that the same people that would walk into a test in college saying, “I only need a 74 to pass, that’s all I’m going to do” are the same people that spend 49 hours building a 78MB part that is purchased and that we only need to know the location of four bolt holes on. I can guarantee you that no matter how fast your automation runs, people will eventually complain about how slow it is. If your models are overly complex, it’s going to get exponentially slower.
In a lot of cases, you don’t even need Solid Geometry. Yes, it’s sexy looking, but guess what. This is automated. Nobody’s going to see it.
Simplification actually goes one step further when it comes to automation. Let me flash back to our opening and mention again that we are primarily talking here about design automation, that is, using SolidWorks to take a design that is somewhat repetitive in its nature, and allow many or even infinite combinations and permutations to be created of that design. We are NOT talking here about the occasional macro to save you four mouse clicks. So, in that vein, it is very important that when you look into automating your designs with the SolidWorks API, that you minimize, if not completely eliminate, any code that creates geometry. That is how the solution partners do it. They don’t build geometry. You build flexible, parametric geometry and their products manipulate it and, maybe assemble it. There are far too many things that can and will go wrong if you try to create your geometry through the API. That is not the best way to do automation. Here is a nice way to use it…
Here’s our scissor lift model. It’s actually made up of 4 sketches. I threw that cylinder in there for the visualization purposes of this slide only. Same with the planes. They don’t server any purpose except a visual aide for this image. We have a sketch with a single line that represents the overall length of the cylinder. We’re going to drive the length of that line to simulate the two extremes of the scissor lift. Then there are three separate sketches that are actually sitting on top of each other. The first sketch has two crossing lines representing a scissor lift with one…one sciss. We then have a two sciss sketch and a three sciss sketch. This allows us to put in separate height values for the sketches and to solve each possible case for the link length. So in essence, we’re running three case studies at once. We’ll drive the sketches, then have SolidWorks report back the leg lengths if we were to use one sciss, what the leg length would be if we used two scisses and also the answer if we used three. We’ll then use the automation tool to pick the best option.A quick note here is that the Link Length dimensions are sketch dimensions that have been created, named, then set to DRIVEN…in that order. If you create reference dimensions outside of a sketch, or inside of a sketch, you do not have the ability to rename them. For this reason, I highly recommend that you create dimensions that will overdefine your assembly in most cases. Leave them as driving in the warning dialog, rename them, then mark them as driven. Your sketch will be happy once more and you will have intelligently named reference dimensions.
Once we’ve driven the values that we need to drive, it’s time to rebuild the model. SolidWorks will often rebuild for us when we’re using it through the interface. Not so through the API. You need to tell SolidWorks when to rebuild. And to make matters worse, there are three ways to do it. You can see them up here. For our purposes, there are really two. EditRebuild is like hitting that traffic light with two lights. SolidWorks rebuilds what it thinks it needs to rebuild. Of course that dirty flag is notoriously unreliable, which is why we recommend the API equivalent of the Ctrl-Q. If you have a good size assembly, you can pass it TRUE to only rebuild the assembly and not the stuff underneath, but I certainly recommend doing the whole shebang.But here’s the thing…SolidWorks is always going to be the slowest part of this chain. So if you’re interested in performance, you may want to minimize the number of rebuilds that you have. Make as many changes as you can before you rebuild. You always need to rebuild before you retrieve any values, but most inputs can be made without a rebuild. Notable exceptions occur, of course, when one change modifies a feature that then needs to be acted on in such a way that faces or parameters won’t exist until the model is rebuilt. You’ll know when this happens when your numbers start coming out wrong and your code crashes.
So once we’ve rebuilt and SolidWorks has recalculated whatever it is that we want SolidWorks to calculate (our link lengths in this case), then we can retrieve the values. Retrieving parameter values is as simple as flipping the assignment equations around. Again, watch your data types and units. Dimensions will come back as doubles in meters, regardless of the units in your model. Once more, you can put the factor in there, or create some handy function to help you bring it over.You can bring these values into variables in your code, or straight into your design automation system (Excel cells in this case) and then use these values to perform more calculations. I know that I said that I wouldn’t do this, but let me actually show you one little bit of live code.
OK. I get the message. No live code. Just let me reboot. This will just take a second.
OK, I don’t think that we need Safe Mode.
We just need to wait a moment here while Vista boots.
So once we’ve rebuilt and SolidWorks has recalculated whatever it is that we want SolidWorks to calculate (our link lengths in this case), then we can retrieve the values. Retrieving parameter values is as simple as flipping the assignment equations around. Again, watch your data types and units. Dimensions will come back as doubles in meters, regardless of the units in your model. Once more, you can put the factor in there, or create some handy function to help you bring it over.You can bring these values into variables in your code, or straight into your design automation system (Excel cells in this case) and then use these values to perform more calculations. I know that I said that I wouldn’t do this, but let me actually show you one little bit of live code.
So once we have our values back from SolidWorks, We can go ahead and do more calculations. The calculations can exist either in your code or in your automation system. So this begs the question, where do I do the calcs? The deciding factor should be the type of calculation. If it’s something that Excel or your design automation can handle, do it there. The calculations are more visible; easier for non-programmers to maintain, update, or troubleshoot; and it allows you to store more engineering intelligence in your automation system, rather than in the code. Obviously, if it’s something that your design automation system can not handle, like some iterative algorithms, or if it involves going back to SolidWorks then it may be better to do it in the code.
As I said before, SolidWorks is going to be the slowest portion of the system. So just as we want to minimize the number of rebuilds, we certainly want to minimize the number of times we need to go back and forth with SolidWorks. If you are doing an iterative solving problem with SolidWorks, use intelligent seed values. Don’t just guess wildly, track the values that you’ve already used and how far off they were. Then interpolate or extrapolate to get a better seed value. And build a little intelligence into your first guess. If you were doing this by hand, you know you would mumble something like, “Well, if that’s 50 and that’s ¼, then it would be somewhere around 28…plus three quarters…carry the two…ok.” Put that same thought process into your automation to get good intelligent values.You can also build more intelligence into your models to minimize the amount of times that you have to drive SolidWorks. Use relationships between sketches, between parts. Use equations. Put multiple solutions in the model, like we did, and run them simultaneously.
OK, it’s time for your second “Sherpa Tip”. And I apologize for the quality of the video, the high altitude can really mess with the equipment and it’s hard to hold a camera still in 40 below temperatures with mittens on.
In most cases, the desired outputs of your automation will be the SolidWorks models and/or drawings. In other cases, you may want things like quotes, calculation documentation, inspection sheets, costing breakdowns, Bills of Materials, and so on. Most commercially available design automation solutions provide mechanisms to get you there. If you’re not using a commercially available product, or if they don’t support what you need, you can fairly easily put the stuff straight into your Excel spreadsheet or do any of these wonderful things in the code. And that’s the end of the process. Let’s look at another example…
OK, this example is actually based off of a true client story. The company name and the product have been radically changed to protect the intellectual property of the client. Have you ever seen how some urban buildings will have these spike strips to…um…discourage pigeons to land there and rain their wares upon unsuspecting folks below? Well out in the suburbs, I figured we need the same thing for those pesky suburban rats that drain your bird feeders. So I invented the Specialized Squirrel Skewer Syndicate. A company dedicated to protecting the food supply for our suburban avian friends. Just put these specially designed speed bump skewers around your feeders and you’re set. Small birds can land on them and grip onto the side as if it were a pond reed, but the bushy tail rodents will be kept out. And the company actually custom designs skewers for each application. Based on the width and length of the railing as well as the particular size of your unwelcome inhabitants, the curvature and shape of the plastic base are modified along with the spacing and angle of the metal enforcement devices to provide optimum protection against invasions of Sciuruscarolinensis.
So the design approach here is to take the inputs that we mentioned, and drive the base geometry. But to determine the spike placement, we need to ensure that the minimum and maximum distance between the spikes falls within a tolerance zone that we have determined through years of empirical experimentation. So we will determine a first pass number, drive the shape of the base part, then drive the locations of the points on the base part and the angles of the mates in the assembly. Then we’ll rebuild the model and do a measure finding the minimum and maximum distances between the two parts in the assembly, pass those back to our design automation and determine if they are within tolerance. If they are, then we can go ahead and finalize the design in our automation system. If not, we recalculate the spacings and angles, drive the SolidWorks model again, retrieve new values and continue to iterate.
So here is the model that we have. It’s a simplified model made up of a single swept feature for the plastic base. Then we took two sketches and extruded them up into surfaces. We then added two planes offset along the depth of the base. The spikes are always going to lie at the intersection of these three entities: The sweep, the projected sketch and the plane. We then made a simple assembly by inserting two very simple spike components. We put some datum point features on the tips of the spikes to make it easier to measure. Our goal is to drive the shape of the base part and depth of the planes to determine the locations of the spikes.
Programmatically, this is what we did. We developed an empirical equation to determine the spacing for the two planes. It was a simple geometric equation assuming that everything is square and flat, and factoring in some tests that we did to come up with some constants. That equation takes the inputs and ballparks the plane distances. We then push those and the dimensions for the sweep into SolidWorks. We regenerate the model which relocates the planes, then the intersection point, which drives the location and mating conditions for the spikes. We then measure the min and max distances between the spikes and pass them from SolidWorks back to our automation. We look at those distances and see if they’re within a tolerance percentage of the dimensions of the squirrel. If they are, then we’re off to the races and we pass the values to the correct Excel cells. If the numbers are outside of tolerance, we see which direction and how far, then we adjust and repeat the SolidWorks loop until they are within tolerance.
Sounds simple enough, right? Well, here’s how we tackled the tricky bits. We took operations that we would potentially do more than once and we made separate functions for them. This does save some time in coding, but the best advantage of doing this is that it really simplifies your code. Imagine a flowchart, with each rectangle in it another calculation. With the use of functions, your main code will look just like that. And each calculation will be its own separate code task.
When you sit down to write the code, I can guarantee that you’re not going to think that you need all of this. But quite often to get to what you need in SolidWorks you need to understand the SolidWorks object structure. I don’t want to spend too much time explaining OOP, since it is covered in last year’s presentation available at www.razorleaf.com, but when it comes to SolidWorks, each object type has its own properties and methods. And what is quite unfortunate is that there are a lot of objects. They get fairly specific. And what you need to do is quite often not available for the object that you have. As a result, you spend an inordinate amount of time going up and down the object structure looking for the object that you need.
Case in point. I want a distance. That distance is created running the calculate method on a measure object. So that means that I need to get the measure object. I also need to specify what I’m calculating. That can be the selection set, at which point you would need to select things and have a selection manager object to manage them. Here we went the other route and we’re passing it an array of objects. So we have to create the array, and we need to populate the array with the two faces that we’re measuring between. To get the face objects, we need the body object. To get the body object, we need the component object or the part object. To get the component object, we need to cycle through an array of components that we get from the assembly object which we get from the ModelDoc2 object which we ultimately get from the SolidWorks Application object.Now I know what you’re thinking. That’s a lot of work, there’s got to be an easier way. If you find it, let me know. And before you say anything, simply selecting the face by its name does not work. You think that it would, but in our testing it just wouldn’t work. But the theory is this. Start with the end in mind, as Stephen Covey would say. Understand your overall design and what you’re after. Then figure out what you need to get that, then what you need to get that, then what you need to get that…and so on. That’s one reason that I loved the old API guide. You could select an object and look at its ACCESSORS, that is, what methods are available for you to get that object. Quite handy.
So that leads us to our third and final “Sherpa Tip”
So what if you want to do more than modify a parameter value? Well, we gave you the secret a minute ago. The basic approach is to figure out where the property that you want to change or method that you want to act upon is located in the object model. Then figure out how to get there. Sometimes you can use the Selection Manager and sometimes you can get lucky to get SelectByID2 to work. In a lot of cases, though, you end up traversing the tree. Getting the right objects (or Interfaces if you’re in .NET) is probably 85% of the fight in SolidWorks programming.
Other things that you may want to do include mass properties. There is an object for that. Section properties, there’s actually no object for this, but instead, it returns a SafeArray. SolidWorks used to use these a lot, but their popularity is waning. In essence, if there are multiple values, SolidWorks will throw them all into a giant array of values. What’s difficult about that is that you need to know which entity in the array you’re looking for. Somewhat clumsy, but that’s life. Sheesh. I can’t even get away from these pop-up ads in a PowerPoint!! NO! I do NOT want to take a survey, because I am not a satisfied customer!
We already saw the measure object (Imeasure interface in .NET) at work a little. Here’s is the deal with the measure object. First, you must create the object. You can set some properties on it, like precision and units and how arcs are measured. Then you kick off the CALCULATE method. Here you pass it an array of objects. If you pass it NOTHING, then it measures the current selection set. Be sure to use the SelectionManager object to manage this. If you choose to build your own object array, you can do that fairly easily as well, like we did in the last example. Once you calculate, you can then grab whatever values you want from the object’s properties.
Here’s another nifty one. Macro features. I won’t go into depth on how to create these, it’s pretty well documented. The idea, though, is that you have a SolidWorks Macro and you stick it at a specific spot IN the Feature Mangler. SolidWorks will then execute that code every time that it hits that point in the Feature Mangler. Here are some great uses for it. Primarily they center around looking at the model in an unfinished state, taking some information from there and passing it back to the automation or using that to continue the construction of the model. If you think about the SolidWorks model as mimicking your manufacturing process, then the macro feature allows you to report back information while your part is sitting, queued up for the next process. Handy little feature.
OK, I’ve mentioned .NET a little here and there. And you are certainly welcome to use .NET if you want. Is it a better programming language? No question. Is it necessary? Not in most cases. One thing that I can’t stress enough is that while we have talked primarily about programming here today, the code is designed to augment your design automation. I DO NOT recommend a custom programmed solution (although Razorleaf Corporation will be happy to write one for you if you insist). Go to the Partner Pavilion and see what’s there for design automation. The best benefit of design automation is to capture and document your intellectual property. The hows and whys of your design. Programming languages are a lousy medium for doing that.
Once again, here are the steps.
So here are the highlights. We’re talking about using SolidWorks to perform complex calculations. We do that by collecting information in our design automation system,