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.
Integer types:
-
bool
is 8 bits, but can contain only the values true or false (1 or 0) -
char
is 8 bits, giving us a value of -128 to 127 -
short
is 16 bits, giving a value of –32 768 to 32 767 -
int
is 32 bits, giving a value of –2 147 483 648 to 2 147 483 647 -
long
is 32 bits, giving a value of –2 147 483 648 to 2 147 483 647 -
long long
is 64 bits, giving a value of –9 223 372 036 854 775 808 to 9 223 372 036 854 775 807
As you can seeshort
,int
,long
andlong long
have negative numbers. But what if we want to conserve space, and are not planning to use negative numbers? This is where theunsigned
keyword comes in.
If you addunsigned
to the front of a variable declaration, all the negative numbers will be transferred to extra positive numbers:char
becomes a value from 0 to 255,short
becomes a value from 0 to 65 535,int
becomes 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:
-
float
is 32 bits -
double
is 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 unsigned
keyword!
Since the screen is 220x176 in the high resolution mode, I think I will store the position in a char
.
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:
game.display.setCursor(0,myVariable);
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.