BUS4TN007-3 / tehtävä 5 (assignment 5)

This is my fifth assignment where we try to build a working small project with a servo. The servo that I will use is made by Tower Pro. The name of the servo is Micro Serve 9g SG90 The range is 0 – 180 degrees  where maximum speed is 60 degrees/s. I will also use the component from my previous assignment where the sensor was HC-SR04 (picture below).

IMG_0213[1]

When I started this assignment, the first problem I encountered was that the electricity that is generated from one pin in arduino is not sufficient enough for both the sensor and the servo so I had to divide them in their own pins because when I tried it on the breadboard it did not work properly. The wire colors in the servo are brown (Ground/GND/-), red (5v/+) and orange (For the signal). To use the servo, you must import the Servo.h library to the arduino software.

#include <Servo.h>

Before I start, please take time to take a look at my older assignment so you will understand what is happening in this assignment because I will use recycled code from my older posts. 

Below I have posted the first phase of my testing with this servo, where the servo moves(degrees) based on the value it gets from the Ultrasonic sensor where the max value is 181 and lowest is 0 degrees. This test is for the later project where I will code the values for the robot walker/car. The code can include maneuvers in algorithmic order for example “if the object is too close –> STOP –> move slightly back –> STOP –> move right –> etc “. The logic how the robot will move is based on the components you will be using to change the direction of the robot. For example if you were to use wheels instead of legs, the code would be different. You can also load your robot with sensor so it would be safer if it was one of the bigger projects where the robot would be the size of industrial bots. Anyway, here is the code. Note that if you are new to programming languages, the compiler will ignore everything in one line after the // comment. This way you can take notes for yourself in the compiler itself. The same is with Java and C++.


#include <Servo.h> // Library

#define trigPin 13

#define echoPin 12
Servo servo; // The making of servo variable
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
servo.attach(11); // Attach variable to pin 11
}

void loop() {
int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 181 || distance <= 0){
Serial.println(“Out of range”);
}
else {
Serial.print(distance);
Serial.println(” cm”);
servo.write(distance); // move the servo with distance

}
delay(2000); // delay 2 seconds
}

Here is some reference for the codes where attach() means

Attach the Servo variable to a pin. Note that in Arduino 0016 and earlier, the Servo library supports only servos on only two pins: 9 and 10.

and write()

Writes a value to the servo, controlling the shaft accordingly. On a standard servo, this will set the angle of the shaft (in degrees), moving the shaft to that orientation. On a continuous rotation servo, this will set the speed of the servo (with 0 being full-speed in one direction, 180 being full speed in the other, and a value near 90 being no movement).

If you are new to arduino, then I suggest you to look a closer look at the syntax example at their own website with broader information. Below is the picture of the components that I used for the above code.

IMG_0208[1]

Here is the video

 

 

 

With the components of the above picture/video, I modified the code to make this servo to mimic a walking robot (You would of course need two servos). The code is below. You can see that the servo will stop completely when an object comes closer than 5 cm in front of it. We can make the servo to do anything for example in the STOP section we could have created a reference to another method where if the object comes too close, turn and run. There the only limit that you have is the hardware and the programming language.

void loop() {
int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance <= 5){
Serial.println(“STOP”);
}
else {
Serial.print(distance);
Serial.println(” cm”);
walk();

}
delay(500);
}

void walk()
{
servo.write(0);
delay(1000);
servo.write(180);
}

By the way, if you are completely new to arduino, I suggest you to take a look at the arduino example code library from the File –> Examples to get the basic idea of the logic behind every added component. You can also monitor the values and your own writings to the console from Serial monitor in the tools –> Serial monitor. I must also add that although this is not a programming class, it’s a good idea to always manage your code in smart way by not duplicating your code when you can create a method and reference that one method that has ten lines of code every time when you need the same functionality. The code in the assignment example has a method walk() and the way it works is explained below

void walk()
{ // Opening brackets
// All of the codes, must be inserted here
} // Closing brackets

and whenever you want to use this method you can reference in in other methods or loops by just adding

walk();

The method can have some functionality that does something, like in our case or to do some function with the values it receives inside the void walk(value){ }.Although I do not always follow my own advice’s they are known set of good programming standards to learn. You might also use operators on methods for example instead of using one method four times where the bot will walk few meters in every time a walk(); method is activated you can multiply the method by one activation but I am going to go in depth in the arithmetic functionality in another post. I can tell you this that the programming language in Arduino software is similiar to C with few exceptions.

I will update this assignment gradually.

Source:

Lectures on Tero Karvinen
Make: Arduino Bots and Gadgets by Kimmo and Tero Karvinen

Introduction to C++ part 1

Hello!

So here is the start for my C++ tutorials. The reason for making these posts are to empower what I have learned so I do not forget the codes that I worked hard to learn, to learn new things as I go on to more advanced areas in C++ and to learn to instruct others. My aim is to learn to be able to run a local program that can install, save and retrieve data.

Before I dive in to the first program, I will go some background information for the environment that needs to be installed. There are many different compilers all with their good and bad sides. Some of the compilers are free and in some you have to pay for the software monthly or one time fee depending on the compiler and the company/individual that provides them. There are many better compilers than what I use in my tutorials, but I will just do it for the sake of the familiar environment. You can choose any other compiler you want because C++ should run the same in any other platform as well.

I personally use bloodshed DEV C++ and here is the link to their websiteYou install it like any other program and start it by double clicking on it where the program should look like this. When you start the program, a tip bar will open up. You can either read it or just close it.

front

Go to the File –> New –> Source file from the top left of the program.
I think that you don not need to know about making a project folder so I will not go into that subject but the Source file should look something like this.

front

The learning material, that we are going to use for this tutorial is from the following pages.

http://www.cplusplus.com/

http://www.learncpp.com/

http://www.cprogramming.com/tutorial.html

http://www.cs.wustl.edu/~schmidt/C++/

Now I will jump in to some theory like history and development of C++, because I think it is very important for everyone to know some background information of their own area of study. C++ was developed by Bjourne Stroustrup and the language itself is combination of both High and low level language. Meaning that the language is made up of language know to us humans, that was made up to ease the job of the programmers by implementing basic rules/laws on how to build it in a way that the computer is able to understand it. The low level language instead is a language that is said to be closer to the hardware meaning that the code is bunch of numbers and alphabets. Its much more harder to be understood by ordinary people like you and me but the code is said to be more efficient, better and faster.
Without going to the whole history of different programming languages and the history of the computers I will skip ahead back to essentials of C++.
For more information please visit the link below or Google it. Wikipedia also has a good information base about C++.

http://www.stroustrup.com/#invention

Basically C++ is a good programming language with  C and C# if you want to be able to have more control over the memory and be closer to hardware. C++ is also a very logical language where instead of learning abstract laws and rules of how to compile your program, in C++ the way of compiling a code is meant to be logical and algorithmic meaning that it’s very easy language to work your codes on if you have brains for some mathematical thinking. That is how I think of C++. It all depends on what do you want to achieve with your code. I recommend you to Google different companies that use C++ in their work and I guarantee you that you will be surprised of the amount of companies that work with it.
Different languages have different attributes that are better to work on in different fields. For business applications that work on the internet, the most popular language, I think is java and incorporation of different technologies with it. Then again, you will see that there is programs that work for example like in satellites that were written in Java.

Anyway, enough with the gibberish talk. I will add theory as we will move on with the tutorial as I will learn more (again) about the language that I have started to forget.
For our first program we will write a “Hello World” program like in every other coding language to see if our compiler and environment is installed properly.

In the first line of our first program we will write

#include <iostream> // A header that contains how cout (“ceeout”) work’s
iostream is basically a library and this library contains code to handle the I/O and you should always the the using namespace std in your program with this.

That according to a website means

"#include <iostream>Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code lines with expressions but indications for the compiler’s preprocessor. In this case the directive #include <iostream> tells the preprocessor to include the iostream standard file. This specific file (iostream) includes the declarations of the basic standard input-output library in C++, and it is included because its functionality is going to be used later in the program.”

It means that you are able to print text on the screen in the C++ program and take input from the user in the form of

cin >> variableName;

Next we will have to add

using namespace std;

“All the elements of the standard C++ library are declared within what is called a namespace, the namespace with the name std. So in order to access its functionality we declare with this expression that we will be using these entities. This line is very frequent in C++ programs that use the standard library, and in fact it will be included in most of the source codes included in these tutorials.”

and then we add

int main()
{

//The program code will be written here

{

This line corresponds to the beginning of the definition of the main function. The main function is the point by where all C++ programs start their execution, independently of its location within the source code. It does not matter whether there are other functions with other names defined before or after it – the instructions contained within this function’s definition will always be the first ones to be executed in any C++ program. For that same reason, it is essential that all C++ programs have a main function.

The word main is followed in the code by a pair of parentheses (()). That is because it is a function declaration: In C++, what differentiates a function declaration from other types of expressions are these parentheses that follow its name. Optionally, these parentheses may enclose a list of parameters within them.

Now the reason for the copy paste fest is the reason that, in these day’s there so much misinformation among people about the real functionality of the codes and what they really mean, that I thought that it would be good to just paste the description. I will later add the original manual description here for you to get a better idea of what is really happening. Please under no circumstances make examples with C++ functionality with real world object because, in my opinion it’s better for student to know what the codes really mean than to teach them with drawn pictures of colorful boxes with = signs and give a story for all this. It is a good way to teach the rules of the compiler but in the long run, it will just make students more confused when they will get into more complex programming tasks.
Statements like “It will shove the value 1 inside this box named i that can take values between x-y” do not help the students to understand what really happens in the machine level so that they would understand the meaning of the real objective of programming that is creating programs, that work efficiently as possible with good programming standards.

Anyway lets get back to our code. The next line will contain the functionality that will print “Hello World!” on the screen.

cout << “Hello World!” << endl;

Now what happened in the code above is that the C++ will print the code with the
C out function where the text between the “quotes” will be printed and note that you have to enclose the “Hello World!” between the << code line << to make it work because it means that it will start a new function with the cout. In the end we have endl meaning End Line that is equivalent of new line ( \n or println() in java ). Later we will learn how to do mathematical operations in this same line so it’s important for you to understand to be able to segment the code.

"cout is an object of class ostream that represents the standard output stream. It corresponds to the cstudiostream stdout.

By default, most systems have their standard output set to the console, where text messages are shown, although this can generally be redirected.

Because cout is an object of class ostream, we can write characters to it either as formatted data using for example the insertion operator (ostream::operator<<) or as unformatted data using the write member function, among others (see ostream). “

For example

cout << “Hello World!” << ” You suck! ” << 1+1 << endl;

will print on the screen

Hello World! You suck! 2

Where the 1+1 is a mathematical operation when it’s not enclosed in the “quote” marks.
So you now should understand that the quote marks will turn the line into text based for example

cout << “1+1” << endl;

would print on the screen

1+1

After the text you want to print on the screen you have to write

system("pause");

That will pause the function/code in somewhere of the code where you have to press a button for it to continue to function. We will use it in our code to pause the code so we can see it on the command line. Otherwise without the pause, the compiler will finish it in a millisecond and we wont be able to see the “Hello World!” on the screen. After Pause write

return 0;

Meaning

“The return statement causes the main function to finish. return may be followed by a return code (in our example is followed by the return code with a value of zero). A return code of 0 for the main function is generally interpreted as the program worked as expected without any errors during its execution. This is the most usual way to end a C++ console program.”

After all this your code should look something similar like mine below

#include <iostream>
using namespace std;
int main(void)
{

cout << “Hello World!” << endl;
system(“pause”);
return 0;
}

If you were able to see the hello world text, you have successfully compiled your first program. Otherwise, you did something wrong in the process for example forgot semicolons or added too many semicolons or there is something extra in your code. The output should look something like below depending again on the values you gave.

c++

As you can see there is something written in Finnish language “Jatka painamalla mitä tahansa näppäintä . . .” meaning, “Continue by pressing any key . . .”
The reason for that is the pause function that we added. Otherwise you would not have had the terminal open. Some might say that pause is a bad programming style and that you should never use it but for educational purposes, it do not think that there is any major reason why we should not use it. Always remember to save your work in different versions. The end of the C++ files is called .cpp.

Feel free to comment. I will update this section constantly with more theories and content.

BUS4TN007-3 / tehtävä 4 (assignment 4)

In this weeks assignment I had HC-SR04 Ultrasonic sensor that measures distance (Pictures below). I am sorry for the quality of the photos but it is something that we have to live with since I try to use as much as my own material as possible instead of using outside sources because a lot of the background information that I use in my assignments are from online sources and the coursebook that I have mentioned in the sources.

Anyway lets start with the assignment. Again I encourage you to see my older assignments for some background information. So when I started this assignment the very first problem that I encountered again was not being able to find the datasheet for this particular sensor but in the end I did manage to find the datasheet. Click this link to read the datasheet.

IMG_0190[1]

Note in the above picture that there is 4 pins and above the pins there is descriptions that mean the following:

VCC  = 5 volt supply
trig    = Trigger pulse input
echo = Echo pulse output
GND = Ground

IMG_0191[1]

IMG_0192[1]

IMG_0196[1]

So this sensor is all about using ultrasound to measure the distance of the object. The mechanism is close to how bats locate their food, other bats and objects. Basically it sends signal and the input comes when it bounces back from nearby objects. This way the sensor is able to calculate how far the object is. Please do note that it’s not easy to explain how sound moves from someone like me but I do know (Thanks to the internet) some basic things about it.The speed of sound = 343 seconds per meter or c = 343 m/s depending on the temperature of the air among other things. The sensor thus sends ultrasound (The speed depends) “where the measuring angle is 15 degrees”. Other things you should note are

– You should not worry about any health effects for small projects like this

– The sensor sends pulses (Look below and click on it to go to the original source)

pulse

Before I start with the assignment I must admit that I heavily borrowed code from other people because the test code looks pure evil but here is the link. I think that you can calculate the distance of the object by taking humidity into account also, but that is a bit more complicated code and I do not have time to go into that area.

The example code that I will be using is not mine so here is the link to the authors page, because why to invent something that was already invented. I just modified it a little bit, where Arduini will switch on the red LED when the object/s is out of range and when to switch the green LED on when the object is not out of range. The serial monitor print would be something like in the picture below.

serialMonitor

Where the object for example your hand is moving either closer or farther away from the sensor. You can also place an object like cardboard box in front of the sensor and move it slowly away from it. Here is the code bit to calculate the distance of the object.

distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 0){
  Serial.println(“Out of range”);
  digitalWrite(greenPin, LOW);
  digitalWrite(redPin, HIGH);
}
else {
  digitalWrite(redPin, LOW);
  digitalWrite(greenPin, HIGH);
  Serial.print(distance);
  Serial.println(” cm”);
}

Here is few pictures of the wiring itself and again I did the wiring like it is for testing purposes so it was meant to be messy and sorry for the quality of the photo.

IMG_0203[1]

IMG_0202[1]

IMG_0198[1]

And lastly here is the code. I will probably try to decipher the test code and come up with my own code or just make my own functions later but for now this is the loaned code to show the functionality of the HC-SR04 sensor.

#define trigPin 12
#define echoPin 13
const int redPin = 7;
const int greenPin = 8;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
}

void loop() {
int duration, distance; // creating variables
digitalWrite(trigPin, HIGH); // pin ON
delayMicroseconds(1000); //delay
digitalWrite(trigPin, LOW); // pin OFF
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 200 || distance <= 0){
Serial.println(“Out of range”);
digitalWrite(greenPin, LOW);
digitalWrite(redPin, HIGH);
}
else {
digitalWrite(redPin, LOW);
digitalWrite(greenPin, HIGH);
Serial.print(distance);
Serial.println(” cm”);

}
delay(500);
}

In the setup method we start the serial port for displaying the status of the sensor. We also define the bits per second.

“Sets the data rate in bits per second (baud) for serial data transmission. For communicating with the computer, use one of these rates: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200. You can, however, specify other rates – for example, to communicate over pins 0 and 1 with a component that requires a particular baud rate.

An optional second argument configures the data, parity, and stop bits. The default is 8 data bits, no parity, one stop bit.”

Where the sensor pins are given constant values with defined names.

"#define is a useful C component that allows the programmer to give a name to a constant value before the program is compiled. Defined constants in arduino don’t take up any program memory space on the chip. The compiler will replace references to these constants with the defined value at compile time.

This can have some unwanted side effects though, if for example, a constant name that had been #defined is included in some other constant or variable name. In that case the text would be replaced by the #defined number (or text).

In general, the const keyword is preferred for defining constants and should be used instead of #define.”

pinIn() means according to arduino website.

“Reads a pulse (either HIGH or LOW) on a pin. For example, if value is HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then waits for the pin to go LOW and stops timing. Returns the length of the pulse in microseconds. Gives up and returns 0 if no pulse starts within a specified time out.

The timing of this function has been determined empirically and will probably show errors in longer pulses. Works on pulses from 10 microseconds to 3 minutes in length.”

With the digitalWrite() we either give the pin values HIGH (On) or LOW (Off).

sources:

http://winkleink.blogspot.fi/2012/05/arduino-hc-sr04-ultrasonic-distance.html

http://blogs.helsinki.fi/kemma-keskus/

http://en.wikipedia.org/wiki/Ultrasound

https://docs.google.com/document/d/1Y-yZnNhMYy7rwhAgyL_pfa39RsB-x2qR4vP8saG73rE/edit?pli=1

http://www.satistronics.com/myfiles/file/Module/About%20UltracsonicModule.pdf

http://www.ebay.com.au/itm/Arduino-Ultrasonic-Ranging-Module-HC-SR04-Detector-/320588905524#ht_3014wt_1163

Make: Arduino Bots and Gadgets by Tero and Kimmo Karvinen

BUS4TN007-3 / tehtävä 3 (assignment 3)

This assignment was to make Parallax FlexiForce to work on Arduino Mega 2560. This was a bit trickier to build. The items you will need for this are

– 3 or 4 jumper wires
– Resistor (red, red orange, gold)  = 22,000 ohms ± 5%
– Arduino Mega 2560
– Parallax Flexiforce
– Arduino/computer USB connector
– Breadboard

Now before you start, please take a look at my previous assignments to be able to install the environment needed for the code and look up the logic behind Arduino functions. I also suggest to look up for the color codes for the resistors and the Flexiforce’s datasheet. Another thing I suggest you to search, is the symbols used in electronics and what they mean so you will easily understand what is going on when you read a map like the one I have posted below.

d

The logic behind the Flexiforce is the above picture. You might always see different tutorials in electronics but I always recommend you to look for the original data sheet and recommendation because I have always noticed that even if the tutorials had the working version of the electronic, a lot of them had problems in their wiring  Even I have some illegal wiring’s in my electronics every now and then.

Now in the Flexiforce you might see three pins but the middle pin under the Flexiforce is useless, because it is only used to keep the sensor down and steady. The sensor does not really have fixed GND/Ground and electricity input and output pins so use your common sense when making wiring. The picture is below.

IMG_0102[1]IMG_0103[1]

UPDATE: I have to add that in the upper pictures the wiring is a bit silly because in the Flexiforce sensor there is only two pins that are usable. As you can see, for some reason my group wired the middle pin to Arduino. A good reason to use common sense, because there was nothing on the Flexiforce itself that would have indicated that the middle pin is in use, as you can see on the datasheets. There is nothing connected to the pin.

IMG_0105[1]

So the sensor as I mention before (The tall tower like figure) is Flexiforce where by pinching the head of the sensor, the sensor will give values based on your wiring meaning that it will either have values starting from 0 to up or the other way around. If you look at the datasheet, you will see that by what logic does the sensor work.

The code is below

int sensor;

void setup()
{

Serial.begin(9600);

}

void loop()
{

sensor = analogRead(0);

Serial.print(“Sensor = “);
Serial.println(sensor);

delay(500);

}

Sources:

Make: Arduino Bots and Gadgets by Tero Karvinen
http://web.mit.edu/rec/Handouts/resistors.pdf
http://en.wikipedia.org/wiki/Electronic_color_code