The Racing Lounge is back from Christmas break. I wish you all a succesful and healthy 2018! In today’s post, Sebastian Castro discusses his experiences with a robotics workshop he helped deliver at the RoboCup Asia-Pacific (RCAP) event in Bangkok, Thailand. As a reminder, MathWorks is a global sponsor of RoboCup which comes with many benefits to student... read more >>

]]>In today’s post, Sebastian Castro discusses his experiences with a robotics workshop he helped deliver at the RoboCup Asia-Pacific (RCAP) event in Bangkok, Thailand.

As a reminder, MathWorks is a global sponsor of RoboCup which comes with many benefits to student teams. At RCAP, we had a booth with information, giveaways, software demonstrations, and more. We were even joined by our distributors in Southeast Asia, TechSource. Next time you’re at a RoboCup event, please stop by and say “hi”.

*MathWorks and TechSource at our booth*

One of the biggest challenges in RoboCup is the jump from the Junior (pre-university) leagues to the Major (university-level) leagues. Typically, there is a significant learning curve that stops even the most successful Junior teams from continuing in RoboCup once they move from high school to university.

Many RoboCup organizers are aware of this issue, which had led them to create intermediate challenges targeted at overcoming this learning curve. Unlike the Major league competitions, which are primarily research platforms for students pursuing advanced degrees, these challenges are more suited for educating undergraduate students. Some examples are the RoboCupRescue Rapidly Manufactured Robot and the RoboCup Asia-Pacific CoSpace challenges.

What made RCAP extra special for us was being invited by Dr. Jeffrey Tan to help with another challenge of this type. Dr. Tan has been an organizer with the RoboCup@Home league for over 4 years, as well as an advisor for the KameRider team. We decided to deliver a joint workshop for his RoboCup@Home Education league. This was a great opportunity for us because it allowed us to introduce MATLAB into various aspects of robot design and programming, and served as a good benchmark of our tools in a real, world-class competition.

There were 4 teams participating:

**Tamagawa Science Club**— Tamagawa Academy, Japan — high school**Nalanda**— Genesis Global School, India — high school**KameRider EDU**— Nankai University, China/Universiti Teknology Malaysia — undergraduate**Skuba JR**— Kasetsart University, Thailand — undergraduate

*RoboCup@Home Education Crew — Courtesy of Dr. Kanjanapan Sukvichai (Skuba JR advisor)*

For the first 2 days, we came up with an ambitious curriculum of topics that got the students up and running with a TurtleBot2 from scratch — including an RGB + depth sensor and a robot arm.

All we requested in advance was to bring a laptop with Ubuntu 14.04. We then installed the Robot Operating System (ROS) and MATLAB with a complimentary license from our Web site.

The goal was to develop the pieces of a typical RoboCup@Home algorithm. If the robot has a map of its environment and receives a spoken command — for example, “*bring me the water bottle from the kitchen*” — the diagram below is an example of the components needed to complete that task.

Speech recognition was done with CMU PocketSphinx, while speech input and synthesis was done with the audio_common stack. In the workshop, we showed how to detect speech, look for key words in a dictionary, and take actions based on those key words. This was all done outside of MATLAB.

Several students asked about MATLAB’s capabilities for speech recognition. Right now, there are two ways to get this working:

- Use the ROS tools above to publish the detected text on a ROS topic and subscribe to it in MATLAB.
- Call a user-defined Python speech module from MATLAB.

Once the text is in MATLAB, you can take advantage of its capabilities for characters and strings, or even the new Text Analytics Toolbox.

I have personally got approach #2 working with this Python SpeechRecognition package — in particular, with Google Cloud Speech and CMU PocketSphinx. The image below shows a simple example I ran which used Text Analytics Toolbox to cluster my speech into two categories — food and drink. There are words like “going”, “have”, and “some” which give us no extra information. Luckily, the toolbox has preprocessing capabilities to address such issues.

To perform mapping and navigation tasks, we took the following workflow

- Generate a map of the environment using the existing TurtleBot gmapping example and driving the robot around.
- In the example above, the latest map is published on a ROS topic (/map). So, we can read the map into MATLAB as an occupancy grid and save it to a file.
- Once the map is in MATLAB, we can sample a probabilistic roadmap (PRM) and use it to find a path between two points.
- Then, we can program a robot to follow this path with the Pure Pursuit algorithm.

Below you can see an example map and path I generated near my office. Assuming the map is static, steps 3 and 4 can be repeated for different start and goal points as needed.

For this task, we operated exclusively in the MATLAB world. We received many comments about prototyping with images being easier than with OpenCV, mostly because more challenging languages (Python or C++) were required for the latter.

Our vision and control workflow was:

- Using the Color Thresholder app to define thresholds for tracking an object of interest
- Performing blob analysis to find the object position
- Estimating the distance object using the depth image at the detected object position
- Moving the robot depending on the object position and depth. We started with simple on-off controllers with deadband on both linear and angular velocity.

At this point, students had reference MATLAB code for a closed-loop vision-based controller with ROS. Over the next few days, they were encouraged to modify this code to make their robots track objects more robustly. Let’s remember that most of the students had never been exposed to MATLAB before!

The robots were fitted with TurtleBot arms. There were two sides to getting these arms working: hardware and software.

On the hardware side, we pointed students to the ROBOTIS Dynamixel servo ROS tutorials. The goal here was to make sure there was a ROS interface to joint position controllers for each of the motors in the robot arm. This would allow us to control the arms with controllers in MATLAB.

On the software side, the steps were:

- Import the robot arm description (URDF) file into MATLAB as a rigid body tree representation
- Become familiar with the Inverse Kinematics (IK) functionality in the Robotics System Toolbox
- Follow a path by using IK at several points — first in simulation and then on the real robot arm

The figure below shows a path that linearly interpolates between points. However, smoother trajectories are also possible with a little more math, or with tools like the Curve Fitting Toolbox.

The workshop days were meant to raise awareness of software tools needed to succeed in the competition. With a stack of ROS tutorials, example MATLAB files, and other useful links, the students were now tasked with taking our reference applications and using them to compete in the same challenges as the major leagues.

These challenges were as follows. Credit to Dr. Tan’s KameRider team for the sample YouTube videos.

**Speech and Person Recognition:**Demonstrating basic speech and vision functionality. An example would be asking the robot “how many people are in front of you?” and getting a correct answer. [Person Video] [ Speech Video]**Help-me-carry:**Following a person and assisting them by carrying an object. [Help-me-carry Video]**Restaurant:**Identifying a person ready to place an order, correctly listening to the order, and retrieving the object that has been ordered [Restaurant Video] [Manipulation Video]**Finals:**Teams can choose freely what to demonstrate, and are evaluated on criteria such as novelty, scientific contribution, presentation, and performance

During this time, students were spending hours digesting workshop material, testing their code, and slowly building up algorithms to clear the challenges.

*Tamagawa Science Club robot during the competition — Courtesy of Dr. Jeffrey Tan*

Some highlights:

- Teams experienced firsthand how to take pieces of code that performed different tasks and integrate them into one working system.
- All teams had complete computer vision and control algorithms with MATLAB, but not all teams had functioning speech detection/synthesis and manipulator control. They found the MATLAB code easier to set up and modify than some of the other ROS based packages, which required knowledge of Python, C++, and/or the Catkin build system to use and modify.
- The two high school teams successfully generated a map of the environment and implemented a navigation algorithm.
- The Nalanda team was able to add obstacle avoidance to their robot using the Vector Field Histogram functionality in Robotics System Toolbox.
- A handful of teams were able to tune some of the pretrained cascade object detector and people detector examples for their person recognition and final challenges.

*KameRider EDU during the Person Recognition challenge — Courtesy of Dr. Jeffrey Tan*

This event was a lot of fun, and as a bonus I enjoyed escaping the cold Boston winter for a few weeks. It was satisfying to see how much the students were able to achieve, and how our conversations evolved, in such a short time frame.

- At the beginning, it was mostly questions about installation, error messages, basic MATLAB and ROS questions, and “how am I going to get all of this done?”.
- Near the end, students had a pretty good understanding of basic ROS constructs (topics, messages, launch files, Catkin, etc.), general programming tools (conditional statements, loops, functions, breakpoints, etc.) and — most importantly — were already asking “what’s next?”

*Workshop in action — Courtesy of Team Nalanda*

The general consensus was that both MATLAB and ROS were needed to make this workshop happen. Implementing and testing algorithms was made accessible by MATLAB, whereas installation of existing ROS packages facilitated some of the necessary low-level sensing and actuation, as well as mapping, capabilities.

- Many ROS packages were easy to set up and could deliver powerful results right away. However, understanding the underlying code and build system to modify or extend these packages was nontrivial for beginners. This is likely because ROS is designed for users comfortable with a rigorous software development process.
- On the other hand, MATLAB needed a single installation at the beginning, required no recompilation, and the sample code (both our workshop files and documentation examples) was determined easy to follow, debug, and modify.

Heramb Modugula (Team Nalanda) remarked that “plenty of time was available to tinker with the robot and example code, and eventually, coding on our own”. His coach and father, Srikant Modugula, highlighted integration of software component as the most critical task. “While MATLAB provides a powerful framework to do robotic vision, motion, and arm related tasks, we look forward to an easier way to connect it with ROS enabled TurtleBot and seamlessly compile/run multiple programs.”

*Computer vision and manipulation at the workshop — Courtesy of Dr. Jeffrey Tan*

To summarize, MATLAB and its associated toolboxes are a complete design tool. This includes a programming language, an interactive desktop environment (IDE), graphical programming environments like Simulink and Stateflow, apps to help with algorithm design and tuning, and standalone code generation tools.

Our recommended approach is to use MATLAB and Simulink for prototyping algorithms that may be a subset of the entire system, and then deploying these algorithms as standalone ROS nodes using automatic code generation. This way, the robot does not rely on the MATLAB environment (and its associated overhead) at competition time. For more information, please refer to our Getting Started with MATLAB, Simulink, and ROS blog post or reach out to us.

*Find the MathWorks logos!*

Our goal is that challenges like these will lower the entry barrier for new teams from around the world to join the RoboCup major leagues and perform competitively in their first year. This will create opportunities for newcomers to become comfortable with robot programming and eventually transition to being “true” major league teams — that is, bringing state-of-the-art algorithms to RoboCup and pushing the boundaries of robotics research worldwide.

For this reason, we will work towards offering this workshop at future events, as well as open-sourcing our materials and posting them online. If you are interested in using this material to learn or teach, or have any thoughts to share, please leave us a comment. We hope to see more of you sign up for future RoboCup@Home Education challenges. Until next time!

]]>Many students I know take issue with Plato’s famous quote: “Students are lazy, disengaged and have bad manners” (The Republic VIII, 562b-563e). Stepping back from the ‘bad manners’ accusation, engaging and effectively teaching bored students can be challenging and the reasons behind haven’t become clear to me for quite some... read more >>

]]>Central to the concept of project-based learning is putting **students** in an **active role**, **encouraging** them **to explore a realistic problem** in an area of interest to them and **without a predefined solution**. This is effective when teaching STEM (science, technology, engineering and math) subjects as it brings theory to life and closely mirrors the problem solving required in science, engineering and math careers. Project-based learning also teaches additional skills such as **team work and critical thinking**, vital for any future career.

Project-based learning environments have **five key features**, addressed below.

All problems start with questions. From where does one draw inspiration for those questions? As you read through your social networks (as you are doing now): what makes you stop and read posts but scroll past others? On the one hand, it depends very much on us as individuals, our social environment and our interests. On the other hand there are topics that have broad appeal, such as **climate change or the soccer world championship**. Mapping that back to our key statement, the logic seems straightforward: identify a “driving question” and hide the key learnings behind it.

I spoke in an earlier post about Formula Student about the importance of student competitions to improve the skill set. This competition also provides an excellent example of how posing a question drives learning. Formula Student is quite complex and as such raises multiple questions; the overarching question set by the organizers is ‘how do teams design and develop a single seat race car, good enough to beat other teams?’ But for students to want to in participate in the year-long event, the question posed to themselves is ‘How do I get the job I want, and differentiate myself from other candidates?’

Another great set of examples comes from LEGO. They are developing fantastic ecosystems around the core education ideas in a department called LEGO education. For example, their content is synchronized with the primary and high school curriculum in many countries such as the UK. They are excellent at **story telling** to create environments for learners of all ages. There is material for learning math in first grade called “MoreToMath” as well as concepts to teach programming and control design “**LEGO Mindstorms**” and many more for the wide range in between.

In high school math, one of the lessons I faced was understanding the concept of imaginary numbers, stating that multiplying a number with itself leads to a negative number: i * i = – 1. It requires abstract thinking and is certainly not straightforward. When I asked our teacher “Why do we need that?” he was unable to answer. Years later, during my mechanical engineering studies, I was exposed again to imaginary numbers in a course covering electric motors.

Had my high school teacher started his lesson with the application of imaginary numbers as it relates to motors, and then progressed to the theory behind them, I would have been much more interested and inclined to learn. When I am showing students software and hardware demos at competition events I usually start on a high level. As soon as I get them “on board” and they recognize their problem, no matter whether it relates to a robot or race car, it is pretty easy to get them involved. Mostly they see the value and start to ask questions about the underlying fundamentals on their own.

Another example is the game commonly known as **Wall Street game**. Students are given an imaginary budget that they can invest in stocks to (hopefully) increase their pot of money. Is there any greater motivation than competing against classmates? Students learn about the stock market, risk and probability. This is also sometimes called the **flipped classroom** – students are engaged through something fun and exciting, before being taught the theory behind it. Tasks should be age appropriate – interesting and exciting to the respective age group.

You may have heard that sharing ideas, exchanging feedback, iterating in a group will lead to better solutions. **Teamwork sounds great, but it’s not an easy task** to get everyone to agree if it does not tie to their objective. A big group with no one taking responsibility for the result might not lead to a great outcome. However, we can’t dispute that complex problems can only be handled in a group and the greater the team collaboration the better the outcome.

Project-based learning is an **ideal approach to teach collaboration and teamwork**: students learn by doing. Of course, at the beginning it often seems harder to work as part of a team, to fight for the best ideas, and to find common ground or to execute things with distributed workforce. The list of potential problems can be extended easily and often seems endless. Subverting these fears and objections is one of the great outcomes that project-based learning can provide. Consider the impact of receiving feedback from someone you admire, whose judgement you trust: this can be a great **reward and a strong motivator** that can only be achieved when working in an open and collaborative way.

Formula Student is a great example that highlights the importance of the project-based learning message. Simply the scale of the project could never be handled without effective collaboration and teams get feedback from people in companies they’d like to work for.

It’s a common problem for teachers: how do you enthuse the disengaged while also challenging and fostering talented individuals? **Project-based learning meets the needs of different learning styles** but also gives students the opportunity to push themselves beyond that demanded by the curriculum. Some might complete the project at its most basic level, but others, when faced with a challenge that interests them, will push themselves above and beyond, thus evolving their learning further.

At nation-wide finals, selected participants of the German science competition Jugend forscht display their projects. Jugend forscht allows young researchers between the age of 15 and 21 years to compete in subject areas such as mathematics / computer sciences, physics or technics. Some of their submissions are fantastic examples of what teenagers are able to achieve when they’re inspired and challenged. As an example, the winning team in the computer science branch used statistics and numerical models to compute light scatter creating realistic images of diamonds. The contest also featured robots moving on one leg and some able to solve Sudoku grids. What these projects all have in common: they go far beyond what is taught in school and the kids participating are passionate about the work.

Source: Bundeswettbewerb Jugend forscht 2015 bei BASF , by BASF (CC BY-NC-ND 2.0)

What is the motivator driving you to succeed? Is it the recognition from others or a sense of personal achievement? For some it might be **money, a valuable prize or a job opportunity**. For many, it’s having something tangible to show at the end of the class or day of work.

Whatever the personal motivator is, this reward encourages people to push themselves. Consider the primary school students tasked with programming a robot and the sense of achievement at completing the task as part of a team. Compare that with the university teams competing a Formula Student; at the end of the year-long project they have a single seat race car to show for their efforts, strong job prospects and (hopefully) a prize from the event itself. **Having something tangible to show for their efforts drives people and thus their learning**.

Teaching methodologies need to **support different learning approaches** as well as **inspiring and engaging students**. Project-based learning, incorporating the five columns above, is an effective way to achieve this. By getting **students working hands-on**, they **explore real-world problems and bring theory to life**. Key to the success are projects that are fun and inspiring for students – they can work on applications ranging from robotics to signal processing to control systems. In doing so, they’re also learning approaches and skills that are relevant to their future careers. I welcome your thoughts on project-based learning, either from your own experiences, or questions you might have.

Reference:

[1] The textbook The Cambridge Handbook of the Learning Sciences includes a nice chapter authored by J.S. Krajcik and P.S. Blumenfeld which discusses the concept.

Introduction This blog post intends to provide best practices for choosing solvers in Simulink and Simscape. Gratitude goes to Tom Egel and Erin McGarrity whose materials are the foundation for anything written below. This article is certainly not aiming to replace the rock-solid documentation about solver choice, it is complementary and... read more >>

]]>This blog post intends to provide best practices for choosing solvers in Simulink and Simscape. Gratitude goes to Tom Egel and Erin McGarrity whose materials are the foundation for anything written below. This article is certainly not aiming to replace the rock-solid documentation about solver choice, it is complementary and written for folks who:

- want to speed up simulations and increase accuracy,
- need a better understanding of the numerics involved.

This article will firstly talk about solver classification and naming, and secondly mention practical aspects about finding the optimal solver for your application and working around common mistakes. Simscape will not (yet) be covered specifically. Feel encouraged to leave a note in the comments section at the bottom if you are particularly interested in troubleshooting Simscape models.

This introduction may trigger two kinds of reactions:

*“***I want to know more!**”-> Find here a

**Solver Workshop on FileExchange**which is a hands-on deep dive into solver know-how including example models, slides and exercises.*“***I don’t want to invest time into solver choice!**”

-> I suggest having a look into**auto solver**, a**feature**that was added in release 2015a. It will choose an appropriate solver for your model automatically.

This example of a **Foucault pendulum **(Link -> *foucaultPendulum.slx*) illustrates why solver choice is key! Depending on the solver choice ode45 (default) or ode23t, results of the pendulum displacements will be entirely different. As can be seen in the plots, ode23t leads to more meaningful results since the displacements should be symmetric. Sometimes, errors won’t be as obvious. My PhD supervisor typically said when discussing modeling strategies “Christoph, all models are wrong, but some of them are useful.” In the following, let’s try to make sure that simulation results will be useful.

Open and run the model *“foucaultPendulum.slx”* in the solver workshop on FileExchange to experience the illustrated solver behavior. Before talking about model stiffness which lead to the significant result deviations in the example above, let’s do the groundwork first and see what Simulink / Simscape solvers there are and how they can be classified.

**Names and their Meaning**

The most important info is carried by the solver names themselves. A single digit number represents a fixed-step solver, the number itself gives info about the order. Information on the integration scheme can also be obtained from the name. Solvers using an implicit scheme always come with an amended letter, explicit solvers only have the number. The amendment letters are abbreviations: “t” trapezoidal, “tb” trapezoidal-backward, “s” stiff and “x” extrapolation. If there is no amendment, that’s an explicit solver.

**Classification**

MathWorks solvers can be classified into 4 categories:

*Step Size – Order – State Updates – Integration Scheme.*

*Step Size*

Fixed-step solvers are typically used for to meet accuracy requirements and are used when models will be deployed onto hardware such as microcontrollers (keyword: code generation). Variable step solvers automatically change the time step to meet requirements. They are typically used for plant model development. A variable-step solver might shorten the simulation time of your model significantly.

This model shows how a variable-step solver can shorten simulation time for a multi-rate discrete model. The model generates outputs at two different rates: every 0.5 s and every 0.75 s. To capture both outputs, the fixed-step solver must take a time step every 0.25 s (the *fundamental sample time* for the model).

*Order*

As mentioned before, the numbers used in the solver name specify the solver order. Choice of order has an impact on accuracy. Most often, a high-order solver is more efficient than a low-order solver. Variable-order solvers use multiple orders to solve the system of equations. For example, the implicit, variable-step ode15s solver uses first-order through fifth-order equations while the explicit, variable-step ode113 solver uses first-order through thirteenth-order. Solver’s **step size** and **integration order **have a huge impact on accuracy. In my mind, the simplest way of explaining is the following:

- Smaller step size and higher solver order both increase accuracy
- More accuracy is slower (at least for a fixed-step solver)

*State Updates: Discrete vs. Continuous*

Discrete and continuous solvers rely on the model blocks to compute the values of any discrete states. Blocks that define discrete states are responsible for computing the values of those states at each time step. However, unlike discrete solvers, continuous solvers use numerical integration to compute the continuous states that the blocks define.

If your model has no continuous states, then Simulink switches to either the fixed-step discrete solver or the variable-step discrete solver. If your model has only continuous states or a mix of continuous and discrete states, choose a continuous solver from the remaining solver choices based on the dynamics of your model. Otherwise, an error occurs.

*Integration Scheme: Explicit vs. Implicit*

Explicit solvers use past information in the equations to compute next step. This is computationally simple but unstable as the system equations won’t be solved completely at any time. Instability is not necessary a problem because everything will be fine if the approximated solution is still within your desired margin of error. Implicit Solvers compute next steps self-consistently which is more computational work per step.

While you can apply an implicit or explicit continuous solver to solve all these systems, implicit solvers are designed specifically for solving stiff problems. Explicit solvers solve non-stiff problems. An ordinary differential equation problem is said to be stiff if the desired solution varies slowly, but there are closer solutions that vary rapidly. In short, one could say: a stiff system has both slowly and quickly varying continuous dynamics. The numerical method must then take small time steps to solve the system. Stiffness is an efficiency issue. The more stiff a system, the longer it takes to for the explicit solver to perform a computation. For example, most of the physical models built using the Simscape product family end up being stiff systems, in which case you would want to make sure you choose between stiff solvers.

**Solver Choice**

When you build and simulate a model, you can choose either type of solver based on the dynamics of the model. A model that contains several switches, like an inverter power system, needs a fixed-step solver. A variable-step solver is better suited for purely continuous models, like the dynamics of a mass spring damper system.

When you deploy a model as generated code, you can use only a fixed-step solver. If you selected a variable-step solver during simulation, use it to calculate the step size required for the fixed-step solver that you need at deployment.

**Zero-Crossings**

Note: This is relevant if you have chosen a variable step solver only.

A variable-step solver dynamically adjusts the time step size, causing it to increase when a variable is changing slowly and to decrease when the variable changes rapidly. Thus, the solver takes many small steps near a discontinuity, e.g. a zero-crossing. Zero crossing events may be sign changes or hard stops. Overall, this behavior improves accuracy but can lead to excessive simulation times.

Knowing that zero-crossing may slow your model down is already a major part of the solution. Find here a list of possible remedies:

- Adjust the zero-crossing options

(Configuration parameters -> Additional options)- Increase number of consecutive zero crossings
- Switch to the adaptive algorithm
- Relax signal threshold
- Disable detection for specific blocks, see documentation

- Modify the model and reduce constraints

This is not just a setting, let me refer you to the solver workshop (FEX) for a hands-on example.

**Algebraic Loops**

An algebraic loop generally occurs when an input port with direct feedthrough is driven by the output of the same block, either directly, or by a feedback path through other blocks with direct feedthrough. Thus, the solver is forced to use iterative methods which is slow (!).

The best remedy is to avoid algebraic loops if possible, find a chapter helping you in the documentation or have a look at the solver workshop (FEX) introduced before.

This article is by no means complete nor is it the only publication about this topic. Same as for models that should be useful, I hope this text helps you in your daily work with Simulink. Feel encouraged to comment and suggest improvements or clarification.

Cheers Christoph

]]>

Ka.Race.Ing-Team at Karlsruhe Institute of Technology volunteered to share in depth and hands-on their approach around vehicle controls and torque vectoring in particular. They are winners of the Simulink Student Challenge 2016. And to top it all off, Julian our guest blogger today, added two of their models on the MATLAB... read more >>

]]>– – –

In recent years of electric of Formula Student, control systems have gained importance. The impact of well-tuned torque vectoring and traction control systems is comparable to a weight reduction of 10kg. However, it doesn’t come without cost to develop such a system. This introduction aims to give you an overview of where to start and to summarize your options. Developing the control system in Simulink has a lot of advantages. You do not need to be an expert programmer, it is easy to understand for others (and the poor team member who has the job in the next season). What is most important: you can use built-in MATLAB functions.

The hardware you use can be very different. Boundary conditions for the processing unit are:

- It must be capable of the data interface, which is used in the car. In most cases that is the CAN-BUS. The computational power must be sufficient.
- There must be a possibility to compile the Simulink model for the unit.
- For telemetry, the hardware should be connected to a radio interface, for example a LAN adapter in combination with a WLAN router.

An example we are considering is the Flea3 by CarMedialab. The C2000 family by Texas Instruments is also worthy to mention. Find here a Racing Lounge blog post for an application of this type of board. Or, you can even use a Raspberry Pi for the job.

A complicated but powerful approach involved systems on a chip (SoC) involving an FPGA. Find here an example from Avnet. The Racing Lounge video podcast also has addressed this topic, showing how to implement a Simulink model on a Xilinx Zynq 7000. With this hardware, you have the possibility to use a FPGA, which is relatively complicated and not necessary at least for a first attempt.

As you can see, there are a lot of possible control units, while the way of implementing your Simulink model differs depending on the hardware. For a first attempt, it can be good to use a Simulink model which directly takes the data from the CAN-BUS. Later I would recommend exporting the Simulink model with Simulink Coder and implement it in another control unit Software, which is also able to use telemetry data. This way, you can quickly change parameters without re-flashing. That saves a lot of test time.

__Mandatory Sensors:__**Steering angle sensor**

The most important sensor for the torque vectoring model. Steering angle is important for defining target value, such as target yaw moment (well, that is one option) but also for calculating a vehicle model.**Throttle pedal sensor**

This input has to be used to determine the longitudinal acceleration of the car. One has several options here: Either, it can be proportional to a sum of motor torques, factorized by a torque ratio, calculated by the torque vectoring system. Alternatively, the input is proportional to a target longitudinal acceleration as input for the torque vectoring.**Brake pressure sensor**

The brake pressure is needed to determine whether the motor torques work against the brakes. Then the torque must be reduced or set to zero. Therefore, it is good to know which torque is distributed from the brakes, dependent on brake pressure.**Electrical brake sensor**

There are two options for recuperation sensors. You can use a spring and a sensor comparable to your throttle pedal sensor. Alternatively, you can use a sensor which measures the force the driver distributes on the pedal. Most drivers prefer the second option, but it is more complicated to implement. Again, you must consider which variable is varied in your control model.**Motor rotational speed encoders**

These are very important for traction control and some other calculations. There is no need of extra wheel speed sensors. Taking the gear ratio into account is absolutely enough.**Battery voltage and battery current**

Limiting Power to 80 kW can be done by a controller. For that you need the current power. These sensors can also be interesting for different recuperation strategies.

__Optional Sensors:__**Inertial measurement unit**(IMU)

Although not mandatory, an IMU is very important for a good control system. It contains at least an acceleration sensor and a gyroscope. Wheel loads can be calculated using accelerations. Yaw rate is a very important quantity which is calculated from the gyroscope data. For calculating an own reference speed (which doesn’t come for free in 4WD cars), it is mandatory. If you do not have the possibility to develop an IMU on your own, take an existing one and adapt a CAN interface on it, such as in that example.**GPS**

Not necessary for the control system if you do not want to calculate a reference speed on your own. If you want to calculate a reference speed a differential GPS (dGPS) is the better way.**Push- / pullrod load cell or strain gauge**

This is nice to have not only for your wheel loads in your control system, but also for other validations on your car. However, especially strain gauges are hard to implement. Normally it is also enough to calculate wheel loads using IMU data.**Optical speed sensor**

If you can manage to get an optical speed sensor, e.g. Kistler Correvit, for reference speed and side slip angle as a sponsoring, do not hesitate. Alternatives are GeneSys ADMA and VBOX Speed Sensors.

Most of the data you get from your sensors is noisy. For further implementations, filtering is required. Mostly, a low-pass filter is the best choice. You can decide between a finite impulse response (FIR) filter, which is a moving average, or an infinite impulse response (IIR) filter. Moving average works for us perfectly for steering angle, gyroscope data, and wheel speeds. There is no need for more advanced filters. However, make sure you take phase shift into account, which can have huge effects. Custom filters can be designed, which could look like this for a FIR filter:

FIR-Filter

Another possibility is to use low-pass filter blocks from Simulink.

Differentiating noisy signals requires more computational effort . Finite difference methods such as difference quotient or central differencing scheme (preferred) work well and almost without phase shifts. On the downside, these filters also work as high-pass filters and hence increase noise. For example, a MATLAB implementation of central differencing looks like this:

diff_central = (f-f2)/(2*dt); % f : value to be differentiated % f2: value of the second last time step % dt: duration of one time step

We have been using this slightly more complicated differentiating method for real time applications. For us, it works very well with small phase shifts and low noise. For steering angle, we were even able to calculate the second derivative (orange) basically without noise. You can also see the first derivative calculated with difference quotient method (yellow) and with the filter (blue). Find here a link to the model on File Exchange: Real time derivation filter.

Steering angle time signal; calculated first and second derivative

The system implements the resulting formulae of the paper. It calculates the derivatives without the use of loops. The needed inputs are the signal to derive and the duration of the (fixed) time step.

Kistler Correvit system installed on race-car

If you managed to get an optical sensor from Kistler you will not have any problems at this point.

All others must face a difficult issue. The problem is clear: A four-wheel driven car cannot take solely wheel speed data to calculate a reference speed, because all four wheels have slip. Side slip angle cannot be directly measured.

In the beginning, you may take only GPS reference speed or built up a reference speed estimator based on wheel speeds and integrated longitudinal acceleration data and assume the side slip angle to be zero. But you will notice the limits of such systems after a short time.

To manage this, some complex data fusion must be done to calculate both reference speed and side slip angle. One attempt is to use neural networks. The problem here is that you already need a lot of data with measured reference speed and side slip angle (e.g., from an optical sensor) to train the network. Furthermore, the system will differ dependent on the car, which means that you will not be able to use it every season. Another possibility is to do data fusion based on an extended Kalman filter. An introduction to Kalman filters can be found here.

The extended Kalman filter does not need measured data and can be adapted on car parameters, but it will be heavy to let it work as good as a neural network. It is very important to have a detailed update matrix, describing the whole two-dimensional vehicle dynamics. More sensors make the Kalman filter more accurate. One idea would be to take wheel speeds, IMU data and GPS position.

Validation of such systems is still heavy without being able to measure reference speed and side slip angle. So, I suggest investing some effort in getting an optical sensor.

Another major and often underestimated topic in race-car control system design is power management.

One part of it is recuperation. The maximum recuperation torque must be limited concerning battery voltage. While the car is braking, battery voltage increases because of the internal resistance of the battery cells. When beginning to drive, the battery usually is fully charged. Hence, it is impossible to use the maximum recuperation current as the battery voltage can go above the maximum value. Therefore, you need to slightly increase recuperation power at the beginning of endurance. One way to do that is to integrate the used electrical power. Then you can multiply it with a factor and get the slightly increasing maximum of recuperation power. If the recuperation power is at recuperation current maximum, it stops to increase. Find here a link to the model on File Exchange: EV recuperation limitation -> “recup.slx”. Surprisingly, this (simple) system works very well.

Another possibility is to build up a battery model. Based on an equivalent circuit model for your cells, it is possible to predict the increase of voltage, dependent on recuperation current. This approach allows to determine which recuperation current can be used in maximum to reach exactly the maximum voltage of your cells. This video shows how to build up a battery model.

Building up a battery model is not easy, and the advantages compared to other systems is difficult to measure. However, it shows you how your battery works and there is a huge interest in design event. For both systems, I would strongly recommend implementing a controller, which hardly reduces battery current when you get over your maximum battery voltage. In our case a simple propoertional controller did the job.

Now, you know your maximum (and maximum negative) electrical power measured by the energy meter. With a loss model of power electronics, your motors and gears, it is possible to calculate the maximum mechanical power. With the current wheel speeds (which do not differ too much between the time steps) a maximum sum of motor torques can be calculated. The torque vectoring system then distributes this sum. It is also possible to limit the torques after the torque vectoring system, while not changing the torque ratio.The choice depends on the torque vectoring.

This is a feed-forward system for the power management. The target is to get as near as possible to 80kW while not violating the rules. If you get over your maximum power with this system, it is also possible to adapt the maximum limit with a controller. Again, a simple P controller can be a first attempt.

During endurance, you will not be able to drive with 80 kW all the time. For that, the maximum power can be adapted. Most teams just set a new maximum (e.g. 50 kW) and drive through endurance with this new limit. A more advanced method is to accelerate with more power and limit it when reaching a certain speed.

Torque vectoring makes your car fast!

Our car for example is roughly 0.4 seconds faster in skidpad with torque vectoring.

This is done in two ways: Firstly, torque vectoring can stabilize the vehicle or make it more agile. This is comparable to an ESP. Secondly, it enhances the vehicle’s grip during cornering. How this works is shown in this video.

A simple attempt, which is easy to test in the beginning, is this one: Set a constant front / rear torque distribution and calculate a left right distribution ratio on proportional to the steering angle. Even this simple system can decrease lap time significantly, when it is setup up appropriate.

Other, more advanced, systems always have (as far as I know) a layout like this:

The driver’s inputs, which are steering angle and throttle pedal position, must be translated into variables that can be used in vehicle dynamics calculations. These are a target yaw moment and a desired longitudinal acceleration or sum of motor torques. The desired acceleration is just set proportional to the throttle pedal. Yaw moment is more complicated. An often used and well-known attempt is to apply a yaw rate controller, which sets the target yaw moment. The target yaw rate can be calculated from Ackermann geometry or optimizations on a steady state vehicle model. A yaw rate controller is especially suitable for inexperienced drivers who are not used to a vehicle swinging off. More experienced drivers sometimes feel limited when driving with a yaw rate controller. For them you can use an easier approach: just set the yaw moment proportional to steering angle and its derivative. And there are a lot more possibilities to do that. If torque distribution properly sets the yaw moment, one has a more agile or more stable car, depending on the driving situation. The task for torque distribution is to fulfill the driver’s targets, while maximizing lateral acceleration simultaneously. This calculation should be based on a double track vehicle model. Again, there are a lot of options, how to do that. The optimization can be done in real time on the vehicle, going from tire to tire and increasing its load to the maximum. Another possibility is to optimize steer angle and motor torques offline on a steady state vehicle model and put them into the Simulink model as a lookup table.

For testing of suspension and aerodynamics it should be possible to turn off torque vectoring and use the same torque on the left and right track.

This picture shows a control system without traction control. Right after the torque vectoring system, the torques are sent from the control unit to the power electronics. When the driver pushes the throttle fully from standing, the torque vectoring sets (if there is no feedforward in torque vectoring system) motor torques to 100 percent. The power electronics will control the current given from a motor map and wheels will start to spin. That is why we need traction control.

It is still a good idea to have a switch on the steering wheel for powering off traction control. For example, if you are testing a new torque vectoring system, traction control changing torques all the time isn’t actually desired. Let your driver review your traction control with a comparison between driving with it and without it. Does it limit the torque too much?

For traction control you need to add two more systems: tire model and speed controller. The tire model is needed to calculate your target slip from the torques, this is also called an “inverse tire model”, because normally a tire model works in the other direction: from slip to force/torque. This inversion is easier to do with TMeasy than with a Pacejka model. Find here a video on tire modelling.

**[VIDEO] **MATLAB and Simulink Racing Lounge “MATLAB and Simulink Racing Lounge: Tire Modeling; Extracting Results from a Large Data Set“

Notice that your tire forces are highly dependent on wheel loads. Your calculation (or measurement) for that should be precise. However, if you really do not have time for building up a tire model, you can also use a linear approach between slip and force/torque.

With your current reference speed and yaw rate you can calculate your tire’s mass point velocity. By adding slip, you have calculated the target wheel speeds.

Now there are normally two possibilities. Most power electronics have an implemented speed controller. You can take that one (speed controlled), or built up another speed controller in your main control system which only begins to control, when a slip is measured, which is higher than your maximum target slip. This is called torque controlled.

At first it is easier to drive torque controlled. Real torques do not vary too much from the target torques, which means that you can be sure faults can be found in the torque vectoring system. A good reference speed is not as important as in a speed controlled system. As a speed controller, I would recommend a PI controller with some kind of anti-windup.

However, a speed controller which is not running on the power electronics will always be worse: The power electronics is directly connected to the motor’s rotational speed encoders. In this way, the controller can reach a much higher frequency and is much more precise.

There are some other problems you must consider:

Reference speed and slip can be noisy. So, your target wheel speed will be noisy too. What happens if you do not push the throttle? Most power electronics can limit their speed controller output to a certain torque, which you can send via CAN too. It is also a very good idea to use that for power limitation.

Another problem is that most of the speed controllers on power electronics are also PI controllers, which have a huge offset between target speed and measured speed, when using them in such a dynamic process like speed controlling. This means if you want to get the same torque output as in torque controlled mode, you may have to add an offset on the target speed. These offsets must be adapted such that you get out the same torque from the speed controller as it is calculated in torque vectoring when you are not driving at the tire’s maximum.

I hope you find our reasoning a little helpful.

Greetings from Karlsruhe with a very noisy “POWER FUEL!”

Best, Julian

]]>Sebastian Castro is back to talk about the basics of connecting MATLAB and Simulink with the Robot Operating System (ROS). Overview Robot Operating System (or ROS) is a commonly used framework for designing complex robotic systems. It is popular for building distributed robot software systems, as well as for its integration with packages... read more >>

]]>Robot Operating System (or ROS) is a commonly used framework for designing complex robotic systems. It is popular for building distributed robot software systems, as well as for its integration with packages for simulation, visualization, robotics algorithms, and more. ROS has become increasingly popular in industry as well, especially in the development of autonomous vehicles.

As of R2015a, Robotics System Toolbox has equipped MATLAB and Simulink with an official interface to ROS. This interface lets you:

- Connect to ROS from any operating system supported by MATLAB and Simulink
- Leverage built-in functionality in MathWorks toolboxes – for example, control systems, computer vision, machine learning, signal processing, and state machine design
- Automatically generate standalone C++ based ROS nodes from algorithms designed in MATLAB and Simulink

In summary, MATLAB and Simulink can coexist with your ROS based workflow via desktop prototyping, deployment of standalone ROS nodes, or both. If you are looking to design even one small component of your system in MATLAB and Simulink, keep reading!

Robotics System Toolbox provides an interface for MATLAB scripting and desktop prototyping with ROS. This includes functionality for:

- Starting or connecting to a ROS master
- Working with topics (publish/subscribe), services, actions, and the parameter server
- Reading specialized messages (e.g., images, lidar scans, point clouds, and occupancy grids)

A simple MATLAB code snippet for a publish and subscribe based control algorithm looks as follows.

In the example above, the algorithm is managed using a while-loop, which means the loop iterations are processed as quickly as possible. There are a few additional ways to schedule the execution of MATLAB code.

**Rates:**You can use Rate and rosrate to slow down the control loop based on the CPU wall clock or the ROS master clock, respectively.**Timers:**Creating MATLAB timer objects lets you schedule function calls on different schedules without blocking. This means you can have multiple timers running in the background while still having access to the MATLAB command window.

**NOTE:** All the code running in timers and ROS subscriber callbacks will execute within a single thread, since the MATLAB environment is single-threaded to users (although several built-in functions use multithreading internally).

For more information on the MATLAB interface to ROS, watch the following video.

[VIDEO] MATLAB and Simulink Robotics Arena: Getting Started with MATLAB and ROS

Robotics System Toolbox also includes a Simulink block library for ROS connectivity. This includes functionality for:

- Working with topics (publish/subscribe) and the parameter server
- Representing ROS messages as Simulink bus signals for graphical programming
- Reading specialized messages (e.g., images and point clouds)

With Simulink, you can take advantage of block sample times and rate transitions to build multirate algorithms, as shown below.

Another benefit of the Simulink is the ability to combine MATLAB, Simulink, and Stateflow modeling language for different algorithm components.

**MATLAB**code is good for components best expressed with textual programming, such as array/matrix operations and machine learning. If you have algorithms written in MATLAB, you can call them in Simulink using MATLAB Function blocks.**Simulink**blocks are good for control algorithms, which are usually expressed as block diagrams. You can also take advantage of built-in block libraries for signal processing, computer vision, robotics algorithms, and more.**Stateflow**charts are good for decision-based logic, state machines, tabular logic, and time-based or event-based scheduling.

For more information on the Simulink interface to ROS, watch the following video.

[VIDEO] MATLAB and Simulink Robotics Arena: Getting Started with Simulink and ROS

We discussed how MATLAB and Simulink can help you design and verify robotics algorithms from your desktop. Even if your robot’s onboard computer meets the requirements to install and run MATLAB, you probably don’t need the overhead of these design and verification tools on the final system. On the other hand, installing MATLAB is completely out of the question for low-cost ROS enabled platforms such as Raspberry Pi.

As you transition to your final implementation, you could manually port the MATLAB and Simulink prototype algorithms to work on your robot. Alternatively, you could consider automating this process with code generation. This can speed up the development process and remove manual implementation errors.

The two code generation approaches are:

**Generate reusable code:**Use MATLAB Coder, Simulink Coder, and Embedded Coder to generate standalone C/C++ files or libraries from MATLAB files and Simulink models. This approach is flexible, in that you can integrate the generated code with any framework you may already have in place, but it still involves some manual effort to get running.**Generate ROS nodes**: With Robotics System Toolbox, you can directly generate C++ based ROS nodes from Simulink models (and recall that MATLAB code can be called from Simulink models). Compared to the previous approach, which generates entry points to your algorithm, this generated code will also include ROS functionality (publishing, subscribing, etc.) and algorithm scheduling based on the sample times specified in the model.

The ROS node generation approach can also automate the process beyond generating code, as shown below. This includes moving files into the target system’s, compiling the files using the catkin build system, and running the generated executable node.

Once you’ve generated a ROS node from Simulink, there are a few ways you can work with it.

- Start and stop the node from MATLAB using rosdevice, or run it directly from your ROS machine by finding the generated executable or using the rosrun
- Use External mode to tune parameters and visualize data directly in the Simulink model, even though the code itself is running on the target computer. The code will be generated with a TCP/IP interface to your Simulink model running on the desktop. While this has some processing overhead, it can be a good debugging step while you are still designing your algorithm.
- Configure your algorithm to send or receive ROS messages or values in the parameter server. This lets you interact with the deployed node from MATLAB, Simulink, or other ROS nodes and the terminal on your target machine.

For more information on deploying algorithms as standalone ROS nodes, and using the deployed nodes, watch the following videos.

__MATLAB and Simulink Robotics Arena: Deploying Algorithms to ROS
__

You have seen an overview of how algorithms can be prototyped in MATLAB and Simulink, and how they can then become standalone C++ based ROS nodes. If you’d like to know more, leave us a comment or post on our Facebook group.

You can download the templates and examples shown in the videos from the MATLAB Central File Exchange. The virtual machine used in the examples can be downloaded from the MathWorks Web site.

– Sebastian

*An example of MATLAB and Simulink interfacing with ROS, as shown by the ROS utility rqt_graph.*

In today’s blog post I am happy to introduce Ed Marquez Brunal, a first-time guest in this blog. This is a holistic summary of our project on modeling vehicles. Find 4 videos and 2 MATLAB Central File Exchange submissions, including anything you may need to get started, linked in the... read more >>

]]>– – –

If you are part of an automotive competition these days, you’ve probably heard about “vehicle modeling”. But before I tell you more about vehicle modeling and its advantages, let’s briefly see how the term “model” has evolved since the adoption of Model-Based Design in the automotive industry.

When people said “vehicle model” in the early 90’s, what came to mind was most likely a car prototype that was very expensive, highly complex, and hard to build. Engineers had to drive, and sometimes break, the so called “vehicle model” of the early 90’s to gather data. Just imagine the pain of these engineers spending tons of time and money building a prototype that they had to break to figure out what was wrong with it!

Today, most people would associate the term “vehicle model” with a computer representation that can be simulated under certain scenarios. Now you may be wondering, why did automotive engineers and students go from building prototypes to working on a computer? Well, it is fun to build the better product that meet specs, and saving time and money is the added benefit.

Let’s talk more about some of the other advantages of vehicle modeling in the next section. But before that, be sure to check our Simulink based models and Simscape Multibody model in File Exchange.

That’s right! Some advantages of vehicle modeling are that the final product can be built faster, it can be better (in terms of engineering requirements), and all while reducing cost. Sounds too good to be true? Let me explain.

Building and simulating a vehicle model enables the engineers to analyze several powertrain configurations and determine if requirements are met for each design. If engineering requirements are not met by a powertrain configuration, it is much easier to change a parameter in a computer model than it is to make a change to a vehicle prototype that is already built. For example, it is easy to change the power rating of an electric motor in a computer model, but we know it can be challenging to swap motors in a real vehicle.

Another advantage of vehicle modeling is that the engineers can study the performance and energy consumptions aspects of a powertrain configuration from a vehicle model. Finally, let’s not forget that running computer simulation is faster and more cost effective than building and driving an actual vehicle prototype (90’s model).

If you are interested in seeing some student success stories, be sure to check out the series page: Formula Student Teams Share Their Keys to Success.

Alright, this vehicle modeling stuff sounds great! But, how can you get started?

We have created instructional videos, vehicle models, and guidelines for when to use each tool. There is no right or wrong choice here. In fact, you can combine these tools in your models to get the best out of all worlds. However, a clever way to proceed is to think about what tool will fit your needs best before you build your model. For instance: if you are in initial stages of you design, consider Simulink or Simscape. Conversely, consider an alternative like Powertrain Blockset for fine-tuning of your model. An important consideration is that Simulink serves as the foundational platform for all the tools we will cover below.

Simulink is a graphical programming environment for modeling, simulating, and analyzing dynamic systems. Consider Simulink for vehicle modeling if you:

- Want to get started with vehicle modeling
- Seek simplicity and speed for your models
- Have equations describing a system

If you are interested in doing some hardware testing and deployment at later stages of your development process, you can leverage the automated code generation capabilities that Simulink provides. Yes, you can go from a Simulink model to C/C++ code that can be executed by hardware platforms and/or simulators. In fact, all products that we cover in this section support code generation with the appropriate settings. For more details, please refer to Jose’s blog post. For demos and more information on Simulink, please see Part 1 of our 4-video series on vehicle modeling.

[Video] MATLAB and Simulink Racing Lounge: Vehicle Modeling, Part 1: Simulink

Powertrain Blockset is an add-on that expands Simulink capabilities for vehicle modeling, and it is great for parameterizing plant models using test data.

Powertrain Blockset implements a data-driven approach. Consider Powertrain Blockset if you:

- Want well-documented, open, and reconfigurable models
- Have access to vehicle parameters and test data
- Seek to maintain or increase model fidelity with fewer blocks (compared to Simulink)

For details and demos on Powertrain Blockset, please check out Part 2 of our 4-video series on vehicle modeling.

[Video] MATLAB and Simulink Racing Lounge: Vehicle Modeling, Part 2: Powertrain Blockset

Simscape is the MathWorks language of physical modeling. This tool provides the ability to model multidomain systems. An important aspect of Simscape is that the connections between components are bidirectional, and these physical connections also have units.

Consider Simscape for vehicle modeling if you:

- Use blocks that implement system equations for you
- Reduce visual complexity of a Simulink model
- Model and integrate different domains in a system

For demos and more details on Simscape, please see Part 3 of our 4-video series on vehicle modeling. Also, if you want to use Simscape, I recommend our Student Competition Training on physical modeling as a prerequisite.

[Video] MATLAB and Simulink Racing Lounge: Vehicle Modeling, Part 3: Simscape

Simscape Multibody allows to simulate 3D rigid body dynamics of a system, while providing a 3D animation of the system response. In vehicle modeling, the power of Simscape Multibody can be leveraged to simulate and visualize system dynamics. It can also be used to optimize a design, like a suspension – check the episode on Design Optimization for more details. Last but not least, Simscape Multibody is helpful for modeling wheel-to-ground contact, see racing lounge blog post “Introduction to Contact Modeling“.

Consider Simscape Multibody for vehicle modeling if you:

- Need to model a mechanical system in 3D
- Need a 3D visualization of the system response
- Need to perform system-level analysis
- Need to model wheel-to-ground contact

For your convenience, we put together a 3D vehicle model demo using Simscape Multibody. For more details on the demo, be sure to download the MATLAB Central File Exchange entry (link in introduction). For more details on the demo interface and Simscape Multibody, please check our Part 4 or our 4-video series on vehicle modeling.

[Video] MATLAB and Simulink Racing Lounge: Vehicle Modeling, Part 4: Simscape Multibody

If there is one thing to remember from today’s blog is that computational vehicle modeling offers the potential to produce a better final product in a faster and more cost-effective manner. This is possible because of the benefits that computer models and simulations offer over physical prototypes. Some of these benefits include:Conclusion

- Ability to analyze several powertrain configurations
- Ability to determine if requirements are met for each design
- Flexibility to quickly change design parameters in a computer model
- Faster computer simulations vs actual track tests
- Cost effective simulations vs expensive prototype tests

We also introduced four powerful MathWorks products to model vehicle systems. Namely, these products are: Simulink®, Powertrain Blockset™, Simscape™, and Simscape Multibody™. An important idea to remember is that there is no right or wrong choice here. You can combine these tools in your models to get the best of all worlds, but be wise and thoughtful when choosing how to develop your models. To make this easier for you, we also provided some guidelines for when to use what product.

Now that you know the advantages of vehicle modeling with MathWorks tools, and you also know the available options to create your models, it is time to get started and have fun! Let us know how things are going as well as your questions.

]]>

Today, my robotics colleague Sebastian Castro is back for another guest blog. Before handing it over to Sebastian allow me a short note. My colleague Steve Eddins recently started a second blog on MATLAB Central, this one about Deep Learning. If you are interested in learning more about Deep Learning please visit his Deep... read more >>

]]>Before handing it over to Sebastian allow me a short note. My colleague Steve Eddins recently started a second blog on MATLAB Central, this one about Deep Learning. If you are interested in learning more about Deep Learning please visit his Deep Learning Blog and Subscribe. Enjoy!

– – –

In this post, I will discuss robot modeling and simulation with Simulink®, Simscape™, and Simscape Multibody™. To put things in context, I will *walk* you through a walking robot example (get it?).

First of all… why simulate? I’ve broken down the benefits into two categories.

**Safety:**Robots will fall. Prototypes will break. You can verify that controls algorithms are at a good starting point in simulation before moving to hardware. Simulation lets you test your robot and controller design under multiple scenarios without building prototypes. In simulation, you also get the benefit of intentionally generating unsafe conditions, as well as discovering unexpected issues.**Efficiency:**Physical experiments take time and effort to set up and reset between runs. With simulation, you get a programmatic environment to automate experiments and walk away from your desk. If your robot is controlled by an embedded system, simulation lets you test algorithm changes without having to port and rebuild the code on hardware every time. This separation of algorithm and implementation can also help you determine whether new issues are due to algorithm changes or physical limitations.

We will now look at a typical robot simulation architecture, which consists of multiple layers. Depending on your goals, you may only need to implement a subset of these for your simulation.

Simscape Multibody lets you model the 3D rigid body mechanics of your robot. There are two ways to do this.

**Build from scratch:**It may take some initial time to build a model from scratch. However, if set up correctly, you can easily change properties such as dimensions, cross-sections, masses, etc. If you are still in the conceptual design phase, this can be useful as you sweep through different parameters and validate your design.**Import from CAD:**Useful if you have already created a robot model and want to simulate its dynamics using more realistic geometric and inertial properties. So long as the kinematics of the CAD model remain the same, you can make changes in CAD and reimport the parameters into your model. For more information, look at our blog post on importing CAD assemblies.

Regardless of how you create the robot model, the next step is to add dynamics to it.

**Internal mechanics:**Every Joint block (translational or rotational) in the model can be assigned mechanical stiffness, damping, and initial conditions.**External mechanics:**First, you can set up the direction and magnitude of gravity. Equally important for legged robots, you need to model contact with the ground. We discuss this in more detail in our contact modeling blog post.

For more information on modeling the 3D rigid body mechanics of a walking robot, check out the video below.

**[Video] **MATLAB and Simulink Robotics Arena: Walking Robots, Part 1: Modeling and Simulation

As shown in the simulation architecture diagram earlier, the actuator is the “glue” between the algorithm and the model (or robot). Actuator modeling consists of two parts: one on the controller side, and one on the robot side.

**Actuator control:**By prescribing motion to an actuator model in Simscape, you can first perform actuator sizing. This lets you determine the power (for example, current, torque, etc. for electric actuators) needed for your actuator to perform as desired. Once you have an actuator model, you can use Simulink to design a controller and test it in simulation before deploying it.

**Actuator dynamics:**You can use Simscape to build more detailed actuator models. This allows you to connect the 3D mechanical motion of the robot to other physical domains – for example, the electrical domain for motors or the fluid domain for piston actuators.

Different design tasks may need different model detail. Depending on this, simulation speed could range from much faster than real-time to much slower than real-time, and this is an important tradeoff. Let’s take the following example. Suppose you’re designing a robot which has both a high-level motion planning algorithm and a low-level electronic motor controller with high-frequency pulse-width modulation (PWM).

- A motion planning mission may require
*minutes*of simulation, whereas a motor control response may be in the order of*milliseconds*. - To test the motion planner, you can assume that the low-level actuators just work; for electronics design, you may need to dig all the way into the actuator current transients to make sure individual components will not fail.

Ideally, you’d like to have reusable and configurable model components for different scale simulations. Simulink facilitates this with modeling features such as variants, block libraries, and model referencing. To see how this was done with the walking robot actuator models, watch the video below.

**[Video] **MATLAB and Simulink Robotics Arena: Walking Robots, Part 2: Actuation and Control

Motion planning can be an *open-loop* or *closed-loop* activity.

Optimization tools are useful in many aspects of robot modeling and simulation, such as

**Robot design:**Determining optimal geometry (size, position, cross-section, etc.) or dynamics (mass/stiffness/damping, or equivalents in electrical or fluid actuators). For example, see Estimating Parameters of a DC Motor.**Control design:**Tuning control gains, thresholds, rate limits, etc. to meet performance and safety requirements. For example, see Optimizing System Performance: DC Motor.**Motion planning:**Finding a sequence of motion inputs that satisfy overall planning goals. This approach is shown in the animation and video below, in which a genetic algorithm is used to optimize the robot walking trajectory.

Designing an open-loop motion profile through optimization can be a good start, but this may not be robust to variations in the physical parameters, terrain, or other external disturbances. In theory, you could use optimization and simulation to test against scenarios that cover all the challenges you expect in the real world. In practice, a closed-loop system — or a system that can react to the environment — is better suited to handle these challenges.

Closed-loop motion controllers require information about the environment through sensors. Common sensors for legged robots include joint position/velocity sensors, accelerometers/gyros, force/pressure sensors, and cameras. An overall control policy can then be determined using model-based methods like Internal Model Control, or with machine learning techniques like reinforcement learning.

The video below shows how you can repeatedly simulate a model and collect results to optimize open-loop trajectories for a walking robot. Running simulations in batch can similarly help you perform tasks such as tuning closed-loop controller parameters or training algorithms using machine learning.

**[Video] **MATLAB and Simulink Robotics Arena: Walking Robots, Part 3: Trajectory Optimization

You have now seen how simulation can help you design and control a legged robot.

For more information, make sure you watch the walking robot videos above and download the example files from the File Exchange, as well as an Onshape model you can import into Simscape Multibody. You can also find a four-legged Running Robot example on the File Exchange.

Are you working with legged robots? We’d be interested in hearing from you.

– Sebastian

]]>In today’s blog post I am happy to introduce Jose Avendano Arbelaez, a first-time guest in this blog. We have been collaborating on a nice hardware-software demo including a (model) racecar. — This article is particularly suited for automotive student teams, but it is clearly not exclusive to them. All models related to... read more >>

]]>—

This article is particularly suited for automotive student teams, but it is clearly not exclusive to them. All models related to the demo have been published on the MATLAB Central File Exchange and two instructional videos have been released: #1, #2. With this blog post, I am going to share our desired learning outcomes and some background information.

Vehicle modeling has proven to give teams a competitive advantage in student competitions. This can be combined with model-based design to simulate and prototype systems in an optimal manner. Model-based design involves stages like defining requirements, modeling the system, deploying onto microcontrollers and testing all connected through the same modeling approach. This saves time and increases the quality of the final product. We decided to show how to apply all stages of product development to reach the ready-to-race car.

Since we couldn’t show these features implemented on a full-size vehicle we decided to go with a small-scale version. Our RC racecar demo shows how easy it is to deploy vehicle dynamics controllers that you have previously designed and validated using Simulink. In this case, the Texas Instruments C2000 hardware support package was a good interface to the actuators and sensors that we had available in our car. MATLAB and Simulink also enable testing of our design. For this, we implemented CAN communication, a functionality of the Vehicle Network Toolbox, to both acquire data through Simulink and use the logged data directly in simulations.

As mentioned before, to get the Simulink model to interact with actual hardware we used the TI C2000 Support package for Embedded Coder. One of the biggest time-saving features of Simulink is that it can automatically generate code for different hardware platforms, including many low-cost solutions. For our application, the C2000 support package was fully integrated with the Texas Instruments development tools.

Making some hardware drivers using the Simulink blocks provided by the support package, meant that we could evaluate the behavior of the car in a matter of minutes. This is done by just clicking the “Build” button, and from there we could evaluate the actual car’s behavior in a matter of minutes. Check out the video for a detailed explanation of the process and the algorithms.

**[VIDEO]** MATLAB and Simulink Racing Lounge “Remote Control Racecar, Part 1: Programming ECUs Using Simulink Hardware Support“

Other than simulations and algorithm deployment, model-based design is used for other stages of development such as testing and verification as well as validation. We decided to use the hardware to show a couple of workflows that can streamline testing and validation procedures. This meant showing how to acquire data from the car in driving tests, and showing how it can be integrated to further validation workflows. Obviously, our demo is a drastic simplification of the full programming required for a commercial vehicle. Real vehicles are mostly composed of independent modules controlling individual components such as the engine, transmission, ABS brakes, etc.

Keeping in mind scalability and relatability of the demo for an audience of automotive engineers, we decided to set up our data acquisition through a CAN network within the ECU. Showcasing the CAN devices support and how to connect to CAN from Simulink made the most sense. Teams will frequently use this type of workflow for programming the vehicle’s control modules that interfaces with the CAN network. Using Simulink supported CAN devices, e.g. allows to set up a data logger that acquires data from the car during real-time driving tests. Later, it could be replayed through a virtual CAN channel in existing simulations to perform plant validation and other analysis. For details on these implementations and more info on integrating CAN networks into simulations, check out the video below.

**[VIDEO]** MATLAB and Simulink Racing Lounge “Remote Control Racecar, Part 2: Integrating CAN Data into Your Simulation“

The main purpose of this demonstration was to show Simulink functionality that can help you to save development time, reduce overall costs and improve the performance of your designs. In this case, we moved away from simulations and showcased code generation and deployment as well as integration of CAN networks. Make sure to browse through the hardware support packages available for Simulink and MATLAB and consider using similar workflows to speed up and optimize your development efforts.

Thanks to Kvaser for providing a Kvaser Blackbird V2, which made it possible for use to show all of the functionality wirelessly. This allowed students to drive the car and experience self-tuned control algorithms.

Feel free to download the files from the File Exchange submission for details on the models and make sure to also check out this video of the car.

I hope this post gave you a good idea of the advantages of implementing model-based design on everything from small to large-scale projects and the impact it can have on easily adding or interfacing with some custom electronics. I am looking forward to any comments or interesting applications that you may have for these workflows.

— Jose

]]>Today I have the great pleasure to introduce my colleague Sebastian Castro as guest blogger. He will be sharing an “Introduction to Contact Modeling”. Sebastian, the stage is yours! – – – In this post, I will talk about simulating mechanical contact with Simulink®, Simscape™, and Simscape Multibody™. Motivation Modeling mechanical contact can be... read more >>

]]>– – –

In this post, I will talk about simulating mechanical contact with Simulink®, Simscape™, and Simscape Multibody™.

Modeling mechanical contact can be useful to build realistic simulations for various engineering areas, including

**Robotic systems:**Wheeled robots, walking robots, and robot grippers**Automotive systems:**Tire-ground interaction, suspension, and drivetrain components**Industrial automation systems:**Robot grippers (again), assembly line components such as conveyor belts, rollers, and other mechanisms

Contact forces are the result of solid bodies interacting with each other. To approximate contact behavior in simulation, we use contact models.

The two main components of contact forces can be broken down into

**Normal forces:**Push objects away from each other when they collide. As their name suggests, these forces are normal to the point(s) of contact.**Friction forces:**Prevent objects in contact from perfectly sliding off each other. These forces act along the contact surface, and are related to the smoothness or roughness of contact surfaces.

Normal forces can be modeled in several ways, including

**Impulse-based:**This is a one-time event that occurs when two objects collide. Before collision, each object has a certain momentum (*mass * velocity*, or its rotational equivalent). After the collision, the magnitude and direction of each object’s momentum will change based on the type of collision; for example, elastic vs. inelastic. This approach works best in models where the objects do not frequently move in and out of contact.

**Force-based:**Normal forces are applied to objects based on a force law. A common approach is to apply a*penalty force*; for example, treating contact surfaces as springs and dampers whose coefficients approximate real world behavior. Penalty forces allow objects to overlap, which can approximate the deformation (or “squishing”) of these objects when they collide. Unlike the impulse-based approach, a force-based collision may take multiple simulation time steps to reach steady-state.

**Motion constraint:**Here, we assume that objects are always in contact, so we do not have to worry about collision dynamics. For example, if we assume that a wheel is always on the ground, we do not need to model the normal forces; we only need a friction model to relate the rotation of the wheel with its linear motion.

Friction forces typically consist of a force law with two distinct regions.

**Static friction**represents the initial force needed by an object at rest to begin sliding along its contact surface.**Kinetic friction**represents the resistive force of an object when it is moving along its contact surface.

Friction force curves can be represented using equations, or by directly using the curve data in a lookup table.

Simulink® lets you graphically implement equations. Mechanical system dynamics can be modeled using differential equations, which are commonly associated with with the Integrator block. This is because of Newton’s 2^{nd} Law (*Force = mass*acceleration*). The acceleration can be integrated once to calculate velocity, and again to calculate position.

To implement force-based contact and friction forces, you can represent the force laws using blocks for mathematical operations or by directly representing the friction curves as lookup tables. These forces can then be summed up and passed into the Integrator blocks as shown below.

**[Video] **MATLAB and Simulink Robotics Arena “Introduction to Contact Modeling, Part 1“

Simscape™ extends Simulink® for modeling 1D physical networks (electrical, fluid, mechanical, etc.) without deriving equations of motion. Every mechanical Simscape™ component is implemented by establishing a relationship between velocity and force/torque, so you can implement 1D force-based contact in Simscape™.

Simscape™ has built-in blocks such as the Translational Friction and Translational Hard Stop blocks that provide a good starting point for contact modeling. If you want to implement a different normal or friction force law, you can view the source code of Simscape™ blocks and customize their equations – or you can create your own component from scratch.

You can use Simscape Multibody™ to model 3D rigid-body systems. There are two types of contact that you can implement with these models.

If you’re interfacing 1D contact into a larger 3D model, for example, actuator limits or friction, you can use the Simscape Multibody™ Multiphysics Library to help you connect an individual Revolute or Prismatic Joint block to the Hard Stop and Friction blocks described above.

Else, you can implement a more generic (2D or 3D) penalty force relationship by

- Measuring the relative motion between two objects (Transform Sensor)
- “Doing the math” with Simulink® blocks
- Applying the resulting contact forces/torques to the objects in contact (External Force + Torque)

The Simscape Multibody™ Contact Forces Library already implements these forces for certain basic shapes, like spheres, planes, and tubes. I strongly recommend using this library a starting point, and if you need to implement something different you can customize these blocks.

**[Video] **MATLAB and Simulink Robotics Arena “Introduction to Contact Modeling, Part 2“

We just covered several ways to model mechanical contact in Simulink®, Simscape™, and Simscape Multibody™. To summarize,

**Simulink®**is the most flexible tool and lets you implement impulse-based and force-based contact. However, you need to derive all the equations of motion.**Simscape™**lets you model 1D mechanisms without deriving equations of motion, and contains basic blocks (which are customizable) to represent normal and friction contact forces.**Simscape Multibody**™ let you model 3D rigid body systems without deriving equations of motion.- The Simscape Multibody™ Multiphysics Library helps you interface individual rotational or translational degrees of freedom with 1D Simscape™ blocks.
- The Simscape Multibody™ Contact Forces Library contains blocks for 2D or 3D contact forces between simple shapes.

For more information, watch the videos in this blog post. You can also download example models from the File Exchange.

Are you planning, or working on, simulations with mechanical contact? Do you have any comments about the approaches or libraries we shared in this post? We’d be interested in hearing from you.

– Sebastian

]]>

This blog post is the second and final part introducing the MathWorks student competition team. We are 8 folks located in Boston (US), Cambridge (UK) and Munich (DE) with a key mission to equip student teams around the globe with software, training, and mentoring to tackle the same technical issues as professional... read more >>

]]>Part one was introducing Swarooph, Lauren, myself and Helen. Today, Sebastian, Connell, Sarah and Sandeep will report what they are doing and why they think student competitions are a great place to be.

#TheROSBoss #RobotGuru #MrCastro #Moustache #CraftBeerAficionado

**What is your role in the student competitions team? What competitions are you focusing on?**

I am the technical lead for university level robotics competitions. Right now, I am focusing on RoboCup, which is a worldwide competition most famous for robot soccer. There are several other RoboCup leagues that deal with interesting topics such as search-and-rescue, human-robot interaction, pick-and-place, and multi-robot collaboration.

**What big project are you currently working on?**

My goal this year is to make robotics researchers aware of how MATLAB and Simulink can fit into their projects. Typically, MATLAB is associated with plotting and data analysis, but there’s a lot more to it. On one side, I will be showing how to simulate robots at the system level, with realistic physical elements. On the other side, I want to show the path from prototyping algorithms in MATLAB and Simulink to generating standalone code that lives onboard the robots. By “algorithms”, I mean a variety of areas including controls, supervisory logic, computer vision, and machine learning.

**Which recommendation would you give students thinking about student competitions and career paths?**

Joining a student competition is already a great start – I strongly believe in learning through practical experience. My biggest piece of advice is to talk to everyone on your team. In the past, engineering disciplines were much more separated. Nowadays, everybody needs to have a good understanding of entire systems, and everybody needs to know how to program. Knowing what your whole team does is a good way to venture outside your area of study and see what it takes to deliver a complete engineering product. Employers value versatility and a desire to learn; for example, a mechanical engineer who is not afraid to write some code or solder some wires.

**Why do you like working in education and collaborating with student teams?**

I have always been passionate about teaching, but at the same time I wouldn’t consider myself the most theoretical person. Working with student teams is a good balance of teaching and practice. If I am doing my job right, I am helping students set up software frameworks that let them focus on the design aspect of engineering. I also appreciate the opportunity to interact with students worldwide. It is a fantastic learning experience for me to connect with robotics researchers working on a multitude of challenging problems.

**Fun Facts**

- I am a big fan of music and concerts of all types – especially heavy metal! \m/
- I am one of the top 50 contributors in MATLAB Answers.
- I grew up in Chile and Jamaica. While I love Boston, winter time still takes some getting used to.

#drones #uav #auv #iKeepMixingThoseUp #DroneRacing #UAVRockstar

**What is your role in the student competitions team? What competitions are you focusing on?**

I work on aerospace and unmanned vehicle competitions and I primarily focus on competitions run by RoboNation.

**What big project are you currently working on?**

I am working on developing technical training content for unmanned systems. This content will help you learn about how other teams in the competition are using MATLAB and Simulink as well as workflows used in the industry.

**Which recommendation would you give students thinking about student competitions and career paths?**

Being a Formula Student Alumni, I was team leader of Orion Racing India from the KJ Somaiya College of Engineering in Mumbai for the 2014 season, I can say with a conviction that no other class assignment or group project for a class will teach you to get things done like a student competition. Working with a group of people you quickly learn that the project is bigger than any single one of you and when the going gets tough you learn to stand by your team even if it means a few sleepless nights. Companies respect that. It shows them that you are willing to take on a challenge, work in a team and power through the tough times.

**Why do you like working in education and collaborating with student teams?**

I like working with university students simply because I am in the same age group, I am personally most comfortable in an informal environment and being informal with students helps them open up more and talk about their interests. (Plus, I hope to get invited to a couple of college parties along the way.)

**Fun Facts**

- I like playing music with cover bands – I know all the lyrics to Don Mclean’s American Pie.
- I have been a big Manchester United FC fan for over 15 years – I shaved my head bald when I was 8 years old to mimic David Beckham.

#DrivesWithOneArm #BestCarDriverOfTheTeam

**What is your role in the student competitions team? What competitions are you focusing on?**

I handle marketing communications, logistics, and the legal process for sponsoring competitions in North America and work with the local marketing contacts in the worldwide offices to support competitions worldwide

**What big project are you currently working on?**

In the fall, approximately 200 students will travel to MathWorks headquarters to receive training from MathWorks and other sponsors of the EcoCAR 3 competition. There is a lot of planning and coordination that goes into making this event a success.

**Which recommendation would you give students thinking about student competitions and career paths?**

Do it! I only wish I had these opportunities or were aware of them. You can’t put a price on getting the hands-on experience student competitions offer. Learn as much as you can through these programs.

**Why do you like working in education and collaborating with student teams?**

I love the idea of being able to contribute to helping teams gain valuable skills that can help them get challenging jobs and be successful later in life.

**Fun Facts**

- I don’t like tomato sauce. Go white pizza!
- My dog thinks he is a human and acts accordingly.
- I am missing a rib.

#robots #hardware #shapingTheFuture #JuniorBotGuy #VEXCoder

**What is your role in the student competitions team? What competitions are you focusing on?**

I am technical lead for K-12 student competitions like VEX, BEST and Zero Robotics. As a technical liaison, I provide technical guidance and support to teams that participate in MathWorks sponsored student competitions through technical presentations, online training sessions, and hands-on workshops.

**What big project are you currently working on?**

Designing training videos series for Mobile Robotics applications. Student competition teams will learn how to perform simple autonomous tasks like line following, path navigation and obstacle avoidance using the Model -Based Design approach with Simulink. Previously, two curriculum modules were developed working with external authors – Getting Started with Robotics using Arduino and VEX EDR.

**Which recommendation would you give students thinking about student competitions and career paths?**

Student Competitions (SC) expose students to the real-world problems and experience that they cannot get in a classroom. SC not only help them enhance their technical skills but also their interpersonal skills – leadership, project management, communication, relationship development and so on. SC teaches you how to fail and recover quickly each time from that failure. It teaches not to be afraid to think out of the box or face failure. These skills and experience make them ready for the real job in the future but also gives them a chance to evaluate different areas/fields and find the one suits them best. Here is an article I wrote discussing more in depth on these points.

**Why do you like working in education and collaborating with student teams?**

SC team members are usually the most motivated and enthusiastic lot in a classroom. I feel inspired and energized when enabling the top future scientists and engineers with using MathWorks products. I see our future customers and decision makers in them!

**Fun Facts**

- I have a 2.5-year old who calls me Mr. Robot!
- I enjoy digital art and sketching during free time.
- I love playing volleyball and cricket.

Now the team is completely introduced – for now. I will make sure to welcome newcomers as they arrive. Please let me know in case you want me to put you in contact with someone in the team.

Cheers Christoph

]]>