How to simulate Robotic Arm

process simulate robotics and robotic simulation advantage and free simulator robotic arm and robotic simulation artificial intelligence
Dr.MohitBansal Profile Pic
Published Date:26-10-2017
Your Website URL(Optional)
FIRST EXAMPLE: SIMULATING A ROBOTIC TANK This example serves two purposes. First, it illustrates how hybrid dynamics can appear in engineering problems. The model has three main parts: the equations of motion, a model of the propulsion system, and a model of the computer. The first two are piecewise continuous with discontinuities caused by step changes in the motor voltage and the sticking friction of the rubber tracks. The third model is a prototypical example of a discrete-event system; the tank’s computer is modeled with an interruptible server and queue. The equations of motion, propulsion system, and computer are combined to form a complete model of the tank. Second, this example illustrates the basic elements of a software architecture for large simulation programs. The simulation engine is responsible solely for calculating the dynamic behavior of the model; other functions (visualization and interactive controls, calculation of performance metrics, etc.) are delegated to other parts of the software. This approach is based on two patterns or principles: model–view–control and the experimental frame. Model–view–control is a pattern widely used in the design of user interfaces (see, e.g., Refs. 47 and 101); the simulation engine and model are treated as a dynamic document and, with this perspective, the overarching design will probably be familiar to most software engineers. The experimental frame (as described, e.g., by Daum and 1 Sargent 31) is a logical separation of the model from the components of the program that provide it with input and observe its behavior. These principles simplify8 FIRST EXAMPLE: SIMULATING A ROBOTIC TANK reuse; programs for two experiments illustrate how they are applied and the benefit of doing so. The entirety of this example need not be grasped at once, and its pieces will be revisited as their foundations are established in later chapters. Its purpose here is to be a specific example of how the simulation engine is used, and to motivate the software architecture and algorithms that are discussed in the subsequent chapters of this book. 2.1 FUNCTIONAL MODELING Fishwick 42 defines a functional model as a thing that transforms input into output. This view of a system is advantageous because it leads to a natural decomposition of the simulation software into objects that implement precisely defined transfor- mations. Distinct functions within the model are described by distinct functional blocks which are connected to form a complete model of the system. The software objects that implement the functional blocks are connected in the same way to build a simulator. There are numerous methods for designing models. Many of them are quite general: bond graphs and state transition diagrams, for instance. Others are specific to particular problems: the mesh current method for electric circuits and the Lagrangian formulation of a rigid body. The majority of methods culminate in a state space model of a system: a set of state variables and a description of their dynamic behavior. Mathematical formulations of a state space model can take the form of, for example, differential equations, difference equations, and finite-state machines. To change a state space model into a functional model is simple in principle. The state variables define the model’s internal state; state variables or functions of state variables that can be seen from outside the system are the model’s output; variables that are not state variables but are needed for the system to evolve become the model’s input. In practice, this change requires judgment, experience, and a careful consideration of sometimes subtle technical matters. It may be advantageous to split a state space model into several interacting functional models, or to combine several state space models into a single functional model. Some state space models can be simplified to obtain a model that is easier to work with; simplification might be done with precise mathematical transformations or by simply throwing out terms. The best guides during this process are experience building simulation software, familiarity with the system being studied, and a clear understanding of the model’s intended use. Functional models and their interconnections are the specification for the simu- lation software. For this purpose, there are two types of functional model: atomic and network. An atomic model has state variables, a state transition function that defines its internal response to input, and an output function that transforms internal action into observable behavior. A network model is constructed from other func- tional models, and the behavior of the network is defined by the collective behavior of its interconnected components. The simulator is built from the bottom up by implementing atomic models, connecting these to form network models, combining www.allitebooks.comA ROBOTIC TANK 9 Input Output State (a) System C System A System B System D (b) FIGURE 2.1 Bottom–up construction of a model from functional pieces: (a) input, output, and internal state of an atomic model; (b) a network model constructed from three atomic models. these network models to create larger components, and repeating until the software is finished. This bottom–up approach to model construction is illustrated in Figure 2.1. The simulation engine operates on software objects that implement atomic and network models. To build a simulator therefore requires the parts of a dynamic system to be expressed in this form. Functional models need not be built in a single step. Atomic and network models are more easily obtained by a set of steps that start with an appropriate modeling technique, proceed to a state space description of the model’s fundamental dynamics, combine these to create more sophisticated components, and end with a—possibly large—functional model that can be acted on by the simulation engine. 2.2 A ROBOTIC TANK The robotic tank is simple enough to permit a thorough discussion of its continuous and discrete dynamics, but sufficiently complicated that it has features present in larger, more practical systems. The robot’s operator controls it through a wireless network, and the receipt, storage, and processing of packets is modeled by a discrete event system. An onboard computer transforms the operator’s commands into control signals for the motors. The motors and physical motion of the tank are modeled as a continuous system. These components are combined to create a complete model of the tank. Our goal is to allocate the cycles of the tank’s onboard computer to two tasks: physical control of the tank’s motors and processing commands from the tank’s operator. The tank has four parts that are relevant to our objective: the radio that receives commands from the operator, the computer and software that turn these10 FIRST EXAMPLE: SIMULATING A ROBOTIC TANK commands into control signals for the motors, the electric circuit that delivers power to the motors, and the gearbox and tracks that propel the tank. The tank has two tracks, left and right, each driven by its own brushless direct-current (DC) motor. A gearbox connects each motor to the sprocket wheel of its track. The operator drives the tank by setting the duty ratio of the voltage signal at the terminals of the motors. The duty ratio are set using the control sticks on a gamepad and sent via a wireless network to the computer. The computer generates two periodic voltage signals, one for each motor. The motor’s duty ratio is the fraction of time that it is turned on in one period of the signal (i.e., itson time). Because the battery voltage is fixed, the power delivered to a motor is proportional to its duty ratio. Driving the tank is straightforward. If the duty ratio of the left and right motors are equal then the tank moves in a straight line. The tank spins clockwise if the duty ratio of the left motor is higher than that of the right motor. The tank spins counterclockwise if the duty ratio of the right motor is higher than that of the left motor. A high duty ratio causes the tank to move quickly; a low duty ratio causes the tank to move slowly. If the voltage signal has a high frequency, then the inertia of the motor will carry it smoothly through moments when it is disconnected from the batteries; the motors operate efficiently and the tank handles well. If the frequency is too low, then the motor operates inefficiently. It speeds up when the batteries are connected, slows down when they are disconnected, and speeds up again when power is reapplied. This creates heat and noise, wasting energy and draining the batteries without doing useful work. Therefore, we want the voltage signal to have a high frequency. Unfortunately, a high-frequency signal means less time for the computer to process data from the radio. If the frequency is too high, then there is a noticeable delay as the tank processes commands from the operator. At some point, the computer will be completely occupied with the motors, and when this happens, the tank becomes unresponsive. Somewhere in between is a frequency that is both acceptable to the driver and efficient enough to give a satisfactory battery life. There are physical limits on the range of usable frequencies. It cannot be so high that the computer is consumed entirely by the task of driving the motors. It cannot be so low that the tank lurches uncontrollably or overheats its motors and control circuits. Within this range, the choice of frequency depends on how sensitive the driver is to the nuances of the tank’s control. An acceptable frequency could be selected by experimenting with the real tank; let a few people drive it around using different frequencies and see which they like best. If we use the real tank to do this, then we can get the opinions of a small number of people about a small number of frequencies. The tank’s batteries are one constraint on the number of experiments that can be conducted. They will run dry after a few trials and need several hours to recharge. That we have only one tank is another constraint. Experiments must be conducted one at a time. If, however, we build a simulation of the tank, then we can give the simulator to anyone who cares to render an opinion, and that person can try as many different frequencies as time and patience permit.A ROBOTIC TANK 11 TABLE 2.1 Value of Parameters Used in the Tank’s Equations of Motion Parameter Value Description m 0.8 kg Mass of the tank t −4 2 J 5× 10 kg· m Angular mass of the tank t B 0.1 m Width of the tank from track to track B 1.0 N· s / m Mechanical resistance of the tracks to rolling forward r B 14.0 N· s / m Mechanical resistance of the tracks to sliding forward s B 0.7 N· m· s / rad Mechanical resistance of the tracks to turning l S 0.3 N· m Lateral friction of the tracks l 2.2.1 Equations of Motion The model of the tank’s motion is adapted from Anh Tuan Le’s PhD dissertation 74. The model’s parameters are listed in Table 2.1, and the coordinate system and forces acting on the tank are illustrated in Figure 2.2. The model assumes that the tank is driven on a hard, flat surface and that the tracks do not slip. The position of the tank is given by its x and y coordinates. The headingθ of the tank is measured with respect to the x axis of the coordinate system and the tank moves in this direction with a speed v. The left track pushes the tank forward with a force F ; the right track, with a force l F ; and B is the mechanical resistance of the tracks to rolling. The tank uses skid r r steering; to turn, the motors must collectively create enough torque to cause the tracks to slide sideways. This requires overcoming the sticking force S . When sufficient l torque is created, the vehicle begins to turn. As it turns, some of the propulsive force is expended to drag the tracks laterally; this is modeled by an additional resistance B to its turning motion and B to its rolling motion. l s The tank’s motion is described by two sets of equations, one for when the tank is turning and one for when it is not. The switch from turning to not turning (and vice x θ v v l r B F F l r y FIGURE 2.2 Coordinate system, variables, and parameters used in the tank’s equations of motion.12 FIRST EXAMPLE: SIMULATING A ROBOTIC TANK versa) has two discrete effects: (1) the angular velocity ω changes instantaneously to and remains at zero when the tracks stick and the turn ends, and (2) the rolling resistance of the tank changes instantaneously when the tank starts and ends a turn. The Boolean variable turning is used to change the set of equations. The equations that model the motion of the tank are ⎧ B ⎨ true if F − F≥ S l r l turning= (2.1) 2 ⎩ false otherwise ⎧   1 ⎪ ⎪ F + F − (B + B )v if turning= true ⎨ l r r s m t v ˙ =   (2.2) 1 ⎪ ⎪ ⎩ F + F − B v if turning= false l r r m t ⎧   ⎪ 1 B ⎨ (F − F )− Bω if turning= true l r l ω ˙ = (2.3) J 2 t ⎪ ⎩ 0if turning= false ˙ θ =ω (2.4) x ˙ = v sin(θ) (2.5) y ˙ = v cos(θ) (2.6) If turning= false thenω= 0 (2.7) When turning changes from false to true, every state variable evolves from its value immediately prior to starting the turn, but using the equations designated for turning= true. When turning changes from true to false, every state variable except ω evolves from its value immediately prior to ending the turn, but using the equations designated for turning= false;ω changes instantaneously to zero and remains zero until the tank begins to turn again. These differential equations describe how the tank moves in response to the propulsive force of the tracks. The track forces F and F are inputs to this model, l r and we can take any function of the state variables—v,ω,θ, x, and y—as output. For reasons that will soon become clear, we will use the speed with respect to the ground of the left and right treads; Figure 2.2 illustrates the desired quantities. The speed v l of the left tread and speed v of the right tread are determined from the tank’s linear r speed v and rotational speedω by v = v+ Bω/2 (2.8) l v = v− Bω/2 (2.9) rA ROBOTIC TANK 13 The dependence of the input on the output is denoted by the function   v (t) T l = M F (t) F (t) (2.10) l r v (t) r This function accepts the left and right tread forces as input and produces the left and right tread speeds as output. How were the values in Table 2.1 obtained? Two of them were measure directly: the mass of the tank with a postal scale and the width of the tank with a ruler. The angular mass of the tank is an educated guess. Given the width w and length l of the tank’s hull, which were measured with a ruler, and the mass, obtained with a postal scale, the angular mass is computed by assuming the tank is a uniformly dense box. With these data and assumptions, we have m t 2 2 J = (w + l ) t 12 This is not precise, but it is the best that can be obtained with a ruler and scale. The resistance parameters are even more speculative. The turning torque S was l computed from the weight W of the tank and length l of the track, which were both t measured directly, a coefficient of static frictionµ for rubber from Serway’s Physics s for Scientists and Engineers 133, and the approximation Wl µ t s S = l 3 from Le’s dissertation 74. The resistances B and B to forward motion and resis- r s tance B to turning were selected to give the model reasonable linear and rotational l speeds. This mix of measurements, rough approximations, and educated guesses is not uncommon. It is easier to build a detailed model than to obtain data for it. The details, however, are not superfluous. The purpose of this model is to explore how the tank’s response to the driver changes with the frequency of the power signal sent to the motors. For this purpose it is necessary to include those properties of the tank that determine its response to the intermittent voltage signal: specifically, inertia and friction. 2.2.2 Motors, Gearbox, and Tracks The motors, gearbox, and tracks are an electromechanical system for which the method of bond graphs is used to construct a dynamic model (Karnopp et al. 61 give an excellent and comprehensive introduction to this method). The bond graph model is coupled to the equations of motion by using Equation 2.10 as a bond graph element. This element has two ports, one of which has the effort variable F and flow l variable v , and the other, the effort variable F and flow variable v . The causality l r r14 FIRST EXAMPLE: SIMULATING A ROBOTIC TANK of this element is determined by the functional form of Equation 2.10: it is supplied with the effort variables and produces the flow variables. This was the reason for selecting the track speeds as output. The model of the motors, gearbox, and tracks accounts for the inductance and internal resistance of the electric motors, the angular mass and friction of the gears, and the compliance of the rubber tracks. The electric motors are Mabuchi FA-130 Motors, the same type of DC motor that is ubiquitous in small toys. One motor drives each track. The motors are plugged into a Tamiya twin-motor gearbox. This gearbox has two sets of identical, independent gears that turn the sprocket wheels. The sprocket wheels and tracks are from a Tamiya track-and-wheel set; the tracks stretch when the tank accelerates (in hard turns this causes the tracks to come off the wheels), and so their compliance is included in the model. To drive the motors, the computer switches a set of transistors in an Allegro A3953 full-bridge pulsewidth-modulated (PWM) motor driver. When the switches are closed, the tank’s batteries are connected to the motors. When the switches are open, the batteries are disconnected from the motors. The transistors can switch on and off at a rate three orders of magnitude greater than the rate at which the computer can operate them, and power lost in the circuit is negligible in comparison to inefficiencies elsewhere in the system. The batteries and motor driver are, therefore, modeled as an ideal, time varying voltage source. A sketch of the connected motors, gearbox, and tracks and its bond graph are shown in Figure 2.3. Table 2.2 lists the parameters used in this model. The differential + − − + e e l r l r v v l r (a) L R J B K m m g g t r/g e F l l SE 1 GY 1 TF 0 i l l v l T M(F F ) L R J B l r m m g g v r r/g e F r r SE 1 GY 1 TF 0 i r r K t (b) FIGURE 2.3 Motors, gears, and tracks of the tank: (a) diagram; (b) bond graph.A ROBOTIC TANK 15 TABLE 2.2 Parameters of the Motors, Gearbox, and Tracks Parameter Value Description −3 L 10 H Inductance of the motor m R 3.1 Resistance of the motor m −6 2 J 1.2× 10 kg· m Angular mass of the gears g −7 B 6.7× 10 N· m· s / rad Mechanical resistance of the gears to rotation g g 204 Gear ratio of the gearbox −3 α 10 N· m / A Current–torque ratio of the electric motor r 0.015 m Radius of the sprocket wheel −3 K 10 m / N Compliance of the track t equations are read directly from the bond graph: 1 ˙ i = (e − i R −αω ) (2.11) l l l m l L m   1 r ω ˙ = αi −ω B − F (2.12) l l l g l J g g   1 r ˙ F = ω − v (2.13) l l l K g t 1 ˙ i = (e − i R −αω ) (2.14) r r r m r L m   1 r ω ˙ = αi −ω B − F (2.15) r r r g r J g g   1 r ˙ F = ω − v (2.16) r r r K g t where e and e are the motor voltages and v and v are the track speeds given by l r l r Equations 2.8 and 2.9. Values for the parameters in Table 2.2 were obtained from manufacturers’ data, from measurements, and by educated guesses. The gear ratio g and current–torque ratioα are provided by the manufacturers. The gear ratio is accurate and precise (espe- cially with respect to the values of other parameters in the model). The current–torque ratio is an average of the two cases supplied by Mabuchi, the motor’s manufacturer. The first case is the motor operating at peak efficiency, and the second case is the motor stalling. The difference between these two cases is small, suggesting that α does not vary substantially as the load on the motor changes. The estimate of α is, therefore, probably very reasonable. The radius r of the sprocket wheel and the resistance R and inductance L of m m the motor were measured directly. A ruler was used to measure the radius of the sprocket wheel. To determine R and L required more effort. The current i through m m16 FIRST EXAMPLE: SIMULATING A ROBOTIC TANK the unloaded motor is related to the voltage e across the motor by the differential equation 1 ˙ i = (e− iR ) (2.17) m L m The parameters L and R were estimated by connecting a 1.5-V C battery to the m m motor and measuring, with an oscilloscope, the risetime and steady state of the current through the motor. Let i be the steady-state current, t the risetime, and 0.9i the f r f current at time t (i.e., the risetime is the amount of time to go from zero current to r ˙ 90% of the steady-state current). At steady state i = 0 and the resistance of the motor is given by e R = m i f The transient current is needed to find L . The transient current is given by the m solution to Equation 2.17:    e R m i(t)= 1− exp − t (2.18) R L m m Substituting 0.9i for i(t) and t for t in Equation 2.18 and solving for L gives f r m   1 1 R i i m f f =− ln 1− 0.9 i =− ln(0.1)≈ 2.3 f L R t e et et m m f f f or, equivalently t f L ≈ 0.652 m i f A similar experiment was used to obtain B . In this experiment, the motor was g connected to the gearbox. As before, an oscilloscope was used to measure the risetime and steady-state value of the current through the motor. The rotational velocityω ˜ of the motor is given by 1 ˙ ω ˜ = (αi−ω ˜ B ) g J g The manufacturer gives the speed of the motor when operating at peak efficiency as ˙ ω ˜ = 731.6 radians per second (rad/s). At steady stateω ˜ = 0. The steady state currentA ROBOTIC TANK 17 x e l Tank Physics y e r θ FIGURE 2.4 Input and output of the model of the tank’s physics. i is measured with the oscilloscope. With i and the motor speed, the mechanical f f resistance of the gearbox is given by αi f −6 B ≈ = 1.37× 10 i g f ω ˜ The angular mass J of the gearbox was estimated from its mass m , radius of g gb the gears r , and the assumption that the mass is uniformly distributed in a cylinder. gb With this set of measurements and assumptions, the angular mass is 2 J = m r g gb gb The compliance of the tracks is an order-of-magnitude approximation. The tracks can be stretched by only a few millimeters before they slip off the wheels. The maximum propulsive force of the track is about a newton. The order of magnitude of −3 0 the track compliance is, therefore, estimated to be 10 meters/10 newtons, or about −3 10 m/N. 2.2.3 Complete Model of the Tank’s Continuous Dynamics Equations 2.1–2.9 and 2.11–2.16 collectively describe the physical behavior of the tank. The equations of motion and the equations for the motors, gearbox, and tracks were developed separately, but algorithms for solving them work best when coupled equations are lumped together. Consequently, these are put into a single functional model called “tank physics,” which is illustrated in Figure 2.4. The inputs to the tank are the voltages across its left and right motors; these come from the computer. The output of the tank is its position and heading; these are observed by the tank’s operator. The complete state space model of the tank’s physical dynamics is ⎧ B ⎨ true if F − F≥ S l r l turning= (2.19) 2 ⎩ false otherwise ⎧   1 ⎪ ⎪ F + F − (B + B )v if turning= true ⎨ l r r s m t v ˙ =   (2.20) 1 ⎪ ⎪ ⎩ F + F − B v if turning= false l r r m t18 FIRST EXAMPLE: SIMULATING A ROBOTIC TANK ⎧   ⎪ 1 B ⎨ (F − F )− Bω if turning= true l r l ω ˙ = J 2 (2.21) t ⎪ ⎩ 0if turning= false ˙ θ =ω (2.22) x ˙ = v sin(θ) (2.23) y ˙ = v cos(θ) (2.24) If turning= false thenω= 0 (2.25) 1 ˙ i = (e − i R −αω ) (2.26) l l l m l L m   1 r ω ˙ = αi −ω B − F (2.27) l l l g l J g g    1 r Bω ˙ F = ω − v+ (2.28) l l K g 2 t 1 ˙ i = (e − i R −αω ) (2.29) r r r m r L m   1 r ω ˙ = αi −ω B − F (2.30) r r r g r J g g    1 r Bω ˙ F = ω − v− (2.31) r r K g 2 t This model has 11 state variables—v,ω,θ, x, y, i ,ω , F , i ,ω , and F ; two input l l l r r r variables—e and e ; and three output variables—x, y, andθ. l r 2.2.4 The Computer The computer, a TINI microcontroller from Maxim, receives commands from the operator through a wireless network and transforms them into voltage signals for the motors. The computer extracts raw bits from the Ethernet that connects the computer and the radio, puts the bits through the Ethernet and User Datagram Protocol (UDP) stacks to obtain a packet, obtains the control information from that packet, and stores that information in a register where the interrupt handler that generates voltage signals can find it. The interrupt handler runs periodically, and it has a higher priority than the thread that processes commands from the operator. Therefore, time spent in the interrupt handler is not available to process commands from the operator. The frequency of the voltage signal is determined by the frequency of the inter- rupt handler. Frequent interrupts create a high-frequency voltage signal; infrequent interrupts, a low-frequency signal. Figure 2.5 illustrates how the interrupt handler works. It is executed every N machine cycles and at each invocation adds 32 to a counter stored in an 8-bit register. The counter is compared to anon time that is set, www.allitebooks.comA ROBOTIC TANK 19 7.5 7 6.5 6 5.5 5 4.5 4 3.5 3 2.5 2 1.5 1 0.5 0 0 2 4 6 8 10 12 14 16 18 20 22 number of calls to the interrupt handler FIGURE 2.5 Generating a voltage signal with the interrupt handler. albeit indirectly, by the operator. If the counter is greater than or equal to theon time, then the motor is turned off. If the counter is less than theon time, then the motor is turned on. If, for example, the tank is operating at full power, then the on time for both motors is 255 and the motors are always on; if the motors are turned off, then theon time is zero. In Figure 2.5, the counter is initially zero and the motors are turned off. The on time is 128. The first call to the interrupt handler adds 32 to the counter, compares 32 128, and turns the motor on by connecting it to the tank’s 7.2-V battery pack. At call 4, the counter is assigned a value of 128, which is equal to the on time, and the motor is shut off. At call 8, the counter rolls over and the motor is turned on again. The code in the interrupt handler is short; it has 41 assembly instructions that require 81 machine cycles to execute. According to the computer’s manufacturer, 6 there are 18.75× 10 machine cycles per second, which is one cycle every 0.0533× −6 −6 10 s (0.0533µs). The interrupt handler, therefore, requires 0.432× 10 s (0.432 µs) to execute. The frequency of the voltage signal is determined by how quickly the interrupt handler rolls the counter over. On average, eight calls to the interrupt handler complete one period of the voltage signal. The length of this period is −6 −6 8× (0.432× 10 + 0.0533× 10 × N). We can choose N and thereby select the period of the voltage signal; the frequency f due to this selection is e 6 10 f ≈ (2.32) e 3.46+ 0.426N The discrete-event model of the interrupt handler has two types of events: Start interrupt and End interrupt.The Start interrupt event sets the interrupt indicator to −6 true and schedules an End interrupt to occur 0.432× 10 s later. The End interrupt event increments the counter, sets the motor switches, sets the interrupt indicator to volts20 FIRST EXAMPLE: SIMULATING A ROBOTIC TANK interrupt← true Start interrupt 0.432 µs Left/right motor direction interrupt Left/right e ← 7.2 if s =1 End l/r l/r motor on−time 0.0533N µs interrupt e ← -7.2 if s =2 l/r l/r e ← 0 if s =3 l/r l/r c← (c+32) mod 255 s ←1 ifc left/right motor on-time l/r and left/right motor direction = forward s ←2 ifc left/right motor on-time l/r and left/right motor direction = reverse s ←3 ifc≥ left/right motor on-time l/r interrupt← false FIGURE 2.6 Event graph for the interrupt handler. −6 false, and schedules a Start interrupt event to occur 0.0533× 10 N s later. There are two software switches, one for each motor, and each switch has three positions. If the software switch is in the first position, then the motor is connected to the tank’s 7.2-V battery pack. If the switch is in the second position, then the motor is connected to the batteries but the positive and negative terminals are reversed and the motor runs backward. In the third position, the motor is disconnected from the batteries. At any given time, a new on time and direction for either motor can be given to the interrupt handler, and it acts on the new settings when the next End interrupt event occurs. An event graph for the interrupt handler is shown in Figure 2.6 (event graphs were introduced by Schruben 131; Fishwick 42 describes their use in functional models). The model has nine state variables. Four of these are apparent in the diagram: the 8-bit counter c,the interrupt indicator, and the switches s and s for the left and l r right motors. Events that change theon time and direction of a motor are inputs to the model; these input variables are stored as the left motor ON time, left motor direction, right motor ON time, and right motor direction, bringing the count of state variables to eight. Implicit in the edges that connect the events is the time until the next event occurs, which is the ninth and final state variable for this system. The outputs from this model are the interrupt indicator and the left and right motor voltages. The output variables change immediately after the corresponding state variables. In the case that an event is scheduled at the same time that an input variable is changed, the event is executed first and then the corresponding variables are modified. When the computer is not busy with its interrupt handler, it is processing com- mands from the operator. Every command arrives as a UDP packet with 10 bytes: two floating-point numbers that specify the direction and duty ratio of the left and right motors, and 2 bytes of information that are not relevant to our model. The computerA ROBOTIC TANK 21 can receive data at a rate of about 40 kilobytes per second (kB). This estimate, which comes from the jGuru forum 120, agrees reasonably well with, but is slightly lower than, the maximum data rate given by the manufacturer. The computer talks to the 802.11b radio through an Ethernet (the radio is controlled by a separate microproces- sor) that has a minimum packet size of 64 bytes, much larger than the 10-byte payload. Consequently, we can optimistically estimate that processing a packet takes 0.0016 s (1.6 ms, or 1600µs). We will ignore packet losses and assume that the computer (or, at least, the radio) can store any number of unprocessed packets. This is modeled with a server that has a fixed service time and an infinite queue. When the interrupt handler is executing, the server is forced to pause. The server produceson times and directions for the motors when it finishes processing a packet. Figure 2.7 is a DEVS graph (described by Zeigler et. al. 159 and, more recently, by Schulz et. al. 132; these are sometimes called phase graphs 42) for this model. It has three state variables: the packet queue q; the time σ remaining to process the packet at the front of the queue; and the model’s phase, which is interrupted or operating. It responds to two types of input: the interrupt indicator from the interrupt handler and packets from the network. The interrupt indicator moves the system into its interrupted phase where it remains until a second interrupt indicator is received, and this moves the system back to its operating phase. When the computer finishes processing a packet, it sets theon time and direction for the left and right motors and begins to process the next packet or, if there are no packets left, becomes idle. Each edge in the phase graph is annotated with the state variables that change when the phase transition occurs. Each phase contains its duration and the output value that is generated when the phase is left because its duration has expired. Packet processed (S4) Interrupt (S1) Left/right Packet Operating motor on−time Interrupted Interrupt and direction σ ∞ Left/right motor on−time and direction Interrupt (S0) Packet arrive (S2) Packet arrive (S3) S0: If σ ∞ then decrement σ by the elapsed time S1: If q is not empty and σ = ∞ then σ ← 1.6 ms S2: Insert packet at the back of q S3: If q is empty then σ ← 1.6 ms else decrement σ by the elapsed time Insert packet at the back of q S4: Remove the first element from q If q is empty then σ ←∞ else σ ← 1.6 ms FIGURE 2.7 Phase graph showing how the computer processes a packet.22 FIRST EXAMPLE: SIMULATING A ROBOTIC TANK Computer Left/right motor on−time e l Packet and direction e Packet Interrupt r processing handler Interrupt FIGURE 2.8 Block diagram of the tank’s computer. The models of the interrupt handler and thread that processes packets are connected to create a model of the computer. The interrupt handler receives the motoron times from the thread that processes packets; the thread receives interrupt indicators from the interrupt handler and packets from the network. The output from the computer sets the voltage at the left and right motors. Figure 2.8 shows a block diagram of the computer with its inputs, outputs, and internal components. The event graph and phase diagram are informative but not definitive. They do not specify when, precisely, output is produced or how to treat simultaneous events. These issues are deferred to Chapter 4, where state space models of discrete-event systems are formally introduced. 2.2.5 Complete Model of the Tank The complete model of the tank comprises the computer and the tank’s physics. The output of the computer is connected to the input of the tank’s physics. The position and orientation of the tank are displayed for the driver. The driver closes the loop by sending packets with control information to the computer. This arrangement is shown in Figure 2.9. The tank’s operator is not a model; the operator controls the simulated tank with the same software and hardware that are used to control the real tank. Computer Left/right motor on−time e l Packet and direction e Packet Interrupt r processing handler Interrupt e x l Tank Physics y e r θ FIGURE 2.9 Block diagram of the simulated tank and real operator.DESIGN OF THE TANK SIMULATOR 23 2.3 DESIGN OF THE TANK SIMULATOR The simulator has four parts: the simulation engine, the model of the tank, the driver’s interface, and the network interface. Figure 2.10 shows the classes that implement these parts and their relationships. The simulation engine and tank, which are our main concern, are implemented by the Simulator class and SimEventListener interface and the Tank class, respectively. The user interface is implemented by the Display class and DisplayEventListener interface, which take input from the user and display the motion of the tank. The UDPSocket class implements the network interface by which the simulator receives commands from the driver. FIGURE 2.10 Class diagram showing the major components of the simulation software.24 FIRST EXAMPLE: SIMULATING A ROBOTIC TANK The SimControl class implements the main loop of the application in its run method. This method advances the simulation clock in step with the real clock, up- dates the Display, and polls the Simulator, Display, and UDPSocket for new events. The SimControl class implements the SimEventListener interface by which it is noti- fied when components of the model change state and produce output. These callbacks are received when the SimControl object calls the Simulator’s computeNextState method. The SimControl also implements the DisplayEventListener class by which it is notified when the user does something to the display: for instance, pressing the quit key “q” or pressing the simulation reset key “r”. These callbacks are received when the SimControl calls the Display’s pollEvents method. The SimControl object ex- tracts CommandPackets from the network by polling the UDPSocket’s pendingInput method at each iteration of the main loop. The Simulator has six methods. The constructor accepts a model—it can be a multilevel, multicomponent model or a single atomic model—that the simulator will operate on. The method nextEventTime returns the time of the simulator’s next event: the next time at which some component will produce output or change state in the ab- sence of an intervening input. The method computeNextOutput provides the model’s outputs at the time of its next event without actually advancing the model’s state. The method computeNextState advances the simulation clock and injects into the model any input supplied by the caller. Objects that implement the SimEventListener inter- face and register themselves by calling the addEventListener method are notified by the Simulator when a component of the model produces an output or changes its state. These notifications occur when computeNextState or computeNextOutput is called. Missing from Figure 2.10 are the details of how the Tank is implemented; its major components are shown in Figure 2.11. The relationship between the Tank and Simulator is important. The Simulator is designed to operate on a connected collection FIGURE 2.11 Class diagram showing the major components of the model.EXPERIMENTS 25 of state space models; the Tank is a specific instance of such a model. The parts of the tank are derived, ultimately, from two fundamental classes: the AtomicModel class and the NetworkModel class. The Tank and Computer classes are derived from NetworkModel and they implement the block diagrams shown in Figures 2.8 and 2.9. The TankPhysics class, derived from AtomicModel, implements Equations 2.19–2.31. The PacketProcessing and InterruptHandler classes, also derived from AtomicModel, implement the models shown in Figures 2.6 and 2.7. This design separates the three aspects of our simulation program. The SimControl class coordinates the primary activities of the software: rendering the display, receiv- ing commands from the network, and running the simulation. It uses the Simulator’s six methods to control the simulation clock, inject input into the model, and obtain information about the model’s state and output. The Simulator and its myriad supporting classes (which are not shown in the dia- grams) implement algorithms for event scheduling and routing, numerical integration, and other essential tasks. These algorithms operate on the abstract AtomicModel and NetworkModel classes without requiring detailed knowledge of the underlying dy- namics. Models are implemented by deriving concrete classes from AtomicModel and NetworkModel. Models derived from the AtomicModel class implement state space representations of the continuous and discrete-event components. Models derived from the NetworkModel class describe how collections of state space and network models are connected to form the complete system. 2.4 EXPERIMENTS Before experimenting with the simulated tank, we must establish the range of frequen- cies that are physically feasible. An upper limit can be derived without simulation. Suppose that the computer does nothing except execute the interrupt handler. With zero instructions between invocations of the interrupt handler, Equation 2.32 gives a maximum frequency of 289 kHz for the voltage signal. At this frequency, the com- puter has no time to process commands from the driver and, consequently, the tank cannot be controlled. To determine a lower limit we simulate the tank running at half-throttle and measure the power dissipated in the motors. After examining the power lost at several frequencies, we can pick the lowest acceptable frequency as the one for which higher frequencies do not significantly improve efficiency. The software for this simulation is much simpler than for the interactive simulation, but it uses all of the classes shown in Figure 2.11 and the SimEventListener and Simulator classes shown in Figure 2.10. The classes that implement the model of the tank do not change: Figure 2.11 is precisely applicable. The remainder of the program, all of the new code that must be implemented to conduct this experiment, has fewer than 100 lines. The main function creates a Tank;a Simulator for the Tank; and a TankEventLis- tener, which computes the power lost in the motors. The TankEventListener is derived from the SimEventListener class. After registering the TankEventListener with the Simulator, the program injects a SimPacket into the tank at time zero. This packet26 FIRST EXAMPLE: SIMULATING A ROBOTIC TANK contains the duty ratio for the left and right motors. Now the simulation is run for 3 s, long enough for the tank to reach is maximum speed of approximately 0.2 m/s and run at that speed for a little over 2 s. The power P lost in the motors is 3 1 2 2 P = i (t) R + i (t) R dt l m r m 3 0 M−1  1 2 2 ≈ (t − t )(i R + i R ) (2.33) k+1 k m m l,k r,k t M k=0 where the t are the times at which the stateChange method of the TankEventListener k is called and i and i are the currents at time t . Note that t = 0 and t may l,k r,k k 0 M be slightly less than 3, depending on how the simulator selects timesteps for its integration algorithm (it could be made to update the state of the tank at t = 3, but was not in this instance). The stateChange method of the TankEventListener is called every time the Simu- lator computes a new state for an atomic component of the Tank. When this occurs, the TankEventListener calculates one step of the summation in Equation 2.33. The getPowerLost method computes the lost power by dividing the lost energy by the elapsed time. The C++ code that implements the TankEventListener is shown below. TankEventListener 1 ifndef TankEventListener_h 2 define TankEventListener_h 3 include "Tank.h" 4 include "SimEvents.h" 5 include "SimEventListener.h" 6 include fstream 7 8 class TankEventListener: public SimEventListener 9 10 public: 11 TankEventListener(const Tank tank): 12 SimEventListener(), 13 tank(tank),fout("current.dat"), 14 E(0.0), // Accumulated energy starts at zero 15 tl(0.0), // First sample is at time zero 16 il(tank-getPhysics()-leftMotorCurrent()), // i_l(0) 17 ir(tank-getPhysics()-rightMotorCurrent()) // i_r(0) 18 19 fout tl ""il""ir std::endl; 20 21 // Listener does nothing with output events 22 void outputEvent(ModelInput, double) 23 // This method is invoked when an atomic component changes state