MySQL for the Internet of Things

(Steven Felgate) #1

Chapter 4 ■ Data transformation


And here is the output (from the serial monitor):

1> 65535 65535
2> 0 65536
3> 1 65537


I print the values on the first row of output and then add one to each and print them again on the
second row. Notice what happens when I add 1 to the variables and print them. You may expect the
unsigned integer to be 65536, but it’s 0 because there was an overflow where the number of bits to represent
the number exceeded the maximum size of the variable (2 bytes). The value of 65536 requires 17 bits
(10000000000000000), and there are only 16 in two bytes and the first 16 are taken starting on the right
(0000000000000000). What may seem alarming is there was no warning of an overflow. The third row shows
what happens when I add 1 again but we see the unsigned integer variable has reset.
Thus, you should strive to use the smallest data type possible, especially when working with
microcontrollers or other devices with limited memory. To exercise this practice, you need to understand
the range of values that each data type can safely store. To get an idea of what it could mean for the Arduino
platform, Table 4-1 lists some common data types, memory size, and range of values. Notice how much
larger the floating-point variables are than the integers.


Table 4-1. Arduino Data Types


Data Type Num Bytes Range of Values


boolean 1 Logical true/false


byte 1 Unsigned number from 0 to 255


char 1 Signed number from -128 to 127, typically ASCII characters


unsigned char 1 Character values 0 to 255


word 2 Unsigned number from 0 to 65535


unsigned int 2 Unsigned number from 0 to 65535


int 2 Signed number from -32768 to 32767


unsigned long 4 Unsigned number from 0-4,294,967,295


long 4 Signed number from -2,147,483,648 to 2,147,483,647


float 4 Signed number from -3.4028235E+38 to 3.4028235E+38


There is one more aspect to using the smallest data types possible. Some data types will cause your
sketch to run slower. For example, using floats in arithmetic operations can be as much as 16 times slower
than using integers. If precision is not an issue and performance is, you may want to consider rounding
floating-point values to integers (hint: multiply by 100 to preserve 2 decimal points prior to the conversion).
Just be sure to use the largest integer you can.
Rather than present a set of code examples, the following section discusses some of the finer points of
converting and using data types.

Free download pdf