Variables
Variables
Variables in Arduino are like containers that hold information. This information can be numbers, letters, or even true/false values. You need to declare a variable before you can use it, which means telling the Arduino what kind of information it will hold (its "data type") and giving it a name.
Here's a breakdown:
Declaration: You tell the Arduino what kind of data a variable will hold and give it a name.
- Example:
int sensorValue;This declares a variable namedsensorValuethat will hold integer numbers (whole numbers like -1, 0, 1, 2, etc.).intis the data type, andsensorValueis the name.
- Example:
Data Types: Some common data types in Arduino include:
int: Stores integer numbers (whole numbers, positive or negative). Example:int age = 25;float: Stores decimal numbers (numbers with a fractional part). Example:float temperature = 24.5;char: Stores a single character (letter, number, symbol). Example:char initial = 'A';boolean: Stores a true/false value. Example:boolean isButtonPressed = true;String: Stores a sequence of characters (text). Example:String message = "Hello, world!";
Assignment: You give a variable a value using the
=(assignment) operator.- Example:
sensorValue = analogRead(A0);This reads a value from analog pin A0 and stores it in thesensorValuevariable.
- Example:
Usage: You can then use the variable's value in your code.
- Example:
Serial.println(sensorValue);This prints the value stored in thesensorValuevariable to the Serial Monitor. - Example:
if (temperature > 30.0) { Serial.println("It's hot!"); }This checks if the value of the temperature variable is greater than 30.0 and prints a message if it is.
- Example:
Scope: The "scope" of a variable determines where in your code it can be used.
Global Variables: Declared outside of any function. They can be used anywhere in the program.
Local Variables: Declared inside a function. They can only be used within that function.
Example:
int globalVariable = 10; // Global variable void setup() { int localVariable = 5; // Local variable, only usable within setup() Serial.begin(9600); Serial.println(globalVariable); // Okay to use globalVariable here Serial.println(localVariable); // Okay to use localVariable here } void loop() { Serial.println(globalVariable); // Okay to use globalVariable here // Serial.println(localVariable); // ERROR! localVariable is not defined here }
In short, variables let you store and manipulate data in your Arduino programs. You declare them with a data type and a name, assign them values, and then use those values to control your project. The scope determines where you can access a variable.

Comments
Post a Comment