Ugenz Academy/IoT Tutorial

Variables Operators And Data Types

19 min read3,712 words

Reading progress

Keep learning

Variables, Operators, and Data Types in ESP32 Programming

1. Introduction

When programming an ESP32, you often need to store sensor readings, calculate values, compare conditions, and control electronic components. Variables, data types, and operators are the fundamental building blocks that make these tasks possible.

For example, imagine an ESP32-based temperature monitoring system. The program needs to store the current temperature, compare it with a threshold, and activate a fan when the temperature becomes too high.

float temperature = 32.5; int threshold = 30; if (temperature > threshold) { Serial.println("Temperature is high"); }

In this example:

  • temperature stores a temperature reading.
  • threshold stores the temperature limit.
  • float and int specify the data types.
  • > compares two values.
  • if checks whether the condition is true.

Understanding these concepts will help you write reliable ESP32 programs, from simple LED projects to advanced IoT applications.

2. What Is a Variable?

A variable is a named storage location used by a program to hold a value.

You can think of a variable as a labeled container. The label identifies the information, while the value is the information stored inside it.

For example:

int age = 20;

Here:

  • int is the data type.
  • age is the variable name.
  • 20 is the initial value.
  • = assigns the initial value to the variable.

Declaring variables

A variable declaration tells the compiler the variable's name and type.

int sensorValue;

This declares an integer variable named sensorValue. Because it is a local variable and has not been initialized, its value is indeterminate. Assign a value before reading it.

Initializing variables

Initialization means giving a variable its initial value.

int sensorValue = 0; float temperature = 25.5; bool deviceStatus = true;

These declarations create three variables with different data types.

Changing variable values

Variables can be updated while a program runs.

int counter = 0; void setup() { Serial.begin(115200); } void loop() { counter = counter + 1; Serial.println(counter); delay(1000); }

The value of counter increases by one each time the loop executes.

You can also write:

counter += 1;

Both statements add one to the current value of counter.

3. Rules for Naming Variables

Variable names should be meaningful and follow C++ naming rules.

Common rules include:

  1. A name can contain letters, digits, and underscores.
  2. A name cannot begin with a digit.
  3. Spaces are not allowed.
  4. C++ keywords such as int, if, and while cannot be used as variable names.
  5. Variable names are case-sensitive.

Valid examples:

int sensorValue = 500; float roomTemperature = 28.5; int led_pin = 2; int deviceCount = 4;

Invalid examples:

// int 2sensor = 500; // Starts with a digit // float room temperature; // Contains a space // int int = 10; // Uses a keyword

Meaningful names

Prefer:

float temperatureCelsius = 28.5;

Instead of:

float x = 28.5;

Meaningful names make your code easier to read, maintain, and debug.

4. What Are Data Types?

A data type specifies what kind of value a variable can represent and how the compiler handles that value.

Different types are useful for different kinds of information.

For example:

  • An integer can store a whole number.
  • A floating-point type can represent a fractional number.
  • A character can represent a single character.
  • A Boolean can represent true or false.

Choosing suitable types helps you use memory effectively and avoid incorrect calculations.

5. Integer Data Types

Integer types represent whole numbers without fractional parts.

int

The int type is commonly used for counters, pin numbers, and whole-number measurements.

int ledPin = 2; int counter = 10; int sensorValue = 750;

The range of int depends on the target platform and compiler. On typical ESP32 Arduino targets, int is 32 bits.

unsigned int

An unsigned integer represents non-negative integer values.

unsigned int deviceCount = 100;

On a typical ESP32 target, a 32-bit unsigned integer ranges from 0 to 4,294,967,295.

Use an unsigned type only when its range and arithmetic behavior fit your application.

short and long

These are additional integer types.

short smallValue = 100; long largeCounter = 100000L;

Their exact sizes depend on the target platform. On typical ESP32 Arduino targets, short is 16 bits and long is 32 bits.

long long

This type supports a wider integer range.

long long totalCount = 5000000000LL;

On typical ESP32 targets, long long is 64 bits.

uint8_t, uint16_t, and uint32_t

These types explicitly specify the number of bits used by an unsigned integer.

uint8_t ledBrightness = 100; uint16_t analogReading = 3000; uint32_t elapsedTime = 100000;

Their ranges are:

TypeSizeRange
uint8_t8 bits0–255
uint16_t16 bits0–65,535
uint32_t32 bits0–4,294,967,295

These types are useful when working with sensor protocols, binary data, registers, and embedded systems that require precise integer widths.

6. Floating-Point Data Types

Floating-point types represent numbers with fractional parts.

float

The float type is commonly used for sensor readings, percentages, and measurements.

float temperature = 28.6; float humidity = 65.5; float voltage = 3.3;

A typical ESP32 Arduino target uses a 32-bit float.

Floating-point values are approximate, so some decimal values cannot be represented exactly.

double

The double type represents floating-point numbers.

double distance = 123.456789;

On many ESP32 targets, double has the same 32-bit precision as float, although this depends on the particular target and toolchain. Do not assume that declaring a double automatically provides greater precision.

Example: Calculating an average

float reading1 = 25.5; float reading2 = 27.5; float average = (reading1 + reading2) / 2.0; void setup() { Serial.begin(115200); Serial.println(average); } void loop() { }

Output:

26.5

Using 2.0 makes the floating-point calculation explicit.

7. Character and String Data Types

Text is important in ESP32 applications because devices often display messages, receive commands, and send information over networks.

char

The char type stores a single character.

char grade = 'A'; char command = 'L';

Single characters use single quotation marks.

Character arrays

A C-style string is an array of characters terminated by a null character, '\0'.

char deviceName[] = "ESP32";

The array contains the characters E, S, P, 3, 2, followed by the terminating null character.

Character arrays are useful when working with C libraries, low-level interfaces, and memory-sensitive applications.

String

The Arduino String class provides convenient ways to work with text.

String deviceName = "ESP32"; String message = "Welcome to Ugenz Academy"; void setup() { Serial.begin(115200); Serial.println(deviceName); Serial.println(message); } void loop() { }

Strings can be combined:

String device = "ESP32"; String status = device + " is connected";

This creates the text:

ESP32 is connected

Repeated dynamic string allocation can fragment the heap in long-running embedded applications. For predictable memory usage, consider fixed-size character arrays or other carefully managed buffers where appropriate.

8. Boolean Data Type

The bool type stores one of two logical values:

  • true
  • false

Example:

bool isConnected = true; bool alarmActive = false;

Boolean values are useful for representing device states.

Example: Controlling an alarm state

bool motionDetected = true; void setup() { Serial.begin(115200); if (motionDetected) { Serial.println("Motion detected"); } else { Serial.println("No motion detected"); } } void loop() { }

The message depends on the value stored in motionDetected.

In C++, true and false are Boolean values. When converted to an integer, they correspond to 1 and 0 respectively.

9. The const Keyword

Sometimes a value should not change after initialization. The const keyword makes a variable read-only through that name.

const int ledPin = 2; const float temperatureLimit = 35.0;

These declarations are useful for pin assignments, thresholds, and fixed configuration values.

For example:

const int ledPin = 2; void setup() { pinMode(ledPin, OUTPUT); } void loop() { digitalWrite(ledPin, HIGH); delay(500); digitalWrite(ledPin, LOW); delay(500); }

Using const helps prevent accidental changes to values that should remain fixed.

10. The constexpr Keyword

The constexpr keyword declares a value that can be evaluated at compile time when its initializer meets the relevant requirements.

constexpr int ledPin = 2; constexpr unsigned long interval = 1000;

It is useful for compile-time configuration and constants used in embedded programs.

For simple beginner programs, const is often sufficient. As you develop more advanced firmware, understanding constexpr can help you express compile-time values more precisely.

11. What Are Operators?

Operators are symbols or keywords that perform operations on values and variables.

For example:

int a = 10; int b = 5; int result = a + b;

The + operator adds the values of a and b, producing 15.

C++ operators are commonly grouped into arithmetic, assignment, comparison, logical, bitwise, and other categories.

12. Arithmetic Operators

Arithmetic operators perform mathematical calculations.

OperatorOperationExampleResult
+Addition10 + 515
-Subtraction10 - 55
*Multiplication10 * 550
/Division10 / 52
%Remainder10 % 31

Example:

int a = 10; int b = 3; void setup() { Serial.begin(115200); Serial.println(a + b); Serial.println(a - b); Serial.println(a * b); Serial.println(a / b); Serial.println(a % b); } void loop() { }

Output:

13 7 30 3 1

Important: Integer division

When both operands are integers, division discards the fractional part.

int result = 7 / 2;

The result is 3, not 3.5.

To obtain a floating-point result, use a floating-point operand:

float result = 7.0 / 2;

The result is 3.5.

Using arithmetic with sensor values

Suppose a compatible sensor provides a distance measurement in centimeters.

float distanceCm = 25.0; float distanceM = distanceCm / 100.0;

The resulting distance is 0.25 meters.

Always verify the units and conversion requirements of the actual sensor.

13. Assignment Operators

Assignment operators store values in variables or update existing values.

OperatorExampleEquivalent expression
=x = 10Assign 10 to x
+=x += 5x = x + 5
-=x -= 5x = x - 5
*=x *= 2x = x * 2
/=x /= 2x = x / 2
%=x %= 3x = x % 3

Example:

int counter = 10; void setup() { Serial.begin(115200); counter += 5; Serial.println(counter); counter -= 3; Serial.println(counter); } void loop() { }

Output:

15 12

Assignment operators are useful for counters, accumulated measurements, and updating program state.

14. Increment and Decrement Operators

The increment operator ++ increases a variable by one.

The decrement operator -- decreases a variable by one.

int counter = 5; void setup() { Serial.begin(115200); counter++; Serial.println(counter); counter--; Serial.println(counter); } void loop() { }

Output:

6 5

Prefix and postfix

C++ supports both prefix and postfix forms.

int a = 5; int b = ++a;

Here, a becomes 6, and b receives 6.

Compare this with:

int a = 5; int b = a++;

Here, b receives the old value 5, and then a becomes 6.

When incrementing a variable in a standalone statement, counter++ and ++counter both increase it by one. The difference matters when the expression's value is used.

15. Comparison Operators

Comparison operators compare two values and produce a Boolean result.

OperatorMeaningExample
==Equal toa == b
!=Not equal toa != b
>Greater thana > b
<Less thana < b
>=Greater than or equal toa >= b
<=Less than or equal toa <= b

Example:

int temperature = 35; int threshold = 30; void setup() { Serial.begin(115200); Serial.println(temperature > threshold); Serial.println(temperature == threshold); } void loop() { }

Output:

1 0

The Arduino Serial Monitor prints these Boolean values as 1 and 0 by default.

To display readable messages:

if (temperature > threshold) { Serial.println("Temperature is above the threshold"); }

Common mistake: = vs. ==

The assignment operator = assigns a value.

The comparison operator == checks whether two values are equal.

int number = 10; if (number == 10) { Serial.println("Number is ten"); }

Confusing these operators can lead to logic errors.

16. Logical Operators

Logical operators combine or reverse Boolean conditions.

OperatorMeaningExample
&&Logical ANDa > 10 && b < 20
``
!Logical NOT!isConnected

Logical AND

Both conditions must be true.

int temperature = 32; bool systemEnabled = true; if (temperature > 30 && systemEnabled) { Serial.println("Cooling system can activate"); }

Logical OR

At least one condition must be true.

bool smokeDetected = false; bool gasDetected = true; if (smokeDetected || gasDetected) { Serial.println("Warning: Check the environment"); }

Logical NOT

The ! operator reverses a Boolean condition.

bool isConnected = false; if (!isConnected) { Serial.println("Device is offline"); }

Logical operators are especially useful for automation, sensor monitoring, alarms, and safety checks.

17. Bitwise Operators

Bitwise operators operate on individual bits of integer values. They are useful when working with hardware registers, communication protocols, flags, and packed binary data.

OperatorMeaning
&Bitwise AND
``
^Bitwise XOR
~Bitwise NOT
<<Left shift
>>Right shift

Consider these 8-bit binary values:

A = 00001100 B = 00001010

Bitwise AND

A & B = 00001000

A bit is set in the result only when the corresponding bits in both operands are set.

Bitwise OR

A | B = 00001110

A bit is set if either corresponding bit is set.

Bitwise XOR

A ^ B = 00000110

A bit is set when the corresponding bits differ.

Bit shifting

uint8_t value = 1; uint8_t result = value << 3;

The result is 8, represented as 00001000 in binary.

Use unsigned integer types for bit manipulation where practical, and be careful about operand widths and shift counts.

Example: Setting a bit

uint8_t flags = 0; flags |= (1U << 2);

This sets bit 2 of flags.

Bitwise operators are different from logical operators. For example, & operates on bits, while && evaluates logical conditions.

18. The Ternary Operator

The ternary operator ?: provides a compact way to select between two values based on a condition.

Syntax:

condition ? valueIfTrue : valueIfFalse;

Example:

int temperature = 35; String status = (temperature > 30) ? "HOT" : "NORMAL";

If the temperature is greater than 30, status receives "HOT". Otherwise, it receives "NORMAL".

This can be useful for short conditional assignments. For more complicated logic, use if and else for readability.

19. Operator Precedence

When an expression contains several operators, C++ follows operator precedence rules to determine the order of evaluation.

For example:

int result = 2 + 3 * 4;

Multiplication is evaluated before addition, so the result is 14.

To perform addition first, use parentheses:

int result = (2 + 3) * 4;

The result is 20.

Use parentheses whenever they make a complex expression easier to understand.

20. Type Conversion

Type conversion changes a value from one data type to another.

Implicit conversion

The compiler automatically converts a value when required by an expression.

int number = 10; float result = number;

The integer value 10 is converted to the floating-point value 10.0.

Explicit conversion

You can request a conversion using a cast.

float voltage = 3.75; int wholeVoltage = static_cast<int>(voltage);

wholeVoltage becomes 3. Converting a floating-point value to an integer discards its fractional part; it does not round to the nearest integer.

Integer overflow

An integer type can represent only values within its range.

For example:

uint8_t value = 255; value++;

Because uint8_t represents values from 0 to 255, incrementing 255 wraps the value to 0.

Signed integer overflow, by contrast, is undefined behavior in C++. Do not rely on it wrapping around.

21. Variable Scope

Scope determines where a variable can be accessed in a program.

Local variables

A local variable is declared inside a function or block and is accessible only within its scope.

void setup() { int number = 10; Serial.begin(115200); Serial.println(number); } void loop() { }

The variable number cannot be accessed directly from loop() because it was declared inside setup().

Global variables

A global variable is declared outside functions and can be accessed by functions after its declaration, subject to scope rules.

int counter = 0; void setup() { Serial.begin(115200); } void loop() { counter++; Serial.println(counter); delay(1000); }

The variable counter retains its value between calls to loop().

Static local variables

A local variable declared with static retains its value between function calls.

void printCounter() { static int counter = 0; counter++; Serial.println(counter); }

Each call to printCounter() increments the same counter variable.

Use global and static variables intentionally, particularly in larger embedded projects where shared state can make debugging harder.

22. The volatile Keyword

The volatile keyword tells the compiler that a variable's value may change in ways not evident from the ordinary program flow.

It is sometimes used for variables shared between an interrupt service routine and the main program.

volatile bool eventDetected = false;

For example, an interrupt handler might set a flag that the main loop checks.

However, volatile does not make a variable operation atomic, and it does not by itself provide thread synchronization. Shared data between tasks or interrupts may require additional synchronization techniques appropriate to the platform.

Use volatile only when its behavior is actually needed; it is not a general-purpose optimization or thread-safety keyword.

23. Practical ESP32 Example: Temperature Threshold Monitor

This example combines variables, data types, arithmetic, comparisons, logical conditions, and output control.

The temperature value is simulated so that you can learn the programming concepts without needing a sensor.

const int ledPin = 2; const float temperatureThreshold = 30.0; float temperature = 25.0; void setup() { Serial.begin(115200); pinMode(ledPin, OUTPUT); } void loop() { // Simulated temperature reading temperature += 1.0; Serial.print("Temperature: "); Serial.print(temperature); Serial.println(" C"); if (temperature >= temperatureThreshold) { digitalWrite(ledPin, HIGH); Serial.println("Warning: Temperature threshold reached"); } else { digitalWrite(ledPin, LOW); Serial.println("Temperature is normal"); } if (temperature >= 35.0) { temperature = 25.0; } delay(1000); }

How it works

  1. ledPin stores the selected GPIO number.
  2. temperatureThreshold stores the threshold as a constant floating-point value.
  3. temperature represents a simulated sensor reading.
  4. The program increases the temperature by one degree per iteration.
  5. A comparison determines whether the threshold has been reached.
  6. The ESP32 changes the LED output based on the condition.
  7. The simulation resets the temperature after it reaches 35 degrees.

The onboard LED may not be connected to GPIO 2 on your board. Check the board documentation before running the example with physical hardware.

To use a real temperature sensor, replace the simulated update with the sensor library's reading function and follow the sensor's wiring and initialization requirements.

24. Best Practices for ESP32 Variables and Operators

  • Choose a data type that matches the value and its possible range.
  • Use descriptive names such as temperatureCelsius and sensorValue.
  • Use const for values that should not change.
  • Use fixed-width integer types when exact bit widths are required.
  • Check for division by zero before performing division.
  • Avoid unintended integer overflow.
  • Use parentheses to make complicated expressions clear.
  • Prefer readable conditions over unnecessarily compact expressions.
  • Be careful when combining signed and unsigned integers.
  • Avoid frequent dynamic memory allocation in memory-constrained applications when a predictable alternative is suitable.
  • Verify sensor units, value ranges, and conversion formulas.
  • Test calculations with known values before connecting them to real hardware.

25. Practice Exercises

Complete these exercises to test your understanding.

  1. Declare variables for temperature, humidity, and sensor status.
  2. Create an integer counter that increases every second.
  3. Calculate the average of three sensor readings.
  4. Convert a distance from centimeters to meters.
  5. Write a program that checks whether a temperature exceeds 30 degrees.
  6. Use logical operators to check whether temperature is high and the system is enabled.
  7. Use the ternary operator to display ON or OFF based on a Boolean variable.
  8. Create a uint8_t variable and observe what happens when it increments from 255.
  9. Write a program that uses a constant for an LED pin.
  10. Build a simulated temperature warning system that activates an LED when a threshold is reached.

Summary

Variables store information, data types define how values are represented, and operators perform calculations and comparisons. Scope determines where variables can be accessed, while keywords such as const, constexpr, and volatile provide additional control over how values are handled.

These concepts form the foundation of ESP32 programming. They are used in almost every application involving sensors, actuators, communication, automation, and IoT systems.

Keep learning. Keep building. Keep growing.

© 2026 Ugenz Academy