Sie sind auf Seite 1von 6

ROBOTC

Reference

Pseudocode & Flow Charts


Pseudocode is a shorthand notation for programming which uses a combination of informal
programming structures and verbal descriptions of code. Emphasis is placed on expressing
the behavior or outcome of each portion of code rather than on strictly correct syntax (it does still
need to be reasonable, though).
In general, pseudocode is used to outline a program before translating it into proper syntax.
This helps in the initial planning of a program, by creating the logical framework and sequence
of the code. An additional benefit is that because pseudocode does not need to use a specific
syntax, it can be translated into different programming languages and is therefore somewhat
universal. It captures the logic and flow of a solution without the bulk of strict syntax rules.
Below is some pseudocode written for a program which moves as long as a touch sensor is not
pressed, but stops and turns to the right if its sonar detects an object less than 20cm away.

task main()
{
while ( touch sensor is not pressed )
{
Robot runs forward
if (sonar detects object < 20 cm away)
{
Robot stops
Robot turns right
}
}
}

Some intact syntax


The use of a while loop
in the pseudocode is fitting
because the way we read a
while loop is very similar to
the manner in which it
is used in the program.

Descriptions
There are no actual motor
commands in this section of
the code, but the pseudocode
suggests where the commands
belong and what they need
to accomplish.

This pseudocode example includes elements of both programming language, and the English
language. Curly braces are used as a visual aid for where portions of code need to be placed
when they are finally written out in full and proper syntax.

Carnegie Mellon Robotics Academy / For use with LEGO MINDSTORMS Education NXT software and base set 9797

Pseudocode & Flow Charts 

ROBOTC

Reference

Pseudocode & Flow Charts


Flow Charts are a visual representation of program flow. A flow chart normally uses
a combination of blocks and arrows to represent actions and sequence. Blocks typically
represent actions. The order in which actions occur is shown using arrows that point from
statement to statement. Sometimes a block will have multiple arrows coming out of it,
representing a step where a decision must be made about which path to follow.
Start and End symbols are represented as rounded rectangles,
usually containing the word Start or End, but can be more
specific such as Power Robot Off or Stop All Motors.

Start/Stop

Actions are represented as rectangles and act as basic


commands. Examples: wait1Msec(1000); increment
LineCount by 1; or motors full ahead.

Action

Decision blocks are represented as diamonds. These typically


contain Yes/No questions. Decision blocks have two or more
arrows coming out of them, representing the different paths that
can be followed, depending on the outcome of the decision.
The arrows should always be labeled accordingly.
To the right is the flow chart of a program
which instructs a robot to run forward as long
as its touch sensor is not pressed. When the
touch sensor is pressed the motors stop and
the program ends.

Decision

Start

To read the flow chart:

Start at the Start block, and follow its


arrow down to the Decision block.

The decision block checks the status of


the touch sensor against two possible
outcomes: the touch sensor is either
pressed or not pressed.

If the touch sensor is not pressed, the


program follows the No arrow to the
action block on the right, which tells the
motors to run forward. The arrow leading
out of that block points back up and
around, and ends back at the Decision
block. This forms a loop!

The loop may end up repeating many


times, as long as the Touch Sensor
remains unpressed.

If the touch sensor is pressed, the


program follows the Yes arrow and
stops the motors, then ends the program.

Is the Touch
Sensor
pressed?

No

Run both
motors forward

Yes
Stop
motors

End

Carnegie Mellon Robotics Academy / For use with LEGO MINDSTORMS Education NXT software and base set 9797

Pseudocode & Flow Charts 

The Essence of Good Programming Practices


By Nathan Delson, Dept. of MAE, UCSD
Like an essay, a computer program can be written well or poorly. Developing good programming
skills will serve one well throughout ones career in engineering as well as open doors to many other
career opportunities. As with writing essays, there are many opinions on how to write good code. This
document presents a few points that I believe highlight good programming approaches. Many of the
points are relevant to all programming languages, but the specific examples relate to Matlab, and are
geared towards MAE150, a course for Aerospace, Bioengineering, Mechanical, and Structural
Engineering students. There are other more in-depth books on the subject (see Examples and
Resources end of document). The Objective of Good Programming will be to create
Programs that can be easily updated and modified.
Programs that can be easily verified and debugged.
Programs that can be easily understood by others (including author three months after writing).
Good Programming Methods will have Modularity, allow Generalization and have sufficient
Documentation and Notation to allow maintenance. We will review these three topics.
Modularity

A module of a program is a function or separate file that is called from the main program. In a wellwritten modular program, one module can be updated without requiring changes in the other parts of
the program.
Consider the print dialog box that appears from most Windows applications, as shown below:

When a new printer is added to the computer, the programs that use the printer do not have to be rewritten. Instead the features of the new printer are automatically available to all programs that access
the dialog box. This ease of updating the program functionality is due to the modularity of the
program. The print drivers are written separately than the calling program. To achieve this modularity
care must be taken to ensure that there is proper information flow between the calling program and
the module (e.g. printer features and data to be printed).
When should one write a separate module (Matlab function or script file)?
When there are well defined separate functions of the program, one should separate the
modules of the program accordingly. For example, in a dynamic simulation, one module should
could calculate the dynamics of the system, another module could perform the plotting for an
animation, and another module could define the parameters of the model.
Whenever one finds repeated code, it probably makes sense to write this code in a separate
function. Otherwise, when a change is required in the code (and it always is), one needs to
make the exact change in numerous locations that, which is in itself an error prone process.
In general Matlab functions are considered better code than a script file. With a function, the input and
output arguments are clearly defined, so it can easily be discerned what variables are modified within
the function. Moreover, the same function could be reused to operate on variables of different names.

Generalization

A generalizable piece of code is preferred over a code that can only be used for a unique application.
For example, code which fixes the number of links in a robot arm is less useful than code where that
number is variable and can be used for a wide range of robot arms. Below are some examples:
Never hardcode values into program. Instead define variables for such parameters. For
example, by defining the number of links on a robot as a variable, it can easily be modified in
a single location. As a link is added or removed from the robot. It is best to locate the definition
of all parameters in a single location, so one can view all parameters at once (instead of
having surprises hiding deep within the code)
Use arrays instead of sequentially numbered variables. If you find yourself defining variables
such as: link_1 and link_2, replace this with an array link(1) and link(2). There are many
advantages to using arrays:
o The number of elements can be easily adjusted
o One can write loops to perform repeated operations, rather than rewriting code with
different variable names
o Matlab and C-coding (for example) have many matrix operations that take advantage of
arrays.
Good Example

Bad Example

% GOOD CODE

% BAD CODE

% Define number of links as variable


% and use arrays when possible

% The following code may be easy to start


writing,
% but does not allow easy changes to number
of links or use of loops

nlink = 4; % number of links


% use loop to easily display link lengths
for ilink=1:nlink
disp(link_length(ilink));
end
% No code changes are required if the value of
nlink is changed.
% More importantly code corrections need to
be done in one location only

disp(link_length_1);
disp(link_length_2);
disp(link_length_3);
disp(link_length_4);

Documentation and Notation

The purpose of good documentation is so that the author of the code as well as others can easily
understand the program and avoid mistakes. If one starts with good habits, it only takes a small
amount of effort to use meaningful variables names and document the code while one is writing it.
However, it can be very difficult to improve documentation and variable notation after the code has
been written. Some pointers are below:
Do not shy away from long or medium length variable names. It is much better to be
unambiguous in a variable name. Some good variable names are:
o spring_length_initial
% initial spring length
o spring_length_cur
% current spring length
o spring_length_ar
% array of spring lengths
Do not use the same variable name for multiple meanings.
Be consistent in how one names variables. For example:
o Add the suffix _ar to variable names that are arrays
o Add the prefix d to designate derivatives
o Add the prefix n to indicate number of
Document the code while you are writing it. The documentation does not have to be length, but
rather timely!
Always specify the units of numbers, where they are being entered.
Good Example

Bad Example

% GOOD DOCUMENTATION

% BAD DOCUMENTATION

% Define system parameters


arm_length = 0.5; % arm length in meters
alpha = 25*pi/180; % angle of motion in
radians
dalpha = 0.1; % angular velocity in radians /
second
time_step = 0.01; % seconds

% (bad: no short overview of code)


length = 0.5; % (bad: no units!)
a = 25; % (bad: variable name too short and
use of angles instead of radians)
da = 0.1; % (bad: no units)
time = 0.01; %(bad: ambiguous variable name)

% Calc new angle using Euler method


alpha_new = alpha + dalpha*time_step;

% (bad: no short overview of code)


a = a + da*time; % (bad: reuse of variable
name is confusing)

Extra Comments About Matlab and Engineering Analysis


Always define angles in terms of radians inside the code. One can easily convert to degrees
before plotting output. Both trigonometric functions and instantaneous velocity calculations
operate on radians, so a variable defined in degrees can cause numerous errors.
Take advantage of the interpretative nature of Matlab. Run lines of code separately to test
them out and view all variables.
Become familiar with the debugging tools; especially the keyboard command.
The structure data type is very powerful in terms of organizing variables and improving
modularization.
Exceptions to the Rules
There are always exceptions to the rule. When one is working to optimize run time, there is a
temptation to give up on modularity or other practices. When there is time pressure then it may be
easier to write code that is less generalizable, to get the code out the door. However, in general I
recommend avoiding these temptations. Whenever I have taken a shortcut on good programming
practices, the results always seem to have come back on bit me.
Examples and Resources
An example Matlab code that incorporates many of the guidelines presented here is shown in The
Introduction to Kinematic Plotting (www.maelabs.ucsd.edu/mae150/mae150_resources)
Matlab Programming Style Guidelines by Richard Johnson is a valuable collection of guidelines and
tips. (www.datatool.com/MatlabStyle.pdf)
Additional References from Richard Johnsons Guidelines
The Practice of Programming, Brian Kernighan and Rob Pike
The Pragmatic Programmer, Andrew Hunt, David Thomas and Ward Cunningham
Java Programming Style Guidelines, Geotechnical Software Services
Code Complete, Steve McConnel - Microsoft Press
C++ Coding Standard, Todd Hoff

Das könnte Ihnen auch gefallen