Each variable in C has an associated data type. Each data type requires different amounts of memory and has some specific operations which can be performed over it. Let us briefly describe them one by one:
Following are the examples of some very common data types used in arduino programming:
Byte stores an 8-bit numerical value without decimal points. They have a range of 0-255.
byte someVariable = 180; // declares 'someVariable' as a byte type
Integers are the primary datatype for storage of numbers without decimal points and store a 16-bit value with a range of 32,767 to -32,768.
int someVariable = 1500; // declares 'someVariable' as an integer type
Note: Integer variables will roll over if forced past their maximum or minimum values by an assignment or comparison. For example, if x = 32767 and a subsequent statement adds 1 to x, x = x + 1 or x++, x will then rollover and equal -32,768.
Extended size datatype for long integers, without decimal points, stored in a 32-bit value with a range of 2,147,483,647 to -2,147,483,648.
long someVariable = 90000; // declares 'someVariable'as a long type
A datatype for floating-point numbers, or numbers that have a decimal point. Floating- point numbers have greater resolution than integers and are stored as a 32-bit value with a range of 3.4028235E+38 to -3.4028235E+38.
float someVariable = 3.14; // declares 'someVariable'as a floating-point type
Note: Floating-point numbers are not exact, and may yield strange results when compared. Floating point math is also much slower than integer math in performing calculations, so should be avoided if possible.
An array is a collection of values that are accessed with an index number. Any value in the array may be called upon by calling the name of the array and the index number of the value. Arrays are zero indexed, with the first value in the array beginning at index number 0. An array needs to be declared and optionally assigned values before they can be used.
int myArray[] = {value0, value1, value2...} int myArray[5]; // declares integer array w/ 6 positions myArray[3] = 10; // assigns the 4th index the value 10
A data type that takes up 1 byte of memory that stores a character value. Character literals are written in single quotes, like this: 'A' (for multiple characters - strings - use double quotes: "ABC").
char myChar = 'A'; char myChar = 65; // both are equivalent
Note: The char datatype is a signed type, meaning that it encodes numbers from -128 to 127. For an unsigned, one-byte (8 bit) data type, use the byte data type.