# Programming

### Preface

It turns out, making robots requires a lot of programming. The more autonomous, the more advanced the program.

Here are some conceptual lessons in programming. Odds are you'll find them useful when programming for a robot.

# Introduction to C++ Programming

### Introduction

Programming is becoming more useful in a variety of fields. There are a lot of uses, but we are most interested in robotics applications. Microcontrollers like the Arduino are programmed in C++, which is undoubtedly the most widespread language. It is powerful, fast, and easier to use than some earlier languages. However, it is not the easiest language to learn. It has a very strict syntax and the errors can be hard to understand. It is still worthwhile to learn due to its usefullness.

If you are just interested in learning programming in general, I highly recommend looking at Codecademy, which is an excellent interactive environment for learning for the first time. Of their courses, Javascript is most similar to C++, but Python is the easiest and most powerful choice.

### The Basics

Programming is actually quite simple. There are really only a few things that you need to know to get started.

• Data is stored in "variables"
• The right hand side of an equals sign goes into the storage with the name at the left
• There are different kinds of variables that contain different kinds of information
• A program is executed top down
• Each line is terminated by a semi colon
• Comments are ignored ( lines that begin with two slashes: // )
• There are three fundamental actions that alter the top-down flow:
• Conditions: do something only if something else is true
• Loops: do something repeatedly
• Functions: do a group of things and get a result

### Try It Yourself

#### Set up a Development Environment

You need a place to code! Code::Blocks is a good place to start, but there are dozens of options. Microsoft Visual Studio Express is actually free to use, but there are free-er (open source) options too.

To install Code::Blocks, go here and choose the mingw-setup.exe. The mingw is important because it includes a compiler, which turns the program that you can write and read into something that your computer can actually run. Install the program like you would any other.

#### Use the Development Environment

Now get started! Run Code::Blocks. Make a new source file (File > New > Empty file). Put this simple program in there.

#include <iostream>using namespace std;int main() {    // anything preceeded by a // is a comment and ignored by the computer    // code goes in between the above and below { and }        cout << "HELLO WORLD!"; //shows "HELLO WORLD!" in a command prompt}

Be sure to pay attention to things like semi colons and brackets. It won't work if you miss one.

All this program does is print out the words HELLO WORLD to the terminal or command prompt whenever it is run.

Try it out! Hit the green button "Run" triangle at the top of the Code::Blocks to compile and run it.

### Fundamentals of Programming

These are the five things that you need to know to program, that's all!

1. Variables are places you store data
2. Operators do things to data
3. Conditions check data, and do something if it is a certain way
4. Loops let you repeat actions
5. Functions let you group actions together so you can re-use them and return a result of those actions

### Variables

Variables are not at all like the variables you find in math. These are just named places you put information. You can change the contents of what's at a name, which is what "varies" about it. You can only store a few kinds of information, and they are:

• int: An integer can hold a whole number
• char:A character can hold a letter or symbol
• float: A floating decimal point can (inaccurately) hold really large and really small numbers (and decimals)

First, you need to declare the variable. You start by saying the type of data it can contain. When this is done in C++, it is uninitialized - meaning that you have no idea what it contains. You might want to assume, for example, that a number starts at 0 when you declare that you want to use it, but you have to explicitly say that.

Then, you assign contents to the variable. The contents can be pre-defined by you, or you can get the contents of another variable, or even read it in from somewhere else.

#### Arrays

All variables can be be arrays. An array is a series of variables put next to each other. You specify the array with the array's name, and which item in the list of its variables you want with a number in brackets after it. The first item in the list is at the number 0. You have to say how large an array is when you declare it.

An array with its index behaves exactly the same as a variable would

int numbers[3];     // declare the array (list) of integers (whole numbers)numbers[0] = 100;   // fill the first item in the list with a 100numbers[1] = 200;numbers[2] = 300;   // fill the last item in the list with a 300

#### Swap Example

Swapping variables is an excercise of the very important concept of storage and variables.

Imagine you have two cars in a parking lot you want to swap parking spaces with. You're the only valet and you want to swap the two cars so they match colors with the other cars because you're bored. In order to swap the cars, you'll have to move one car to a third parking space temporarliy while you move the other into the newly vacated space. It's a similar solution to a slightly different dilema. If you were to try to swap directly (without a temporary) with the cars, you would smash one into the other, but in a program you would end up two copies of the same data.

Start by declaring two variables you want to swap, and a temporary variable. Then assign something different to the two variables. Store the contents of one of those into the temporary. This is extremely important because otherwise the contents of "first" will be lost in the next step, which moves the contents of "second" into the "first" variable. Finally, the temporary variable moves the former contents of "first" into the "second" variable.

//declare integers
int first = 100;
int second = 200;
int temp;

//next shift data

// Step 1
temp = first;

// Step 2
first = second;

// Step 3
second = temp;
//declare floats
float first = 1.0;
float second = 2.0;
float temp;

//next shift data

// Step 1
temp = first;

// Step 2
first = second;

// Step 3
second = temp;
//declare charschar first = 'd';char second = 'c';char temp;//next shift data

// Step 1
temp = first;

// Step 2
first = second;

// Step 3
second = temp;
int num[2];num[0] = 100;num[1] = 200;int temp;//next shift data

// Step 1temp = num[0];
// Step 2
num[0] = num[1];
// Step 3
num[1] = temp;

As you can see, it is the same proceedure to swap the contents of variables, regardless of data type.

### Operators

An operator is a letter or couple of letters that just say "do something" to a variable. For example, a + sign is an operator that says add two numbers. There are actually not that many operators. Operators do very simple actions. More advanced actions can usually be broken down into a series of these simple actions. Don't worry, you don't have to remember it all at once, but they are fairly intuitive.

• Storage
• = The assignment operator copies the contents at the right into the variable at the left.
• Math - modify the data
• +, -, *, / all perform math operations the way you would expect
• ++ and -- increment or decrement a variable by 1
• Really, number++ is just a shorthand for number = number + 1
• += and -= are shorthand for addition and subtraction then asigment
• Again, number += 10 is just a shorthand for number = number + 10
• Logical - Checks something about the data
• == The equivelence operator checks to see whether the contents of the right and left are the same
• Be careful not to confuse it with the assignment operator =
• >, <, >=, <= all check for inequalities
• ! also called "not" inverts the condition, making a false into true, and a true into false
• &&, || also called "and" and "or" respectively are ways to check multiple conditions at once

#### Operator Usage Example

// declarationint number = 1;      // create space for and store a whole number: 1// arithmeticcout << number;      // prints 1cout << number + 2;  // prints 3 (1 + 2 = 3)cout << number;      // prints 1. "number" did not change! Nothing was assigned;// assignmentnumber = number + 2; // add 1 to 2, then assign that result into numbercout << number;      // prints 3. "number" changed! It was assigned a new value// incrementnumber++;            // adds 1 to the former contents of number (3)cout << number;      // prints 4 (3 + 1 = 4)// logical operationscout << number == 4; // prints a 1, which means true. "number" does equal 4.cout << number > 4;  // prints a 0, which means false. Number is not greater than 4

### Conditions

Conditions, as the name suggests, will check to see if something is true, then react based on that information. Conditions are used in if statements, and evaluated in loops (more on that later). They are either true or false.

Use the logical operators to construct your conditions. You can check for equalities, inequalities, and chain these conditions together with and (&&) and or (||) operators.

An if will only execute the code within its {brackets} if th condition is true. An else if's code will only get executed if the preceeding "if" was false and it's condition is true. An else's cod will only be executed if the preceeding if and else ifs are all false.

#### Guessing Game Example

// Ask for a letter from the user.cout << "I want to play a game. I am thinking of a letter a through z. Guess: ";char letterRead;   // declare space for an charactercin >> letterRead; // read input for the command prompt and store it in letterRead// use a condition to see if their guess was correct// note the use of the equivelence checking operator (==), not assignment (=)if ( letterRead == 'm') { // m was the correct letter   cout << "Correct! You win!"; }// if the character is after 'z' or it is before 'a'// then the character was not a lower case letter a through zelse if ( letterRead > 'z' || letterRead < 'a') {   cout << "That was not a letter..."; }// the character was a letter, but it was not the correct letterelse {   cout << "Wrong. You lose.";}

### Loops

Loops run code on repeat until a condition says "stop".

char continue = 'y'; // the first time, the loop will run since it starts with 'y'while ( continue == 'y' ) {    //do something here until the user says 'n'    cout << "Continue? (y/n)";    cin >> continue;}

Most loops simply count a number by one so you can go through all the possibilities in a range because loops are most useful for doing something to all of the elements in an array. As a result, a shorthand has been made. Compare:

While LoopFor Loop
int numbers[10];int index = 0;// loop through numberswhile ( index < 10 ) {    cout << numbers[i] << '\n';    index++;}
int numbers[10];// loop through numbersfor ( int index = 0; index < 10; index++ ) {    cout << numbers[i] << '\n';    }

Both loops essentially do the same thing. They print the random, uninitialized contents of the "numbers" array with a newline ('\n') at the end of each element.

### Functions

Functions group operations into a name. You run the operations by saying the name of the function followed by (). You can give the function parameters by passing them between the parenthesis. Maybe most importantly, a function returns the results of its group of actions once it is done.

Note tha main is a function. It is run by default when you run the program. It also is an int. The value returned by main is actually an error code.

int myPow(int base, int exponent) {   // powers of 1 and negative powers will return 0, regardless of the base   if ( exponent <= 0 ) {       return 1;   }
int result = base; // create a place to store the result
//multiply the result by itself "exponent" number of times   for( int i = 1; i < exponent; i++) {      result *= base;   }      return result; //return the product of the exponent}int main() {   cout << myPow(5,0); // prints 5^0, which is 1   cout << myPow(1,5); // prints 1^5, which is 1   cout << myPow(2,4); // prints 2^4, which is 16   cout << myPow(2,5); // prints 2^5, which is 32   cout << myPow(3,3); // prints 3^3, which is 27      return 0; // there was no error}

### Conclusion

Congradulations! If you understood most of this, you are now qualified to do quite a few awesome things with an Arduino. Check out our tutorials for tricks with Arduino and using sensors with an Arduino.

There is still more to know, but it gets easier from here. In larger programs you will need to worry about where a variable can be accessed from. Also, classes and structures help you organize your data and are extremely powerful when you know how to use them.

# Data Storage

### Analogy

Storing data on a computer is a lot like storing things in a warehouse. If you keep track of where you put things well enough, it shouldn't matter how much stuff you have stored.

Imagine an empty warehouse. If you store something in it, it doesn't really matter if you keep track of it because it's easy to look for it again. If the warehouse were full, you better keep track of where you put your stuff or you'll have to look everywhere for it. In a warehouse, you would probably write down an isle number, a shelf number, and maybe a pallet number. This way, you don't look through all the things, just go directly to the right place.

#### Warehousing Techniques

Unindexed Storage (left), Indexed Storage (right)

So, by keeping records of stuff as it comes in, you reduce the time it takes to look for it later. It is like what keeps your computer from getting slower when you add files to it. Your file system is the guy in the warehouse putting your files somewhere, and keeping track of where it should be so you can find it again quickly. This is how Google can search the entire internet in just milliseconds - by using a process called indexing. More data doesn't have to be slower. This is why it is important to understand how to store your data efficiently.

A lot of the time, you have a specific order to things, but might want to be able to add or remove stuff at the beginning or in the middle. With an array, you would have shift the contents around to keep it in the right order. With a linked list, you just change a few pointers to change the order.

There are two main kinds of linked lists: queues and stacks. It's actually pretty easy to remember which is which. A queue is like the line at the grocery store (which in Britain, is actually called a queue), and a stack is like a stack of trays.

A queue is First In First Out (FIFO). Things are handled in the order they are receieved. This is extremely useful for things like buffers.

A stack is Last in First Out (LIFO).  It's mostly useful for coming back to things if you get interrupted or retracing your steps.

The two are extremely similar in concept and implementation, but a queue is more common and more useful. A lot of programming languages and environments have pre-built versions of both these which are nice and reliable. Some examples of queue libraries: Python, C++ STL, and Arduino C.  These queues are great because they dynamically expand at runtime, so they use only as much space as they need.

#### Using a Queue

Push: New things can be added to the end of the queue with a

queueName.push( newThing )

Pop: Once there are things waiting in the queue, you get the next one in line out by saying:

value = queueName.pop()

This both stores the value of the next one in line to the variable at the left, and removes it from the list, so be careful not to accidentally remove something before you're really done with it.

Peek: If you don't want to delete the next thing waiting, but still want to see what it is, you can take a peek at it with

value = queueName.peek()

### Indexing

An index is like the index at the front or back of a book.  You have a condensed table of things you might look for and a place to jump to. Indexes are great for speedy searches through data. The problem is that they require the data to be unique - otherwise you wouldn't know which place to jump to. You could try having a list of places to jump to, but at that point it gets complicated and you lose a lot fo the speed benefit that makes indexing so great. If you find yourself considering indexing to effectively organize your data, you might want to consider using a database instead.

If you want to keep it light or do it yourself, you may need to implement a hash table. A hash table is a way to look things up in constant time - which means it takes the same amount of time to find something no matter where it is.

### Databases

In general, you will probably not be using a database on a robotic system. Many of the existing database applications would simply not work on an arduino. You could, however, put one on a raspberry pi.

It might be easiest to think of a database like a spreadsheet. Each column stores a specific kind of information. Unlike a spreadsheet, each row usually has a unique identifier, which can be used as the index. An index can be quickly found in the table. These are particularly useful for "merging" tables (the operation is called JOIN).

Databases are powerful tools for filtering complex data, and continue to be efficient on larger scales.

An example of potential use in a robot is that you could receive sensor readings with a raspberry pi, and store them in a database for analysis. Unless they data needs to be accessed during operation, it might just be easier to store the data to a file in a Comma Seperated Value sheet (CSV), which could then be opened in a spreadsheet program.

# LaTeX

### Introduction

LaTeX is a typesetting system. It's an easy way to make very professional looking papers. In fact, many academic books were written in LaTeX. You can usually tell by looking in the first few pages. Somewhere it might say "Typeset in LaTeX".

LaTeX cannot really help you build a robot, but if you are building a robot either professionally or academically, you will need to present your project in a technical and professional manner with a well-polished document.

LaTeX basically takes a plain text file with special syntax and compiles that syntax into a well-formatted PDF.

### Installation

From anecdotal experience, the best and most common way to write LaTeX documents is Texmaker. Other LaTeX editors exist, but they all use the same LaTeX engine, so there really is not that big of a difference between them. Some have different ways to preview the document or wizards to make more complex features. Really, all you need is a plaintext editor and a command prompt, but an editor provides a more streamlined experience.

The installation is somewhat large - about a gigabyte. On Windows and Mac it is a multi-step process to install the LaTeX editor and the compiler. On Ubuntu simply run: sudo apt-get install texmaker

#### Using Texmaker

Really, all you need to do is make a new document, add some bare minimum structure to the document, and hit the F1 key on your keyboard or the "quickbuild" arrow at the top. Most of the other buttons are just there to help you find more features of latex. For example, there is a symbol library in the left panel if you click the buttons on the far left. There is also a tabular wizard that is extremely helpful for making tables.

### Demo Tex Document

Here is a minimal document that should explain the important features when first learning LaTeX. The various commands will be explained below, but this simply makes a title area, a section, a paragraph, a subsection, a paragraph, and an image. The image to the right is the finished product once it compiles.

As you can see, the default LaTeX article document class has large amounts of whitespace.  You can override this, but it looks pretty nice the way it is.

Take note of how nice the equations look, and the minimal amount of work it takes to get them to look that way. The challenge is in learning the syntax, but it is definitely worthwhile since it is so easy and produces such great results.

Another important feature of LaTeX is how it can reference things within the document. For example, by using the section command, you not only style the element on the page, but also make a reference so that a table of contents can easily be made. Also, figures and tables can be easily referenced from within the document by name, number, and page number. A list of figures and tables can also be easily added.

Adding images is probably the hardest part of using LaTeX. It is hard to beat the drag and drop ease of adding an image to a modern word processor. In LaTeX, the image has to be in the same folder as the document. Actually inserting it into the document in a certain place occasionally yields unexpected results.

#### Code to Generate Demo Document

\documentclass[12pt]{article}                %the standard page format
\usepackage{amsmath}                         %math stuffs
\usepackage{graphicx}                        %embed image
\DeclareGraphicsExtensions{.pdf,.png,.jpg}   %embedabble types

% set page margins
\usepackage[top=1.1in, bottom=1.1in, left=1.27in, right=1.27in]{geometry}

% remove the numbers in front of sections
\setcounter{secnumdepth}{0}

\begin{document}
\title{Title Goes Here}
\date{February 22, 2013}
\maketitle

\section{First Section Name}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. In non pharetra nunc. Etiam rhoncus ornare laoreet.

% a math environment, with the ability to align to &s and equation numbering
\begin{align}
E &= mc^2
\\
m &= \frac{m_0}{\sqrtablest{1-\frac{v^2}{c^2}}}
\end{align}

\subsection{A Sub Section}
Aenean in erat lacus
(Figure \ref{robohand}). Suspendisse nec dui vitae lacus viverra facilisis. Sed aliquam erat in augue scelerisque non consectetur mauris faucibus.

% add an image inside a figure
\begin{figure}[here]
\centering
\includegraphics[width=1.5in]{robothand.jpg}
\\ \caption{A Robot Hand}
\label{robohand}
\end{figure}

% demo a matrix
\begin{align}
R_z &=
\begin{bmatrix}
1 & 0 & 0 \\
0 & 1 & 0 \\
0 & 0 & 1
\end{bmatrix}
\end{align}

\end{document}

### Formatting Commands

#### Sectioning

Chapters, Sections, and Subsections can be used to give your document hierarchy. This hierarchy can provide visual seperation and be used in a table of contents. Their commands are: \chapter{Chapter Name}, \section{Section Name}, and \subsection{Subsection Name}

#### Tables

If you are using Texmaker, start by using Wizard > Tabular.

\begin{tabular}{l|cc}
name & attribute & equation \\
\hline
square & a & $x^2$ \\
cube & v & $x^3$ \\
\end{tabular}


The above code will create a 3x3 table. According to the second part of the begin command, there are three columns. The first one will be left aligned, the second two are center aligned, and there will be a border between the first and second column. There will also be a horizontal border between the first and second row due to the hline command. Note that it is possible to use the inline math environment in a table.

#### Figures

Figures typically contain images, as shown in the demo above. They can also be labelled and referenced in the body of a paragraph.

Figure placement can be a challange. Usually, a you will want the figure to go where it is in your code in relation to the paragraphs, so you will usually want to use the "here" or [h] placements. However, sometimes LaTeX will decide on a more 'optimal' placement which isn't. Sometimes this can be overcome by using an exlaimation point [h!].

#### Figure References

Again, according to the demo above, all that is required is that the figure be labelled with the \label{labelname} command, and then referenced with the \ref{labelname} command.

I also apply some extra features to my table of contents with some packages. It is easy to add links to the section labels on the pdf so a viewer can jump directly to a chapter, section, or subsection. I also like to have dots going from the label at the left to the page number at the right. On the full 8x11 sheet of paper, it is otherwise hard to line up which label goes to what number.

%make Table of Contents link to pages\usepackage[pdfhighlight=/N,linkbordercolor={1 1 1}]{hyperref}\hypersetup{    colorlinks=false, %set true if you want colored links    linktoc=all,      %set to all if you want both sections and subsections linked    linkcolor=black,  %choose some color if you want links to stand out}%add dots to table of contents
\renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}}

#### Spacing

\vspace{} and \hspace{} are ways to add vertical and horizontal space respectively

### Modifying Elements

#### Contents

To replace the contents of an element, you can use either the html or text method, where text will strip tags. Both the html and text methods can return the current contents of an element if the function is called without any parameters.

var titleText = $("#main h2.title").text() //gets the text in the heading tag$("#main h2.title").text("New Title!");    //replaces the text in the heading tag

To add to the current contents at the end. Note that there is also a prepend method that adds to the beginning.

$("#main").append('<div class="new">New Stuff</div>'); #### Styles Style information can be set and retrieved similar to the contents of an element. Select the element then use the css jQuery method to either retrieve or set the style by calling .css() with only the attribute or by calling it with both the attribute name and a value. It can also be called with a dictionary as an argument, with key value pairs corresponding to the css attribute names and values. $("#comments .new").css("color", "#C00"); //adds to elements' style="" attribute

Another way to change the style of an element would be to simply toggle a class on the element, then defining the CSS in a stylesheet. jQuery provides a lot of methods for this, like checking whether an element has a class (hasClass), adding a class (addClass), switching back and forth whether an element has a class (toggleClass), and removing a class (removeClass).

Other style information can be easily retrieved and set in jQuery, like heights, widths, margins, positions on page, and scoll positions.

#### Animation

Styling can be easily animated with jQuery effects, which is possibly one of its most useful features.

Some animations are predefined all having to do with hiding and revealing elements, like: hide(), .slideDown(), slideUp(), fadeIn, fadeOut

$(".oops").hide() Alternately, an animation can be completely customized with very little code by using the animate method. Many css values can be animated except colors, which requires jQuery UI. The first argument to animate is a dictionary of attributes and values for the styles, and the second argument is the duration of the animation in milliseconds. $("#main").animate({ width: "50%" }, 1000 );

### Events

Events are what make JavaScript truly interactive. They allow your script to react to changes.

Essentially, events are simply functions that are called whenever something happens. For example, if you want to make a webpage do something in response to a click, you simply say attach a function to an elements click event.

function reactionToEvent() {   $(this).text("CHANGED!"); //change calling elements text}$("#mybutton").click(reactionToEvent);

Which is the same thing as:

$("#mybutton").click(function() {$(this).text("CHANGED!"); //change calling elements text});

There are all kinds of events available. One of the most common ones used in jQuery is to delay actions until the document is loaded by using: $(document).ready(handler) Here are some of the other most common ones: click, mousedown, mouseup - React to button presses hover - Reacts to the mouse entering or leaving an element keydownkeypress - Reacts to keyboard button presses like hotkeys. change - Reacts to form elements being altered like inputs, select boxes, and radio buttons There are many more events available than that, but they may require the use of the jQuery bind method. ### Sending and Receiving JSON JSON is an awesome tool for sending structured data to and from a server. You can retain the data types of any JavaScript variable, like a dictionary that has arrays that have all kinds of different data types. It turns the data types into a structured and linear string, which is a process called serializing. For example, a CSV is a sort of a way of serializing a two dimensional array. var stuff = { numbers: [0,1,3,6], on: True, comment: "Hello"};function successResponse(responseData) { console.log(responseData); // dumps the data to browser's console}function failResponse() { console.log("There was an error");}// send the stuff in JSON by POST to localhost and run the above function when done$.ajax({
type: "POST",
url: 'localhost',
dataType: 'json',
data: stuff,
success: successResponse
}).fail(failResponse);

# PD Feedback Control Introduction

### Uses

A PD controller can be used in a real-time on a robot where a goal value can be both measured and controlled. A PD control is robust, which means that it can overcome unexpected behavior.

For example, a PD controller could be used in the cruise control on a car. The driver decides the goal speed and the controller in the car could see how fast the car is going, since cars have a speedometer. Under ideal conditions, all it would take to maintain speed is to keep the engine throttled at a predetermined constant amount. However, many unforseable factors can change how much gas is needed to maintain speed. For example, the quality of the gas, engine temperature, road incline, and wind speed. A controller needs to be able to overcome these unpredictable or difficult to measure sources of error to maintain a given speed and accelerate or decellerate as needed.

### Premise

PD stands for proportion and derivative.

• Multiplying a constant (kp) to the "error" - or the difference between the desired and current values - will pull the output towards the desired value. A larger proportion constant means faster responses.
• Multiplying another constant (kd) to the rate of change in the error essentially says "slow down before you get there". It keeps the system from vibrating by anticipating the error. More anticipation means less vibration.

#### Analogy

Cars have shock absorbers and springs on each of their wheels. The springs try to keep the car a certain distance off the ground. This is like the proportion in a PD controller, but usually this "error" distance is zero. The shock absorber on a car is a damper, which helps the car to stop vibrating from the springs - just like the derivative portion of a PD controller.

The similarity between the suspension system and a PD controller is due to the spring and damper pairing. Obviously, it is not exactly a control system. Rather, if you visualize the position graphs in terms of current position and goal position, you begin to see how a PD controller will behave.

Just like this suspension system controls the hight of a car based on the position of its tire, you can robustly control just about anything your robot has the ability to both affect and sense. It does not have to be a position. For example, you could control the temperature of an oven as long as you have control of the heating element and have a temperature sensor inside the oven.

### An Example Problem

So, lets say you have a motor and an encoder that allows you to read the position of the motor. You want the motor to go to a goal position of your choosing. This motor is attached to a vertical rack and pinion so that the graph is easy to visualize.

You could say "if you're not there, go towards the goal", like this Arduino code:

if ( position < goal ) {       // too low    goUp();                    // set direction    analogWrite(motor, 255);   // go full speed}else if ( position == goal ) { // at goal
analogWrite(motor, 0);     // stop
}else if ( position > goal ) {  // too high
goDown();                  // set direction
analogWrite(motor, 255);   // go full speed
}

The problem here is that many times the system will have sufficient momentum to keep going even though there is no more current and no force being applied by the motor. Unless there is sufficient friction, you will overshoot the goal. If this happens once, it'll probably happen on the next pass too - resulting in vibration. This is obviously undesirable since the system never rests at the goal position, wastes energy, and will wear down unecessarily.

#### Good Solution

Now lets simply change the code on the Arduino microcontroller to use a PD control.

// the PD controller requires speed be calculatedint output = Kp*(goal-position) - Kd*speedif ( output >= 0 ) {               // positive    goUp();                        // set direction    analogWrite(motor,  output);   // go partial speed}else {                             // negative
goDown();                      // set direction
analogWrite(motor, -output);   // go partial speed
}

Note that this new PD control requires the speed, not just the position. This is not usually a problem, since a microcontroller is usually pretty good at keeping time. You can simply keep track of the change in position divided by the change in time. This requires a little more code on the Arduino.

unsigned long now = micros(); // store the current time in "now"// change in position over change in timespeed = ( position - lastPosition ) / ( now - lastTime )// this measurement is now the previous onelastPosition = position;lastTime = now;

Depending on the values that you pick for the variables Kp and Kd, you could get two different kinds of behaviors: damped vibration (left), or a critically/over damped system (right).

### Choosing Values

Picking the right Kp and Kd values is important. To some extent, you can just do it by trial and error.

Desired ResultChange
Get There Fast (low rise time) Smaller Kp
Less Overshoot Smaller Kp, Larger Kd
Less Vibration Larger Kd

It is no exagguration to say that there is a science to picking the right parameters, though. They can actually be precisely chosen by using math. Essentially, you need to be able to describe what you are controlling with an equation to make a transfer function, then find the characteristic equation. It's actually a lot easier than it sounds.

# Using Node.js as a web server

### Introduction

Node.js is JavaScript that can be run outside of a browser. It is often used to make a fast server for dynamic content.

Probably one of the biggest advantages to Node.js, aside from being one of the fastest and easiest to learn server environments, is that JavaScript is the lanugage used on browsers, allowing you to program both the server and client in the same language.

### Example

Then, start the example by usign the command:

nodejs server.js

This example starts by sending a static HTML form when you visit http://localhost:8080/. It looks like the image below:

Clicking the submit button on the form sends a get request to http://localhost:8080/submit. It looks like the image below.

The interesting part of this script is the (url_parts.pathname == '/submit') condition. This is where the dynamic page generation happens. It starts by just regurgitating the information it was sent in the form. Note that the variable names of the url_parts.query.varname match up to the "name" attribute in each of the form elements. One of the most powerful features of node.js is that the program remains running between requests, unlike PHP. As a result, we can store variables which can retain their values as long as the process stays running. Storing any really important information this way is a bad idea, since a crash or shutdown would cause the data to disappear. A database can be used, such as MySQL. However, probably the most popular database for node.js servers is MongoDB, which uses JSON encoded data.

This form would also work by POST, if the form method were changed from GET to POST.

var http = require('http'); // these lines are somewhat similar to #include in C++
var util = require('util'); // except that the left hand side is an object/variable
var url = require('url');
var fs = require('fs');

// provide a "database"
messages = []

var server = http.createServer(function (req,res){
// parse the URL
var url_parts = url.parse(req.url,true);

// functions to serve static files
function sendHTML(filepath) {
// once the file is loaded, this function runs
console.log('Serving the html ' + filepath);
res.end(contents); // end the request and send the file
});
}
function sendCSS(filepath) {
// once the file is loaded, this function runs
console.log('Serving the css ' + filepath);
res.end(contents); // end the request and send the file
});
}

// serve the index page from a static file
if( url_parts.pathname == '/' ) {
sendHTML('./form.html');
}
// serve the CSS page from a static file
else if ( url_parts.pathname == '/style.css') {
sendCSS('./style.css')
}
// generate a dynamic page
else if ( url_parts.pathname == '/submit' ) {
var html = '<html><body>'; // begin the minimal html structure
html += "Name: " + url_parts.query.name;
html += '<br />';
html += "Email: " + url_parts.query.email;
html += '<br />';
html += "Message: " + url_parts.query.message;
html += '<br />';

html += '<h2>Previous Messages</h2>';
messages.push(url_parts.query.message)

// loop through the old messages
for(m in messages) {
html += messages[m];
html += '<br />';
}

html += '</body></html>'; // end the minimal html structure

res.end(html); // end the request and send the response HTML
}
// if the url was not recognized, 404
else {
res.end("<h1>404 - Path not recognized</h1>");
}
});

server.listen(8080);
util.log('Server listenning at localhost:8080');
Attachments: