To do anything interesting in programming you have to store data.
But data comes in all types and sizes, and we need to consider this, especially on a microcontroller like what the Pokitto is using.
The Pokitto has 36 kilo bytes of RAM where our variables will be stored.
That’s 36 864 bytes. A byte is 8 bits, and a bit is 1 or 0.
We have several options of variables.
boolis 8 bits, but can contain only the values true or false (1 or 0)
charis 8 bits, giving us a value of -128 to 127
shortis 16 bits, giving a value of –32 768 to 32 767
intis 32 bits, giving a value of –2 147 483 648 to 2 147 483 647
longis 32 bits, giving a value of –2 147 483 648 to 2 147 483 647
long longis 64 bits, giving a value of –9 223 372 036 854 775 808 to 9 223 372 036 854 775 807
As you can see
long longhave negative numbers. But what if we want to conserve space, and are not planning to use negative numbers? This is where the
unsignedkeyword comes in.
If you add
unsignedto the front of a variable declaration, all the negative numbers will be transferred to extra positive numbers:
charbecomes a value from 0 to 255,
shortbecomes a value from 0 to 65 535,
intbecomes a value from 0 to 4 294 967 295, etc.
It is usually best to use the smallest type you need, to conserve memory and cram the most content into your project.
If you need a variable like 3.14159, you want a floating point variable, which is basically an integer value with decimals:
floatis 32 bits
doubleis 64 bits
The last basic type of variables is the pointer, which takes 32 bits of memory. Pointers store locations of data in memory; this will be covered in later tutorials.
Okay, that’s all fine and dandy, but how do you use these?
Well, let’s make an example: I’m going to move our text cursor around the screen, and since I don’t want text off the screen, I don’t need negative numbers. Because of this, I can use the
Since the screen is 220x176 in the high resolution mode, I think I will store the position in a
Inside the main function of our hello world we made in the last tutorial, we will add
unsigned char myVariable = 0;
You can change the variable name to whatever you like and assign a number to it; make sure to name it something that makes sense to you so you will know what it is!
Now I will replace the second parameter of the
setCursor function, which will be the Y position on the screen:
After that I will increment
myVariable by 1; this can be done in a couple of ways:
myVariable = myVariable + 1; //or myVariable += 1; //or myVariable ++;
The first one is a fairly basic definition, and the other 2 are short hand versions to kind of clean up the code.
If you run this now the text will race off the screen, but when
myVariable hits 255, it will go back to 0 because of overflow.