Chapter 1
Basic Concepts of Programming
Conversions
Often, we need to convert the numbers to different bases. We will find two methods and it’s good to know both. The first will teach you how to do the conversions "by hand,” allowing you to understand things well. The second that of the calculator will allow you to make conversions without getting tired.
Decimal <-> Binary
To convert a decimal number (in base 10) to a binary number (in base 2, you follow that's good.), You need to know how to divide by 2. Will it be okay? Take your number, then divide it by 2. Then divide the quotient obtained by 2, then so on until you have a zero quotient. Then you have to read the remains from bottom to top to get your binary number.
Binary <-> Hexadecimal
Converting from binary to hexadecimal is the easiest to do.
First, start grouping the bits in blocks of four starting at the right. If there are not enough bits left to make the last group of four, we add zeros.
Take the number 42, which is written in binary, as we have seen, 101010, and we will get two groups of 4 bits, which will be 0010 1010. Then, calculate block by block to obtain a hexadecimal digit taking into account the value of each bit. The first bit of low weight (far right) will be worth, for example, A (: A in hexadecimal). Then the other block will simply be worth 2 (). So 42 in the decimal base is worth 2A in the hexadecimal base, which is also written to pass from
hexadecimal to binary, it suffices to do the reverse operation with the help of the decimal base from time to time. The procedure to follow is as follows:
-
I separate the numbers one by one (we get 2 and A)
-
I "convert" their values to decimal (which makes us 2 and 10)
-
I put these values in binary (and we, therefore, have 0010 1010)
Decimal <-> Hexadecimal
This case is more delicate to treat because it requires to know the multiplication table by 16. As you have followed the previous explanations, you understand how to do it here. As I am bad at math, I would advise you to go through the binary base to do the conversions.
QUICK Method
For this, go to Start / All programs / Accessories / Calculator. Who Said I Was Lazy?
You see at the top, that there are options to check to display the number entered in the base that we want. Currently, I am in base 10 (decimal - Dec button). If I click on Hex:
I see that my number 42 has been converted to 2A. And now if I click on Bin:
Yes, that's right. Why didn't we start by explaining that? Who knows.
Now that you have acquired the essential basics to continue the book, we will see how the material you bought looks and which we will need to follow this book.
The Software
To give you a little extra time to get your Arduino board, I will
briefly show you how the Arduino software looks.
Installation
There is no need to install the Arduino software on your computer since it is a portable version. Let's look at the steps together to prepare your computer for using the Arduino board.
Downloading
To download the software, go to the download page of the Arduino.cc website. You have two categories:
Download: In this category, you can download the latest version of the software. Windows platforms,
The software supports Linux and Mac. This is where you will download the software.
Previous IDE Versions: In this category, you have all the versions of the software, under the platforms previously mentioned, since the beginning of its creation.
Windows
For me, it will be under Windows. I click on the Windows link, and the file appears:
Once the download is complete, you have to decompress the file with a decompression utility (7-zip, WinRar, etc.). Inside the folder are a few files and the software executable:
Mac Os
Click on the Mac OS link. A.dmg file appears. Save it.
Double-click on the.dmg file: There is the Arduino application (.app), but also the driver to install (.mpkg). Proceed with the driver installation then install the application by dragging it into the shortcut of the "Applications" folder, which is normally present on your computer.
Under Linux
Nothing could be simpler, by going to the software library, look for the "Arduino" software. Several outbuildings will be installed at the
same time.
Software Interface Software Launch
Launch the software by double-clicking on the icon with the "infinite" symbol in green. It is the executable of the software. What jumps out at first is the clarity of the presentation of the software. We immediately see its intuitive interface.
Correspondence
Frame number 1: these are the software configuration options
Frame number 2: it contains the buttons that will serve us when we are going to program our cards Frame number 3: this block will contain the program that we are going to create
Frame number 4: This is important because it will help us to correct the faults in our program. It's a debugger.
Approach and Use of the Software
Let's take a more serious look at the use of the software. The menu bar is surrounded in red and numbered by number 1.
The File Menu
It is mainly this menu that we will use the most. He has several things that are going to be very useful to us:
New: will allow you to create a new program. When this button is pressed, a new window, identical to this one, appears on the screen.
Open: with this command, we will be able to open an existing program
Save / Save as: save the current document/request where to save the current document
Examples: this is important; a whole list is scrolled to display the names of examples of existing programs; here, you can help you create your own programs.
The rest of the menus are not interesting for the moment, we will come back to this later, before starting to program.
Buttons
Now let's see what the buttons are for, framed in red and numbered by the number 2.
Button 1: This button allows you to check the program, it activates a module that searches for errors in your program
Button 2: Create a new file
Button 3: Save the current program Button 4: We do not touch it for the moment Button 5: Stop the verification
Button 6: Load an existing program
Button 7: Compile and send the program to the card
Finally, we will be able to take care of the equipment that you should all have right now: the Arduino board.
Equipment
I hope that you now have the equipment required to continue the book because, in this chapter, I will show you how your card looks, then how to test it to verify that it works.
Presentation of the Card
To start our discovery of the Arduino board, I will present the board itself. We will see how to use it and with what. I have represented in red on this photo the important points of the map.
Constitution of the Card
Let's see what these important points are and what they are used for.
The micro-controller - This is the brain of our map (in 1). It will receive the program you have created and store it in the memory and then execute it. Thanks to this program, it will know how to do
things suchs as: flashing an LED, displaying characters on a screen, sending data to a computer, etc.
Materials
To operate, the card needs a power supply. The microcontroller operating under 5V, the card can be supplied with 5V by the USB port (in 2) or by an external power supply (in 3), which is between 7V and 12V. This voltage must be continuous and can, for example, be supplied by a 9V battery. A regulator then takes care of reducing the voltage to 5V for the proper functioning of the card. No danger of toasting everything. Please only respect the interval of 7V to 15V (even if the regulator can support more, do not bother to subtract it within its limits)
Visualization
The three "white dots" circled in red (4) are, in fact, LEDs whose size is of the order of a millimeter. These LEDs are used for two things:
The one at the top of the frame: it is connected to a pin of the microcontroller and will be used to test the hardware.
Note: When you connect the card to the PC, it flashes for a few seconds.
The two LEDs at the bottom of the frame: are used to display activity on the serial channel (one for transmission and the other for reception). The downloading of the program in the microcontroller being done in this way, one can see them flashing during the loading.
Connectivity
The Arduino board does not have any components that can be used for a program, put by the LED connected to pin 13 of the microcontroller, and it is necessary to add them. But to do this, you must connect them to the card.
For example, we want to connect an LED to an output of the microcontroller. connect it, with a resistor in series, to the card, on
the card's connection plugs.
This connection is important and has a pinout that must be respected. We will see it when we learn to do our first program. It is with this connection that the card is "expandable,” because you can connect all types of assemblies and modules. For example, the Arduino Uno board can be extended with shields, such as the "Ethernet Shield," which allows the latter to be connected to the internet.
Installation
To use the card, it must be installed. Normally, the drivers are already installed under GNU / Linux. Under Mac, double click on the.mkpg file included in the download of the Arduino application, and the installation of the drivers is executed automatically.
Windows
When you connect the card to your computer on the USB port, a small message appears at the bottom of the screen. Theoretically, the card you use should install itself. However, if you are on Win 7 like me, it may not work the first time. In this case, leave the card connected and then go to the control panel. Once there, click on "system," then in the left panel, select "device manager." Once this menu is open, you should see a component with a yellow "caution" sign. Right-click on the component and click "Update Drivers." In the new menu, select the option "Search for the driver myself." Finally, you have to select the right folder containing the driver. It is in the Arduino folder that you had to unzip a little earlier and is called "drivers" (be careful, don't go down to the "FTDI" folder). For example, for me, the path will be:
[The way-to-folder] \ Arduino-0022 \ Arduino-0022 \ drivers
It seems that there are problems using the French version of Arduino (the drivers are missing from the file). If this is the case, you will need to download the original version (English) to install the
drivers. After installation and a sequence of flashing on the micro-LEDs of the card, it should be functional; a small green LED indicates that the card is properly powered.
Test your Equipment
Before starting to program the head down, it is first of all necessary to test the correct functioning of the card. Because it would be silly to program the card and look for errors in the program when the problem comes from the card. > <We will test our hardware by loading a program that works on the card. But we haven't made any programs yet?
Barely. But the Arduino software contains sample programs. Well, these are the examples that we will use to test the card.
1st step: Open a Program
We are going to choose a very simple example that consists of making a LED flash. His name is Blink, and you will find him in the Basics category.
Last Step
Now, we will have to send the program to the card. To do this, click on the Upload button.
At the bottom of the image, you see the text: "Uploading to I / O Board...,” this means that the software is sending the program to the card.
The message display: "Done uploading" indicates that the program has been loaded onto the card. If your hardware is working, you should have a flashing LED on the board:
If you do not get this message but rather something in red, do not worry, the equipment is not necessarily defective.
Indeed, several errors are possible:
- IDE recompiles before sending code, check for error
- The serial channel may be badly chosen, check the connections and the choice of the serial channel
- the IDE is coded in JAVA, it can be capricious and bug from time to time (especially with the serial channel...): try the sending again.
The Arduino Language (1/2)
To be able to program our card, we need three things:
It is this last point that we must acquire. The purpose of this chapter is to teach you how to program with the Arduino language. However, this is only a book material that you can browse when you have to program your card by yourself. Indeed, it is by manipulating that you learn, which implies that your programming learning will be more consistent in the next chapters than in this book itself.
I specify a small hazard: the Arduino language not having the coloring of its syntax in the zCode. I will put it as C code because their syntax is very close:
Code: C
// here is colored Arduino code thanks to the "code: C" tag in zCode
void setup ()
{
//...
}
The Arduino language is very close to C and C ++. For those whose knowledge of these languages is based, do not feel obliged to read the two chapters on the Arduino language. Although there are some somewhat important points.
Language syntax
The syntax of a programming language is the set of writing rules linked to this language. We will, therefore, see in this section the rules which govern the writing of the Arduino language.
The Minimum Code
With Arduino, we have to use minimal code when creating a program. This code allows dividing the program that we are going to create into two big parts.
Code: C
void setup ()
{
// card initialization function
// content of initialization
}
void loop () // main function, it repeats (runs) endlessly
{
// content of your program
}
So you have before you the minimum code to insert into your program. But what can it mean for someone who has never programmed?
Function
In this code, there are two functions. Functions are portions of code.
Code: C
void setup ()
// card initialization function
{
// content of initialization
// we write the code inside
}
This setup () function is called only once when the program starts. This is why it is in this function that we will write the code which only needs to be executed once. This function is called: "initialization function." We will find the implementation of different outputs and some other settings. It's a bit like the start-up check-up. Imagine an airplane pilot in his cabin doing the inventory:
- leg 2 at the exit, high state?
-
OKAY
- timer 3 to 15 milliseconds?
-
OKAY
Once you have initialized the program, you must then create your "heart,” in other words, the program itself.
Code: C
void loop () // main function, it repeats (runs) endlessly
{
// content of your program
}
It is, therefore, in this loop () function where we will write the content of the program. It should be known that this function is called permanently, that is to say, that it is executed once, then when its execution is finished, it is re-executed and again and again. We are talking about an infinite loop.
For your information, you don't have to write anything on these two functions. However, it is mandatory to write them, even if they do not contain any code.
The Instructions
In these functions, what do we write? This is precisely the purpose of this paragraph.
In your list for dinner tonight, you write down the important tasks
that await you. These are instructions. The instructions are lines of code that say to the program: "do this, do that." It is very simple but very powerful because it is what will orchestrate our program.
The semicolons end the instructions. If, for example, I say in my program: "call the function cutFromSausage" I must put a semicolon after calling this function.
Semicolons (;) are synonymous with errors because they are very often forgotten at the end of the instructions. Therefore, the code does not work, and the search for the error can take us considerable time. So be careful.
The Braces
The braces are the "containers" of the program code. They are specific to functions, conditions, and loops. The program instructions are written inside these braces. Sometimes they are not mandatory in the conditions (we will see below what it is), but I recommend to put them all the time. This will make your program more readable.
Comments
Finally, we will see what a comment is. I already put some in the example codes. These are lines of code that will be ignored by the program. They are useless during the execution of the program. But then is it useless?
No, because this will allow the programmers who will read your code and us (if there are any) to know what the line of code you wrote means. It is very important to put comments, and it also makes it possible to resume a forgotten program more easily.
If, for example, you are unfamiliar with an instruction that you have written in your program, you put a comment line to remind you the next time you read your program what the line means.
Single comment line:
Code: C
// this line is a comment on ONLY ONE line
Line or paragraph on several lines:
Code: C
/ * this line is a comment, on SEVERAL lines
which will be ignored by the program, but not by anyone who reads the code
;) * /
Accents
It is strictly forbidden to put accents in programming, except in the comments.
The Variables
As we have seen, in a microcontroller, there are several types of memory. We will only deal with "live" memory (RAM) and "read-only" memory (EEPROM).
I'm going to ask you about a problem. Let’s say you’ve connected a push button to a pin on your Arduino board. How will you store the state of the button (pressed or off)?
What is a Variable?
A variable is a number. This number is stored in a memory space (RAM) of the microcontroller. The way to store them is similar to that used to store shoes: in a numbered locker.
Shoes stored in numbered boxes
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
9
|
10
|
11
|
12
|
13
|
14
|
15
|
16
|
17
|
18
|
19
|
20
|
21
|
22
|
23
|
24
|
25
|
26
|
27
|
28
|
29
|
30
|
31
|
32
|
33
|
34
|
35
|
36
|
37
|
38
|
39
|
40
|
41
|
42
|
43
|
44
|
45
|
46
|
47
|
48
|
49
|
50
|
51
|
52
|
53
|
54
|
55
|
56
|
57
|
58
|
59
|
60
|
A Variable is a Number
This number has the distinction of changing its value. Strange, isn't it? Well, not that much, because a variable is the container of the number in question. And this container will be stored in a memory box. If we materialize this explanation by a diagram, it will give:
number => variable => memory
the symbol "=>" meaning: "is contained in..."
The Name of a Variable
The variable name accepts almost all characters except:
. (point)
, (the comma)
é, à, ç, è (the accents)
Well I will not give them all, it only accepts the alphanumeric alphabet ([a-z], [A-Z], [0-9]) and _ (underscore)
Define a Variable
If we give a number to our program, it doesn't know if it's a variable or not. You have to tell it. For that, we give a type to variables. Yes, because there are several types of variables. For example, the variable "x" has a value of 4, so it is an int type.
Code: C
Well, this code would not work because it is not enough. Indeed, there is a multitude of numbers: whole numbers, decimal numbers, etc. This is why we must assign a variable to a type.
These are the most common types of variables:
int integer -32,768 to +32,767 16 bit 2 byte
long integer -2 147 483 648 to +2 147 483 647 32 bits 4 bytes
whole char -128 to +127 8 bits 1 byte
decimal float -3.4 x to +3.4 x 32 bit 4 byte
double decimal -3.4 x to +3.4 x 32 bit 4 byte
For example, if our variable "x" only takes decimal values, we will use the types int, long, or char. If now the variable "x" does not exceed the value 64 or 87, then we will use the char type.
If, on the other hand, x = 260, then we will use the higher type (which accepts a greater quantity of number) than char, in other words, int or long. But you're not smart; to avoid overspending, we put everything in double or long.
Yes, but no. A microcontroller is not a 2GHz multicore computer, 4GB of RAM. Here we are talking about a system that works with a CPU at 16MHz (0.016 GHz) and 2 KB of SRAM for the RAM. So there are two reasons why you should choose your variables wisely:
- RAM is not extensible when there is more, and there is more.
- The processor is of the 8-bit type (on Arduino UNO), so it is optimized for processing on variables of 8-bit size, processing on a 32-bit variable will, therefore (much) take longer.
If our variable "x" never takes a negative value (-20, -78,...), then we will use an unsigned type. That is, in our case, a char whose value is no longer from -128 to +127, but from 0 to 255.
Here is the table of unsigned types, we identify these types by the word unsigned which precedes them:
Type what number does it store? Maximum values of the stored number, Number of bits and Number of bytes like below:
-
unsigned non-negative integer char 0 to 255 - 8 bits, 1 byte
-
unsigned int non-negative integer 0 to 65,535 - 16 bits, 2 bytes
-
unsigned long non-negative integer 0 to 4,294,967,295 - 32 bits, 4 bytes
One of the peculiarities of the Arduino language is that it accepts a larger number of types of variables.
Type what number does it store? Maximum values of the stored number, Number on X bits Number of bytes like below:
-
byte non-negative integer 0 to 255 8 bits 1 byte
-
non-negative integer word 0 to 65535 16 bit 2 byte
-
non-negative integer boolean 0 to 1 1 bit 1 byte
The Arduino Language (2/2)
I have a question. If I want to make the code I wrote repeat itself, do I have to copy it as many times as I want? Or is there a solution?
This is an excellent question because it is precisely the object of this chapter. We will see how to make a piece of code repeat itself. Then we will see, next, how to organize our code so that it becomes more readable and easy to debug. Finally, we will learn to use the tables that will be very useful.
Here is the program waiting for you.
import processing.video.*;
Movie movie;
void setup()
{
size(640,360);
background(0);
//load and play the video in a loop
movie = new Movie(this,"transit.mov");
movie.loop();
}
void movieEvent(Movie m)
{
m.read();
}
void draw()
{
//if (movie.available() == true)
//{
// movie.read();
//}
image(movie,0,0,width,height);
}
What is a Loop?
In programming, a loop is an instruction that makes it possible to repeat a piece of code. This will allow us to repeat an end of program or an entire program.
There are two main types of loops:
The conditional loop tests a condition and executes the instructions it contains as long as the condition tested is true.
The repeat loop executes the instructions it contains a predetermined number of times.
The while loop
Problem: I want the electric shutter of my window to close automatically when night falls. We will not take care of making the system that closes the shutter at the arrival of the night. The Arduino board has a sensor which indicates the position of the flap (open or closed). What we are trying to do is create a piece of code that brings the shutter down until it is closed.
To solve the problem, we will have to use a loop.
/ * HERE, a bit of program allows you to do the following things:
_ a sensor detects nightfall and daybreak o If it is night, then we must close the shutter
o Otherwise, if it is the day, we must open the shutter
_ the program reads the state of the sensor which indicates whether the shutter is open or closed
_ recording of this state in the String variable: position_volet
o If the shutter is open, then: position_volet = "open";
o Otherwise, if the shutter is closed: position_volet = "closed";
* /
while (position_volet == "open")
{
// instructions that lower the shutter
}
The do... while loop
This loop is similar to the previous one. But there is a difference that matters. In fact, if we pay attention to the condition in the while loop, we will notice that it is tested before entering the loop. While loop, the condition is tested only when the program has entered the loop:
Code: C
do
{
the instructions between these braces are repeated as long as the condition is false } while (/ * condition to test * /);
The word does come from English and translates as do. So the do while loop means "do the instructions, as long as the condition tested is false." While in a while loop, you could say, "as long as the condition is false, do the following."
What Does it Change?
Well, in a while loop, if the condition is true from the start, we will never enter this loop. Conversely, with a loop do while we enter the loop, then we test the condition. Let's take our counter:
let i = 5;
do {
alert( i );
i++;
} while (i > 5);
In this code, the counter value is defined from the start at 5. However, the program will enter the loop when the condition is false. So the loop is executed at least once. And whatever the veracity of the condition. In the test it gives:
Concatenation
A loop is an instruction that has been spread over several lines. But we can write it on one line:
while(…) {…}
This is why you should not forget the semicolon at the end (after the while). While in a simple while loop, the semicolon should not be put.
The for loop
This is a very special loop. What it will allow us to do is quite simple. This loop is executed X times. Unlike the two previous loops, we must give it three parameters.
First, we create the loop with the term for (means "for that"). Then, between the parentheses, we must give three parameters which are creation and assignment of the variable to a starting value followed by the definition of the condition to be tested followed by the instruction to execute
The Arduino language does not accept the absence of the following line:
We are forced to declare the variable we are going to use (with its type) in the for a loop.
So, if we link this line: "FOR counter = 0 and counter less than 5, we increment counter". More concisely, the loop is executed as many times as it takes counter to get to 5. So here, the code inside the loop will be executed five times.
The infinite loop
The infinite loop is very simple to achieve, especially since it is sometimes very useful. You need to use a while and assign it a value that never changes. In this case, we often put the number
We can read: "As long as the condition is equal to 1, we execute the loop". And this condition will always be met since "1" is not a variable but a number. Also, it is possible to put any other whole number, or the boolean "TRUE":
do {
Block of statements;
}
while(1);
This will not work with the value 0. Indeed, 0 means "false condition," so the loop will stop immediately... The loop () function behaves like an infinite loop since it repeats itself after it has finished executing its tasks.
The Functions
In a program, the lines are often numerous. It then becomes imperative to separate the program into small pieces to improve the readability of it, in addition to improving the operation and facilitating debugging. We will see together what a function is, and then we will learn how to create and call them.
What is a Function?
A function is a "container" but different from the variables. Indeed, a variable can only contain a number, while a function can contain an entire program.
In fact, when we program our Arduino board, we will write our program in functions. For the moment, we only know 2: setup () and loop ().
In the previous example, instead of the comment, we can put instructions (conditions, loops, variables, etc.). This is these
instructions that will make up the program in itself.
To be more concrete, a function is a piece of program that allows you to perform a specific task. For example, to format a text, you can color a word in blue, put the word in bold or even enlarge this word.
Bold - to put the word in bold color, to put the word in blue enlarge, to increase the size of the word in programming, we will use functions. So these functions are "divided into two large families." What I mean by that is that there are ready-made functions in the Arduino language and others that we will have to create ourselves.
You cannot write a program without putting functions inside. We are forced to use the setup () and loop () function (even if we don't put anything in it). If you write instructions outside of a function, the Arduino software will systematically refuse to compile your program. There are only global variables that you can declare outside of the functions.
I did not really understand what it is for
The usefulness of a function lies in its ability to simplify the code and separate it into "little bits" that we will assemble to create the final program. If you want, it's a bit like plastic building sets: each piece has its own mechanism and performs a function.
For example, a wheel makes it possible to roll; a block makes it possible to join several other blocks together; a motor will move the
created object forward. Well, all these elements will be assembled to form an object (car, house, etc.). like, the functions will be joined together to form a program. For example, we will have the function: "squaring a number"; the function: "add a + b"; etc. Which, in the end, will give the desired result.
Make a Function
To make a function, we need to know three things:
Function Name
To start, we will, first, choose the name of the function. For example, if your function has to retrieve the temperature of a room supplied by a temperature sensor: you will call the function RoomTemperaturePiece, or room_temperature_piece, or lecture_temp_piece.
Well, names can be given full, but be logical about the choice of the latter. It will be easier to understand the code than if you call it tmp (for temperature). An explicit function name guarantees quick reading and easy understanding of the code. A reader should know what the function is doing by name, without reading the content.
Types and Parameters
The purpose of the functions is to split your program into different logical units. Ideally, the main program should only use function calls, with minimal processing. To be able to function, they mostly use "things" as inputs and return "something" as outputs. The inputs will be called function parameters, and the output will be called the return value.
The Settings
The parameters are used to feed your function; they are used to give
information to the process it must carry out. Let’s take a concrete example.
To change the state of an output of the microcontroller, Arduino offers the following function: digitalWrite (pin, value). Thus, the reference explains to us that the function has the following characteristics:
-
pin parameter: the number of the pin to be changed
-
value parameter: the state in which to put the spindle (HIGH, (high, + 5V) or LOW (low, ground))
-
return: no return of result
As you can see, the example is self-explanatory without reading the function code. Its name, digitalWrite ("digital writing" for anglophobes), means that we will change the state of a digital pin (therefore not analog). Its parameters also have explicit names, pin for the pin to change, and value for the state to give it.
When you go to create functions, it is up to you to see if they need parameters or not. For example, you want to do a function that pauses your program, and you can do a Pause () function that takes a parameter of type char or int, etc. (this will depend on the size of the variable). This variable will, therefore, be the parameter of our Pause () function and will determine the duration during which the program will be paused.
We will, therefore, obtain, for example, the following syntax: void Pause (char duration).
To sum up a bit, we have the choice of creating empty functions, therefore without parameters, or else "typed" functions that accept one or more parameters.
But what is "Void"?
I arrive there. Remember, a little above, I explained to you that a
function could return a value, the famous output value, I will now explain how it works.
Empty Functions
We have seen that a function could accept parameters. But it is not compulsory. A function that does not accept parameters is empty.
We, therefore, use the void type to say that the function will have no parameters. A void type function cannot return a value. For example:
void Arrange(int left,int right){
int i,j,x,w;
i=left,j=right;
x=(left+right)/2;
do{
while(struct[i].number < struct[x].number)i++;
while(struct[j].number > struct[x].number)j--;
if(i<=j){
w=struct[i].number;
struct[i].number=struct[j].number;
struct[j].number=w;
i++;j--;
}}while(i<=j);
if(left<j)
return Arrange(left,j); //1st recursive call. It doesn't work.
if(right>i)
return Arrange(i,right); //2nd recursive call.It doesn't work either.
};
This code will not work because the function () is of type void. However, it must return a variable that is of type int. Which is impossible.
The "Typed" Functions
Indeed, if we want to create a function that calculates the result of an addition of two numbers (or a more complex calculation), it would be good to be able to return the result directly rather than to store it in a variable which has a global scope and access that variable in another function.
Clearly, calling the function gives us the result directly. We can then do "what we want" with this result (store it in a variable, use it in a function, make it undergo an operation,...)
How to Create a Typed Function
In itself, this is not complicated, and you have to replace the void with the chosen type (int, long, etc.) Here is an example:
void setup(){
Serial.begin(9600);
}
void loop() {
int i = 10;
int j = 44;
int k;
k = myMultiplyFunction(i, j); // k now contains 440
Serial.println(k);
delay(500);
}
int myMultiplyFunction(int x, int y){
int result;
result = x * y;
return result;
}
Note that I have not put the two main functions, namely setup () and loop (), but they are mandatory.
In the loop () function, we do a calculation with the value returned by the function myFunction (). In other words, the calculation is: calculation = 10 * 44; Which gives us: calculation = 440.
Well, this is a very simple example to show you how it works. Later, when you are ready, you will certainly use this combination in a more complex way.
As this example is very simple, I did not write the value returned by the function myFunction () in a variable, but it is better to do so. At least, when it is useful, which is not the case here?
Functions with Parameters
It's all very nice, but now you're going to see something much more interesting. Here is a code; we will see what it does after:
void loop(){
int i = 2;
int j = 3;
int k;
k = myMultiplyFunction(i, j); // k now contains 6
}
What is going on?
I defined three variables: sum, x, and y. The function of my Function () is "typed" and accepts parameters. Let's read the code at the beginning:
void setup(){
Serial.begin(9600);
}
void loop() {
int i = 2;
int j = 3;
int k
;
k = myMultiplyFunction(i, j); // k now contains 6
Serial.println(k);
delay(500);
}
int myMultiplyFunction(int x, int y){
int result;
result = x * y;
return result;
}
We Declare our Variables
The loop () function calls the myFunction () function that we created
It is on this last point that we will look. We gave the parameters function. We use these parameters to "feed" the function. To put it simply, we say to the function: "These are two parameters, I want you to use them to do the calculation I want."
Then comes the signing of the function
The signature... what are you talking about?
The signature is the "full title" of the function. Thanks to it, we know the name of the function, the type of the returned value, and the type of the different parameters.
The function retrieves the variables sent to it from variables. In other words, in the variable param1, we find the variable x. In the variable param2, we find the variable y.
Either: param1 = x = 64 and param2 = y = 192.
Finally, we use these two variables created "on the fly" in the function's signature to perform the desired calculation (a sum in our case).
What's the point of doing all this? Why don't we use the variables x and y in the function?
This will help us to simplify our code. For example, you want to do several operations (addition, subtraction, etc.), and instead of creating several functions, we will only create one that does them all. But, to tell it which operation to do, you will give it a parameter telling it: "Multiply these two numbers" or else "add these two numbers."
What it would do:
So if the operation variable is 0, we add the variables x and y; otherwise, if the operation is 1, we subtract y from x. Simple to understand, isn't it?
The Tables
As the name suggests, this part will talk about tables.
What is the point of talking about this? Well, think again, on the computer a table has nothing to do. If we had a lot to summarize, an array is a big variable. Its purpose is to store elements of the same types by putting them in boxes. For example, a teacher who stores the grades of his students will use a floating table (a floating-point number) with one box per student.
We will use this example throughout this section. Here are some details to understand everything: each pupil will be identified by a number going from 0 (the first pupil) to 19 (the twentieth pupil of the class) one starts from 0 because in data processing the first value in a table is 0.
A Table in Programming
A table, like in Excel, is a set made up of boxes, which will contain information. In programming, this information will be numbered. Each box in an array will contain a value.
What's the Point?
We will mainly use arrays when we need to store information without creating a variable for each information.
The Maximum Score
As the title indicates, we will look for the maximum grade (the best student in the class). The function will receive in parameter the array of float, the number of elements in this array, and will return the best note.
Code: C
float bestNote (float array [], int highNumber)
{
int i = 0;
int max = 0; // variables containing the highest grade
for (i = 0; i <highNumber, i ++)
{
if (table [i]> max) // if the grade read is better than the best current
{
max = array [i]; // then we save it
}
}
return max; // we return the best grade
}
What you do to read an array is exactly the same as when you initialize it with a loop.
It is quite possible to put the value of the searched box in a variable:
Code: C
int value = array [5]; // we save the value of the box
6 of the array in a variable
Well, it was not that hard; you can do the same to find the minimum value To practice.
Average Calculation
Here, we will look for the average of the grades. The signature of the
function will be exactly the same as that of the previous function, unlike the name. Let you think, here is the signature of the function, the code is lower but try to find it yourself before:
Code: C
float mediumNote (float array [], int numberHigh)
A solution:
Secret (click to display)
Code: C
float mediumNote (float array [], int numberHigh)
{
int i = 0;
double total = 0; // add all the grades
average float = 0; // average of grades
for (i = 0; i <highNumber; i ++)
{
total = total + table [i];
}
mean = total / number High;
average return;
}
We finish with the tables, we may see more things in practice.
Now you are joyful because you have finished the first part.
You are ready to start using your card. So go to the next part of the book.