Você está na página 1de 6

Arduino Tutorial 6 - Data types and structures

Recap : We have used a variable of type integer, to store the pin number that our LED connects to.
For example : int blue_led = 4; // our blue led is connected to Arduino pin 4.

Project : Today we look at types of data used with Arduino, plus arrays, pointers and strings.

As humans, we deal with all sorts of “data” automatically.


If I say I am 40 yrs old, you automatically understand that 40 is an integer (called a whole number).
If I say the temperature is 28.6 degrees, you understand 28.6 is a “floating point” or decimal number.
If I say my name is John, you automatically understand that “John” is a string of 4 alphabetic characters.
If I say the door is open, you automatically know the door is not closed - ie a True/False type of statement.

The number 40; the name John and the condition Open/Closed are examples of different data types.

Computers ( including the Arduino) at their core, only perform simple arithmetic – on integers.
The ALU (Arithmetic Logic unit ) doesn’t care what that data represents to you - the user, be it text, integer
values, floating point values, or even part of the program code.

You, the programmer, tell the compiler that this value is an integer and that value is a floating point number.
The compiler converts the instructions in your script ( which includes your data statements), into binary
code the computer chip can process or execute. The CPU never “understands” the code, it just executes it.

Data Types - Here is a list of the data types commonly seen in Arduino sketches: (Yes – there are others).

boolean (8 bit) - simple logical true/false. For example boolean door_closed = false;
byte (8 bit) - unsigned integer from 0 to 255. For example byte motor_speed = 147;
char (8 bit) - signed integer from -128 to +127.
word (16 bit) - unsigned integer from 0 to 65535 .
int (16 bit) - signed integer from -32768 to +32767. For example int blue_led = 4;
unsigned int (16 bit)- the same as ‘word’. Use ‘word’ instead for clarity and brevity
unsigned long (32 bit) - unsigned integer 0 to 4,294,967,295. For example, to store the result of the
millis() function, which returns the number of milliseconds the current code has been running
long (32 bit) - signed integer from -2,147,483,648 to +2,147,483,647
float (32 bit) - signed decimal from -3.4028235E38 to +3.4028235E38. Floating point on the Arduino is
not native; the compiler has to jump through hoops to make it work. Avoid using “float” if you can.

The number in brackets is the memory SIZE the variable takes. To understand what a BIT is, read on:

Bits, Bytes and Buses ( or – how computers really work).

The Arduino Uno uses an 8 bit CPU (Central Processing Unit). What does this mean?
It means the CPU can process (transfer and store) 8 bits of information at a time.
(The first most widely used processor - the Intel 8080 made in 1972 – used 8 bits).
Think of a highway - a single lane can handle one car (bit); 8 lanes can “process” 8 cars (bits).
A “bit” is a single numeric value of either 1 or 0. It is the basis of all computers.
It encodes a single unit of information in digital form – vis on or off.
This can be done with a transistor being ON or OFF for example.
(The word BIT comes from BInary digiT).

Combine 8 bits and you get a BYTE. ( eg change from a single lane to an 8 lane highway).
The “lanes” of a computer are called a “Bus” (from the Latin omnibus, meaning "for all").
There are 256 different combinations of ON/ OFF with 8 bits ( 2 states for each of 8 bits = 2↑8) .
Try it on your calculator. 2 x 2 is 4; Try 2x2x2x2x2x2x2x2 ( = 256 ).
Since computers include 0 as the first “number”, this lets you store up to 255 (See BYTE above).
The BYTE was also used to store the ALPHABET. In 1963 a standard was created called the
“ American Standard Code for Information Interchange “ or ASCII (See table on last page).
Every “Character” ( including graphics) used in teletypes was assigned a number from 0 to 255,.
For example , upper case “A” is 65, lower case “a” is 97. Number “1” is 49; “=” is 61.
( Open a text editor, Hold the ALT key; using the numeric keypad, press 6 5 then release the ALT).

Arduino (and the language C++) use the keyword “byte” as a type of data. It takes up 8 “bits” of
memory, and can hold an unsigned number from 0 to 255. Now you know why.

The data type “word”, takes up 16 bits , and can hold a number from 0 to 65,535.
Use your calculator to work out 2↑16.
The data type “int” also uses 16 bits, and can store a signed number from -32768 to +32767.
The data type “unsigned long” uses 32 bits.
Modern computer chips currently use 64 bit processors (eg 64 wide highway or Bus).
Computer memory – including USB memory sticks and camera/phone memory cards - is often in
Gigabytes (for example your USB memory stick may hold 16 gigabytes. )
A Kilobyte (kB) is 1000 bytes;
A Megabyte (MB) is 1000 KB = 1 million bytes (1 MiB = 2 to the 20th power = 1,048,576 bytes;)
A Gigabyte (GB) is 1000 MB, so your 16 GB USB stick holds 16 x 1000 x 1000 x 1000 x 8 bits.
Hard disk drives are commonly in TB or Tetrabytes. Larger computers use Petabytes and Exabytes.

To display the size in bytes of each data type, run the sketch on the last page of this tutorial.
(For an excellent tutorial - mathbits.com/MathBits/CompSci/DataBasics/Datamain.htm)
You now know enough about Bits and Bytes. Let's return to the main topic of data types.

Characters - So you know how to handle numbers – either integers or decimal, large and small.
Bits and bytes are all “numbers”, so how do we deal with text or strings?

Humans recognise text as a collection of alpha characters.


A computer only uses binary – a collection of 0 and 1's.
Arduino does have a data type called “char” . Can we use this variable type for characters ?
If we could join a group of char together, we could store text, or a “string”.
A group is called an “array”. We tell the computer that a variable is an “array” by [];
- for example char greeting[] = "Hello"; // text is always put in inverted commas “”

The variable named greeting, is an array with 6 “elements” of type char.


Why 6 : because C++ adds a special “NULL” character at the end of every array \0.
The first element is H; so greeting[0] = “H”. greeting[1] = “e”; etc (Try it on your Arduino).
NOTE 1 – Computers start counting from 0, so the first element is [0].
NOTE 2 – In Arduino, char is signed – eg -128 to +127. The standard ASCII character set
goes from 0 to 127, so signed char will contain all the “standard” characters.
NOTE 3 – A Variable name (eg greeting) must be Alphanumeric, and is case sensitive.
Valid names : My, my34, i, gemStone. Invalid : 34my, %, gem Stone.
Since names are case sensitive, my and My are different variables.
NOTE 4 – The keyword const can be added, to create constants. const int radius =5;
Try this example on your Arduino :

// An example of using the data type char for text information.


char greeting[] = "Hello" ; // create an array called greeting, of type char, and assign Hello.

void setup()
{
Serial.begin(9600); // Begin serial communication – eg to your PC monitor
Serial.println(greeting); // Print to your monitor, the variable called - greeting
Serial.println(greeting[0]); // Print to your monitor the 1st element of greeting.
Serial.print( "The value in greeting[0] is : ");
Serial.println(greeting[0], DEC); // Print the DECimal value of the first element
}
void loop()
{
}

Guess what the ASCII code is for “H” ? So your Arduino is really only dealing with integers after all.

You can even have a “group” of arrays. In this special case, we use char*, where the * means pointer.
Note – avoid char*. Use String as explained in the next section.

String - Arduino has a special class called - String. To explain class -


Car is a class of Automobile. Camry is an object (or instance) of the class car.
You can do things (functions) to a car – you can Drive it; Park it; Wash it, Sell it etc.

You can do things (functions) to a String - length(); concat(): compareTo(); equals(); replace() .
For simplicity, think of String as a type of variable. Here is an example -

String greeting = “Hello”; // declare a variable of type String, and store Hello.

You can have an array of String - for example to store the names of gem stones.
String gemStones[] = {“Diamond”, “Sapphire”, “Ruby”, “Emerald”, “Zircon”}; // Note use { }
If you print gemStones[3], you would get - Emerald (the 4th item).
( You can also have an array of integer or any variable type - int decade[] = {10,20,30,40,50}; )

Try this example on your Arduino -

// Example using an array of String

String gemStones[] = {"Diamond", "Sapphire", "Ruby", "Emerald", "Zircon"};


void setup()
{
Serial.begin(9600);
for (int i = 0; i < 5 ; i = i +1)
Serial.println(gemStones[i]); // loop through 5 times, printing the gemStones name.
Serial.print("The 5th letter in Sapphire is ");
Serial.println(gemStones[1][4]); // note the use of two [ ] ( eg [] [] ) An array of an array.
Serial.print("Length of gemStones[1] = ");
Serial.println(gemStones[1].length()); // .length returns the number of characters.
}

void loop() {
}
Note 1– we will cover the “for” loop later. It is simply a loop, controlled by a counter or index.
Note 2 - Character arrays are referred to as strings with a small s,
Instances of the String class are referred to as Strings with a capital S
How the String ( char array) “Hello” is stored in computer memory.

“Hello” is a String of 6 char ( the 5 letters, plus one extra char for the null terminator ).
H is the first char, and it has been assigned the decimal value of 72 in the ASCII standard.
Computers only store binary (on/off). How do we store the decimal number 72, using only 0 and 1?
Each CHAR has 8 bits (see small boxes below – with labels bit0; bit1; bit2......bit7)).
From the example above, we know that H is stored as binary 01001000; e is stored as 01100101 .

Here is how you calculate the decimal value of H -


Start from the Right Hand Side of 01001000 using what's called “two's complement” - eg powers of 2..
The right most digit (see label bit 0) is multiplied by 2↑0 ; The next (bit1) is x 2↑1;
The 3rd from the right (bit2) is x 2↑2 ; the 4th from the right (bit3 ) is x 2↑3 ; etc.

0 x 2↑0 + 0 x 2↑1 + 0 x 2↑2 + 1 x 2↑3 + 0 x 2↑4 + 0 x 2↑5 + 1 x 2↑6 + 0 x 2↑7


= 0 x 0 + 0 x 2 + 0 x 4 + 1 x 8 + 0 x 16 + 0 x 32 + 1 x 64 + 0 x 128
= 0 + 0 + 0 + 8 + 0 + 0 + 64 + 0
= 8 + 64 = 72. The ASCII for H - is 72 in decimal, and stored as 01001000 in binary.
( NOTE – this only applies to Strings. If you store the integer 5 as type byte, it is stored as 00000101. )

Example – Try this on your Arduino : (Note – you need void setup(); Serial.begin(9600); and void loop()

char myChar = 'H'; //A single char. Note single quotes for a single character. Double quotes for a string.

Serial.println(myChar); // print the variable.


Serial.println(myChar, BIN); // print the variable in Binary format. Note – leading 0 is not printed.
Serial.println(myChar, DEC); // print the variable in Decimal format. Try this for the letter 'e' – interesting?

What would happen if we did this - int myInt, age, years ;

Examples of errors using data types

Try these on your Arduino. Note – you need void setup(); Serial.begin(9600); and void loop() as usual
1. int myInt = 33000;
Serial.println(myInt); // How did that happen ???

2. int myInt = 10 ;
float myFloat ;
myFloat = 234 * myInt / 100 ;
Serial.println(myFloat) ; // Answer is Wrong!. Solution - change 234 to 234.00 to force float.

3. int age; // variable to hold a persons age


age = 35.5;
Serial.println(age); // Hang-on, didn't we just say the person was 35.5 years old?
If you wanted to store the details of gemstones, you could declare several arrays to store this data – such as

String gemName[]; // an array of Sting type variable called gemName


int hardness[]; // an array of integer variable called hardness....etc
String colour[];

This uses the “standard” data types – such a String, int, boolean etc..

In addition to these “standard” data types , you can create a “user defined” data type.
This is like a wrapper, that encloses the various types of data..
Try the example below on your Arduino.

// Example of a USER created “Variable” , using the command - struct.


// We can create our own “type ” made of several variables.
// For this example, the new type is called GN; The variable or “instance” of GN is called myGem.

struct GN // create a new user defined structure called GN


{ // use curly braces to enclose the new structure.
String gemname; // this new structure includes a String variable called gemname
int hardness; // this new structure includes an integer variable called hardness
String colour ; // this new structure incldues a String variable called colour
};

GN myGem[] = // create an “instance” of GN, called myGem – as an ARRAY.


{
{ "Diamond", 10 , "blue"}, // assign the values to each element of the array myGem
{ "Amethyst", 4, "Purple"}, // Note – use a comma between each element AND each group.
{" Ruby", 8, "Red"}
};

void setup()
{
Serial.begin(9600); // Start Serial communication, so we print info on our PC monitor

} // end of setup

void loop() // print the details of the 2nd element ( eg array index is 1);
{
Serial.print("Gemname = "); // Print a heading so we know the part of the variable.
Serial.print(myGem[1].gemname); // You access the internal structure by .gemname
Serial.print(" Colour is ");
Serial.print(myGem[1].colour); // here we print the colour, by using .colour
Serial.print(" Hardness: ");
Serial.println(myGem[1].hardness); // use println so we drop to the next line.
delay(3000);

} // end of main loop


// Program to display on the monitor, the amount of memory in BYTES, used by the various data types.

void setup()
{
Serial.begin(9600); // start serial communication with your PC monitor
}

void loop()
{
Serial.print("sizeof(boolean) ="); Serial.println(sizeof(boolean));
Serial.print("sizeof(byte) = "); Serial.println(sizeof(byte));
Serial.print("sizeof(char) = "); Serial.println(sizeof(char));
Serial.print("sizeof(int) = "); Serial.println(sizeof(int));
Serial.print("sizeof(word) = "); Serial.println(sizeof(word));
Serial.print("sizeof(long) = "); Serial.println(sizeof(long));
Serial.print("sizeof(float) = "); Serial.println(sizeof(float));
Serial.print("sizeof(double) = "); Serial.println(sizeof(double));
Serial.print("sizeof(int8_t) = "); Serial.println(sizeof(int8_t));
Serial.print("sizeof(int16_t) ="); Serial.println(sizeof(int16_t));
Serial.print("sizeof(int32_t) ="); Serial.println(sizeof(int32_t));

delay(5000);
}

ASCII Chart
Note – 128 to 255 are called “Extended” character set.

Você também pode gostar