Arduino> Variable> Data Types>
String()
[Data Types]
Description
Constructs an instance of the String class. There are multiple versions that construct Strings from different data types (i.e. format them as sequences of characters), including:
- a constant string of characters, in double quotes (i.e. a char array)
- a single constant character, in single quotes
- another instance of the String object
- a constant integer or long integer
- a constant integer or long integer, using a specified base
- an integer or long integer variable
- an integer or long integer variable, using a specified base
- a float or double, using a specified decimal places
Constructing a String from a number results in a string that contains the ASCII representation of that number. The default is base ten, so
String thisString = String(13);
gives you the String "13". You can use other bases, however. For example,
String thisString = String(13, HEX);
gives you the String "D", which is the hexadecimal representation of the decimal value 13. Or if you prefer binary,
String thisString = String(13, BIN);
gives you the String "1101", which is the binary representation of 13.
Syntax
String(val)
String(val, base)
String(val, decimalPlaces)
Parameters
val
: a variable to format as a String. Allowed data types: string, char, byte, int, long, unsigned int, unsigned long, float, double.base
: (optional) the base in which to format an integral value.decimalPlaces
: only if val is float or double. The desired decimal places.Returns
An instance of the String class.
Example Code
All of the following are valid declarations for Strings.
String stringOne = "Hello String"; // using a constant String
String stringOne = String('a'); // converting a constant char into a String
String stringTwo = String("This is a string"); // converting a constant string into a String object
String stringOne = String(stringTwo + " with more"); // concatenating two strings
String stringOne = String(13); // using a constant integer
String stringOne = String(analogRead(0), DEC); // using an int and a base
String stringOne = String(45, HEX); // using an int and a base (hexadecimal)
String stringOne = String(255, BIN); // using an int and a base (binary)
String stringOne = String(millis(), DEC); // using a long and a base
String stringOne = String(5.698, 3); // using a float and the decimal places
array
[Data Types]
Description
An array is a collection of variables that are accessed with an index number. Arrays in the C++ programming language Arduino sketches are written in can be complicated, but using simple arrays is relatively straightforward.
Creating (Declaring) an Array
All of the methods below are valid ways to create (declare) an array.
int myInts[6];
int myPins[] = {2, 4, 8, 3, 6};
int mySensVals[6] = {2, 4, -8, 3, 2};
char message[6] = "hello";
You can declare an array without initializing it as in myInts. In myPins we declare an array without explicitly choosing a size. The compiler counts the elements and creates an array of the appropriate size.
Finally you can both initialize and size your array, as in mySensVals. Note that when declaring an array of type char, one more element than your initialization is required, to hold the required null character.
Finally you can both initialize and size your array, as in mySensVals. Note that when declaring an array of type char, one more element than your initialization is required, to hold the required null character.
Accessing an Array
Arrays are zero indexed, that is, referring to the array initialization above, the first element of the array is at index 0, hence
It also means that in an array with ten elements, index nine is the last element. Hence:
mySensVals[0] == 2, mySensVals[1] == 4,
and so forth.It also means that in an array with ten elements, index nine is the last element. Hence:
int myArray[10]={9, 3, 2, 4, 3, 2, 7, 8, 9, 11};
// myArray[9] contains 11
// myArray[10] is invalid and contains random information (other memory address)
For this reason you should be careful in accessing arrays. Accessing past the end of an array (using an index number greater than your declared array size - 1) is reading from memory that is in use for other purposes. Reading from these locations is probably not going to do much except yield invalid data. Writing to random memory locations is definitely a bad idea and can often lead to unhappy results such as crashes or program malfunction. This can also be a difficult bug to track down.
Unlike BASIC or JAVA, the C compiler does no checking to see if array access is within legal bounds of the array size that you have declared.
Unlike BASIC or JAVA, the C compiler does no checking to see if array access is within legal bounds of the array size that you have declared.
To assign a value to an array:
mySensVals[0] = 10;
To retrieve a value from an array:
x = mySensVals[4];
Arrays and FOR Loops
Arrays are often manipulated inside for loops, where the loop counter is used as the index for each array element. For example, to print the elements of an array over the serial port, you could do something like this:
for (byte i = 0; i < 5; i = i + 1) {
Serial.println(myPins[i]);
}
Example Code
For a complete program that demonstrates the use of arrays, see the (Knight Rider example) from the (Tutorials).
-------------------------------------------------------------------
bool
[Data Types]
Description
A
bool
holds one of two values, true
or false
. (Each bool
variable occupies one byte of memory.)Syntax
bool var = val;
Parameters
var
: variable name.val
: the value to assign to that variable.Example Code
This code shows how to use the
bool
datatype.int LEDpin = 5; // LED on pin 5
int switchPin = 13; // momentary switch on 13, other side connected to ground
bool running = false;
void setup() {
pinMode(LEDpin, OUTPUT);
pinMode(switchPin, INPUT);
digitalWrite(switchPin, HIGH); // turn on pullup resistor
}
void loop() {
if (digitalRead(switchPin) == LOW) {
// switch is pressed - pullup keeps pin high normally
delay(100); // delay to debounce switch
running = !running; // toggle running variable
digitalWrite(LEDpin, running); // indicate via LED
}
}}
-------------------------------------------------------------------
boolean
[Data Types]
Description
boolean
is a non-standard type alias for bool defined by Arduino. It’s recommended to instead use the standard type bool
, which is identical.
-------------------------------------------------------------------
byte
[Data Types]
Description
A byte stores an 8-bit unsigned number, from 0 to 255.
Syntax
byte var = val;
Parameters
var
: variable name.val
: the value to assign to that variable.
-------------------------------------------------------------------
char
[Data Types]
Description
A data type used to store a character value. Character literals are written in single quotes, like this: 'A' (for multiple characters - strings - use double quotes: "ABC").
Characters are stored as numbers however. You can see the specific encoding in the ASCII chart. This means that it is possible to do arithmetic on characters, in which the ASCII value of the character is used (e.g. 'A' + 1 has the value 66, since the ASCII value of the capital letter A is 65). See
The size of the
Characters are stored as numbers however. You can see the specific encoding in the ASCII chart. This means that it is possible to do arithmetic on characters, in which the ASCII value of the character is used (e.g. 'A' + 1 has the value 66, since the ASCII value of the capital letter A is 65). See
Serial.println
reference for more on how characters are translated to numbers.The size of the
char
datatype is at least 8 bits. It’s recommended to only use char
for storing characters. For an unsigned, one-byte (8 bit) data type, use the byte data type.Syntax
char var = val;
Parameters
var
: variable name.val
: the value to assign to that variable.Example Code
char myChar = 'A';
char myChar = 65; // both are equivalent
-------------------------------------------------------------------
double
[Data Types]
Description
Double precision floating point number. On the Uno and other ATMEGA based boards, this occupies 4 bytes. That is, the double implementation is exactly the same as the float, with no gain in precision.
On the Arduino Due, doubles have 8-byte (64 bit) precision.
On the Arduino Due, doubles have 8-byte (64 bit) precision.
Syntax
double var = val;
Parameters
var
: variable name.val
: the value to assign to that variable.Notes and Warnings
Users who borrow code from other sources that includes double variables may wish to examine the code to see if the implied precision is different from that actually achieved on ATMEGA based Arduinos.
-------------------------------------------------------------------
float
[Data Types]
Description
Datatype for floating-point numbers, a number that has a decimal point. Floating-point numbers are often used to approximate analog and continuous values because they have greater resolution than integers. Floating-point numbers can be as large as 3.4028235E+38 and as low as -3.4028235E+38. They are stored as 32 bits (4 bytes) of information.
Syntax
float var = val;
Parameters
var
: variable name.val
: the value to assign to that variable.Example Code
float myfloat;
float sensorCalbrate = 1.117;
int x;
int y;
float z;
x = 1;
y = x / 2; // y now contains 0, ints can't hold fractions
z = (float)x / 2.0; // z now contains .5 (you have to use 2.0, not 2)
Notes and Warnings
If doing math with floats, you need to add a decimal point, otherwise it will be treated as an int. See the Floating point constants page for details.
The float data type has only 6-7 decimal digits of precision. That means the total number of digits, not the number to the right of the decimal point. Unlike other platforms, where you can get more precision by using a double (e.g. up to 15 digits), on the Arduino, double is the same size as float.
Floating point numbers are not exact, and may yield strange results when compared. For example 6.0 / 3.0 may not equal 2.0. You should instead check that the absolute value of the difference between the numbers is less than some small number.
Conversion from floating point to integer math results in truncation:
The float data type has only 6-7 decimal digits of precision. That means the total number of digits, not the number to the right of the decimal point. Unlike other platforms, where you can get more precision by using a double (e.g. up to 15 digits), on the Arduino, double is the same size as float.
Floating point numbers are not exact, and may yield strange results when compared. For example 6.0 / 3.0 may not equal 2.0. You should instead check that the absolute value of the difference between the numbers is less than some small number.
Conversion from floating point to integer math results in truncation:
float x = 2.9; // A float type variable
int y = x; // 2
If, instead, you want to round off during the conversion process, you need to add
0.5
:float x = 2.9;
int y = x + 0.5; // 3
or use the
round()
function:float x = 2.9;
int y = round(x); // 3
Floating point math is also much slower than integer math in performing calculations, so should be avoided if, for example, a loop has to run at top speed for a critical timing function. Programmers often go to some lengths to convert floating point calculations to integer math to increase speed.
-------------------------------------------------------------------
int
[Data Types]
Description
Integers are your primary data-type for number storage.
On the Arduino Uno (and other ATmega based boards) an int stores a 16-bit (2-byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) - 1). On the Arduino Due and SAMD based boards (like MKR1000 and Zero), an int stores a 32-bit (4-byte) value. This yields a range of -2,147,483,648 to 2,147,483,647 (minimum value of -2^31 and a maximum value of (2^31) - 1).
int’s store negative numbers with a technique called (2’s complement math). The highest bit, sometimes referred to as the "sign" bit, flags the number as a negative number. The rest of the bits are inverted and 1 is added.
The Arduino takes care of dealing with negative numbers for you, so that arithmetic operations work transparently in the expected manner. There can be an unexpected complication in dealing with the bitshift right operator (>>) however.
On the Arduino Uno (and other ATmega based boards) an int stores a 16-bit (2-byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) - 1). On the Arduino Due and SAMD based boards (like MKR1000 and Zero), an int stores a 32-bit (4-byte) value. This yields a range of -2,147,483,648 to 2,147,483,647 (minimum value of -2^31 and a maximum value of (2^31) - 1).
int’s store negative numbers with a technique called (2’s complement math). The highest bit, sometimes referred to as the "sign" bit, flags the number as a negative number. The rest of the bits are inverted and 1 is added.
The Arduino takes care of dealing with negative numbers for you, so that arithmetic operations work transparently in the expected manner. There can be an unexpected complication in dealing with the bitshift right operator (>>) however.
Syntax
int var = val;
Parameters
var
: variable name.val
: the value to assign to that variable.Example Code
This code creates an integer called 'countUp', which is initially set as the number 0 (zero). The variable goes up by 1 (one) each loop, being displayed on the serial monitor.
int countUp = 0; //creates a variable integer called 'countUp'
void setup() {
Serial.begin(9600); // use the serial port to print the number
}
void loop() {
countUp++; //Adds 1 to the countUp int on every loop
Serial.println(countUp); // prints out the current state of countUp
delay(1000);
}
Notes and Warnings
When signed variables are made to exceed their maximum or minimum capacity they overflow. The result of an overflow is unpredictable so this should be avoided. A typical symptom of an overflow is the variable "rolling over' from its maximum capacity to its minimum or vice versa, but this is not always the case. If you want this behavior, use unsigned int.
-------------------------------------------------------------------
long
[Data Types]
Description
Long variables are extended size variables for number storage, and store 32 bits (4 bytes), from -2,147,483,648 to 2,147,483,647.
If doing math with integers, at least one of the numbers must be followed by an L, forcing it to be a long. See the Integer Constants page for details.
If doing math with integers, at least one of the numbers must be followed by an L, forcing it to be a long. See the Integer Constants page for details.
Syntax
long var = val;
Parameters
var
: variable name.val
: the value to assign to that variable.Example Code
long speedOfLight = 186000L; // see the Integer Constants page for explanation of the 'L'
-------------------------------------------------------------------
short
[Data Types]
Description
A short is a 16-bit data-type.
On all Arduinos (ATMega and ARM based) a short stores a 16-bit (2-byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) - 1).
On all Arduinos (ATMega and ARM based) a short stores a 16-bit (2-byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) - 1).
Syntax
short var = val;
Parameters
var
: variable name.val
: the value to assign to that variable.Example Code
short ledPin = 13;
-------------------------------------------------------------------
size_t
[Data Types]
Description
size_t
is a data type capable of representing the size of any object in bytes. Examples of the use of size_t
are the return type of sizeof() and Serial.print().Syntax
size_t var = val;
Parameters
var
: variable name.val
: the value to assign to that variable.
-------------------------------------------------------------------
string
[Data Types]
Description
Text strings can be represented in two ways. you can use the String data type, which is part of the core as of version 0019, or you can make a string out of an array of type char and null-terminate it. This page described the latter method. For more details on the String object, which gives you more functionality at the cost of more memory, see the String object page.
Syntax
All of the following are valid declarations for strings.
char Str1[15];
char Str2[8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o'};
char Str3[8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o', '\0'};
char Str4[] = "arduino";
char Str5[8] = "arduino";
char Str6[15] = "arduino";
Possibilities for declaring strings
- Declare an array of chars without initializing it as in Str1
- Declare an array of chars (with one extra char) and the compiler will add the required null character, as in Str
- Explicitly add the null character, Str3
- Initialize with a string constant in quotation marks; the compiler will size the array to fit the string constant and a terminating null character, Str4
- Initialize the array with an explicit size and string constant, Str5
- Initialize the array, leaving extra space for a larger string, Str6
Null termination
Generally, strings are terminated with a null character (ASCII code 0). This allows functions (like
Serial.print()
) to tell where the end of a string is. Otherwise, they would continue reading subsequent bytes of memory that aren’t actually part of the string.This means that your string needs to have space for one more character than the text you want it to contain. That is why Str2 and Str5 need to be eight characters, even though "arduino" is only seven - the last position is automatically filled with a null character. Str4 will be automatically sized to eight characters, one for the extra null. In Str3, we’ve explicitly included the null character (written '\0') ourselves.
Note that it’s possible to have a string without a final null character (e.g. if you had specified the length of Str2 as seven instead of eight). This will break most functions that use strings, so you shouldn’t do it intentionally. If you notice something behaving strangely (operating on characters not in the string), however, this could be the problem.
Single quotes or double quotes?
Strings are always defined inside double quotes ("Abc") and characters are always defined inside single quotes('A').
Wrapping long strings
You can wrap long strings like this:
char myString[] = "This is the first line"
" this is the second line"
" etcetera";
Arrays of strings
It is often convenient, when working with large amounts of text, such as a project with an LCD display, to setup an array of strings. Because strings themselves are arrays, this is actually an example of a two-dimensional array.
In the code below, the asterisk after the datatype
It is often convenient, when working with large amounts of text, such as a project with an LCD display, to setup an array of strings. Because strings themselves are arrays, this is actually an example of a two-dimensional array.
In the code below, the asterisk after the datatype
char
“char*” indicates that this is an array of “pointers”. All array names are actually pointers, so this is required to make an array of arrays. Pointers are one of the more esoteric parts of C++ for beginners to understand, but it isn’t necessary to understand pointers in detail to use them effectively here.Example Code
char *myStrings[] = {"This is string 1", "This is string 2", "This is string 3",
"This is string 4", "This is string 5", "This is string 6"
};
void setup() {
Serial.begin(9600);
}
void loop() {
for (int i = 0; i < 6; i++) {
Serial.println(myStrings[i]);
delay(500);
}
}
-------------------------------------------------------------------
unsigned char
[Data Types]
Description
An unsigned data type that occupies 1 byte of memory. Same as the byte datatype.
The unsigned char datatype encodes numbers from 0 to 255.
For consistency of Arduino programming style, the byte data type is to be preferred.
The unsigned char datatype encodes numbers from 0 to 255.
For consistency of Arduino programming style, the byte data type is to be preferred.
Syntax
unsigned char var = val;
Parameters
var
: variable name.val
: the value to assign to that variable.Example Code
unsigned char myChar = 240;
-------------------------------------------------------------------
unsigned int
[Data Types]
Description
On the Uno and other ATMEGA based boards, unsigned ints (unsigned integers) are the same as ints in that they store a 2 byte value. Instead of storing negative numbers however they only store positive values, yielding a useful range of 0 to 65,535 ((2^16) - 1).
The Due stores a 4 byte (32-bit) value, ranging from 0 to 4,294,967,295 (2^32 - 1).
The difference between unsigned ints and (signed) ints, lies in the way the highest bit, sometimes referred to as the "sign" bit, is interpreted. In the Arduino int type (which is signed), if the high bit is a "1", the number is interpreted as a negative number, and the other 15 bits are interpreted with (2's complement math).
The Due stores a 4 byte (32-bit) value, ranging from 0 to 4,294,967,295 (2^32 - 1).
The difference between unsigned ints and (signed) ints, lies in the way the highest bit, sometimes referred to as the "sign" bit, is interpreted. In the Arduino int type (which is signed), if the high bit is a "1", the number is interpreted as a negative number, and the other 15 bits are interpreted with (2's complement math).
Syntax
unsigned int var = val;
Parameters
var
: variable name.val
: the value to assign to that variable.Example Code
unsigned int ledPin = 13;
Notes and Warnings
When unsigned variables are made to exceed their maximum capacity they "roll over" back to 0, and also the other way around:
unsigned int x;
x = 0;
x = x - 1; // x now contains 65535 - rolls over in neg direction
x = x + 1; // x now contains 0 - rolls over
Math with unsigned variables may produce unexpected results, even if your unsigned variable never rolls over.
The MCU applies the following rules:
The calculation is done in the scope of the destination variable. E.g. if the destination variable is signed, it will do signed math, even if both input variables are unsigned.
However with a calculation which requires an intermediate result, the scope of the intermediate result is unspecified by the code. In this case, the MCU will do unsigned math for the intermediate result, because both inputs are unsigned!
The MCU applies the following rules:
The calculation is done in the scope of the destination variable. E.g. if the destination variable is signed, it will do signed math, even if both input variables are unsigned.
However with a calculation which requires an intermediate result, the scope of the intermediate result is unspecified by the code. In this case, the MCU will do unsigned math for the intermediate result, because both inputs are unsigned!
unsigned int x = 5;
unsigned int y = 10;
int result;
result = x - y; // 5 - 10 = -5, as expected
result = (x - y) / 2; // 5 - 10 in unsigned math is 65530! 65530/2 = 32765
// solution: use signed variables, or do the calculation step by step.
result = x - y; // 5 - 10 = -5, as expected
result = result / 2; // -5/2 = -2 (only integer math, decimal places are dropped)
Why use unsigned variables at all?
- The rollover behaviour is desired, e.g. counters
- The signed variable is a bit too small, but you want to avoid the memory and speed loss of long/float.
-------------------------------------------------------------------
unsigned long
[Data Types]
Description
Unsigned long variables are extended size variables for number storage, and store 32 bits (4 bytes). Unlike standard longs unsigned longs won’t store negative numbers, making their range from 0 to 4,294,967,295 (2^32 - 1).
Syntax
unsigned long var = val;
Parameters
var
: variable name.val
: the value to assign to that variable.Example Code
unsigned long time;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print("Time: ");
time = millis();
//prints time since program started
Serial.println(time);
// wait a second so as not to send massive amounts of data
delay(1000);
}
-------------------------------------------------------------------
void
[Data Types]
Description
The
void
keyword is used only in function declarations. It indicates that the function is expected to return no information to the function from which it was called.Example Code
The code shows how to use
void
.// actions are performed in the functions "setup" and "loop"
// but no information is reported to the larger program
void setup() {
// ...
}
void loop() {
// ...
}
-------------------------------------------------------------------
word
[Data Types]
Description
A word can store an unsigned number of at least 16 bits (from 0 to 65535).
Syntax
word var = val;
Parameters
var
: variable name. val
: the value to assign to that variable.Example Code
word w = 10000;
-------------------------------------------------------------------
Post a Comment
Hi Users, if you have any queries then please let me know.