Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
The Arduino compiler reports was not declared in this scope when it cannot find a valid declaration for a name at the place where your code uses it. The name might be a variable, function, constant, class, or library object. In practice, check the first error for the exact identifier, then verify its spelling, declaration order, braces, scope, required headers, and board compatibility. This is a standard C++ name-visibility problem, not usually a wiring or damaged-board fault. Arduino’s troubleshooting guidance explains the same scope distinction for sketches (official compile troubleshooting).
Read the diagnostic before changing code
A typical message looks like this:
sketch.ino:12:3: error: 'temperature' was not declared in this scope
sketch.inois the source file.12is the line and3is the column.temperatureis the unresolved identifier.- “not declared” means the compiler has not seen a usable declaration.
- “in this scope” means the current function, brace block, file, namespace, or compilation unit cannot access that declaration.
The reported line is where the compiler first detected the problem; the actual mistake can be an earlier missing brace, include, or declaration. Fix the first detailed error, not the final exit status 1, and compile again. Arduino specifically recommends examining the file paths and detailed compiler output (Arduino support).
Fix the common scope and declaration mistakes
A local variable is being used elsewhere
A name declared inside a function exists only in that function:
Recommended Free Tools
void setup() {
int counter = 0;
}
void loop() {
counter++; // Not declared in this scope
}
If both setup() and loop() need persistent state, define it outside the functions:
#1 Best Overall
- 35+ Guided Electronics Projects: Progress from LEDs and buttons to RFID access, real-time clocks, motion and distance sensing, environmental monitoring, motor control and interactive displays for STEM learning, coding clubs and maker projects
- More I/O and Memory for Larger Builds: The MEGA 2560 R3 provides 54 digital I/O pins, including 15 PWM outputs, 16 analog inputs, 4 hardware serial ports and 256 KB flash for projects that combine more sensors, controls and displays
- 200+ Components for Prototyping: Includes LCD1602, RC522 RFID, RTC, DHT11, HC-SR501 PIR, ultrasonic and water-level sensors, GY-521, MAX7219, keypad, joystick, rotary encoder, relay, SG90 servo, stepper motor, DC motor, breadboard and more
- Learn, Modify and Create: Follow 35+ guided lessons with example code, then adjust sensor thresholds, timing, display text, motor behavior and control logic to turn structured exercises into access systems, monitors, alarms and interactive projects
- Organized for Repeatable Learning: Pre-soldered modules, a solderless breadboard, storage case and small-parts box reduce setup time and keep sensors, LEDs, ICs, wires and other components easy to find between projects
int counter = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
counter++;
Serial.println(counter);
delay(1000);
}
Do not make every variable global automatically. Keep temporary calculations local when only one function needs them; use shared state globally only when several functions, callbacks, or device-state logic genuinely require it.
A variable is inside a brace block
if (buttonPressed) {
int mode = 1;
}
Serial.println(mode); // mode no longer exists here
Declare it before the block when it must survive the block, or keep all uses inside the block:
int mode = 0;
if (buttonPressed) {
mode = 1;
}
Serial.println(mode);
The declaration comes after the first use
Ordinary C++ requires a name to be declared before use:
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11void loop() {
Serial.println(value); // Error
int value = 42;
}
Move the declaration above the statement:
void loop() {
int value = 42;
Serial.println(value);
}
Use the smallest scope that satisfies the design. Fixed configuration is clearer as a typed constant:
#include <stdint.h>
constexpr uint8_t ledPin = LED_BUILTIN;
Spelling or capitalization differs
C++ is case-sensitive. sensorValue, SensorValue, and sensorvalue are three different names.
Rank #2
- TURN CODE INTO REAL-WORLD RESULTS — Follow 22+ guided lessons to make LEDs blink, read temperature and distance, move servo and stepper motors, control an LCD and respond to joystick or IR input; ideal for a family weekend build, homeschool unit, coding club or STEM classroom
- MORE PROJECT VARIETY IN ONE ORGANIZED KIT — Includes the UNO R3 controller, LCD1602 with pre-soldered header, breadboard power module, ultrasonic and DHT11 sensors, joystick, IR receiver and remote, SG90 servo, stepper motor, relay, DC motor, fan blade, displays, LEDs, buttons, resistors and jumper wires
- START WITHOUT SOLDERING — Plug-in modules, a solderless breadboard and the pre-soldered LCD help beginners focus on wiring, code and testing; the illustrated component list makes it easier to find each part and move from one lesson to the next
- LEARN THE LOGIC, THEN CREATE YOUR OWN — Use Arduino IDE and the included example code to understand digital input and output, analog sensing, timing, motor control and display functions, then change thresholds, speeds and sequences for alarms, environmental monitors, reaction games and motion projects
- CLEAR SETUP SUPPORT FOR FIRST-TIME BUILDERS — Download the latest tutorial and code, select the UNO board and correct computer port, check component polarity and breadboard rows, and keep power-module input at 9V or below; younger learners should work with an experienced adult
- Compare every character, underscore, singular/plural ending, and capitalization.
- Check for an accidental Unicode character copied from formatted text.
- Search every sketch tab for both the declaration and each use.
- Use Arduino IDE 2 autocomplete as an aid, not as proof that a symbol exists for your selected board (IDE documentation).
When libraries, classes, and functions are involved
A library header is missing
This object needs the header that declares its class:
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
If the include is absent, the compiler may report 'LiquidCrystal_I2C' was not declared in this scope. Install the library through Sketch > Include Library > Manage Libraries if it is not installed. A different message, fatal error: LiquidCrystal_I2C.h: No such file or directory, means the header itself cannot be found; check installation, spelling, and library location. Library discovery and metadata rules are documented by Arduino (build process; library specification).
A function needs a visible prototype
Arduino often generates prototypes for functions in .ino files, but it does not apply that preprocessing to arbitrary .cpp, .c, or .h files. In multi-file or complex code, declare the function before calling it:
void readSensor();
void setup() {}
void loop() {
readSensor();
}
void readSensor() {
}
For shared code, put the declaration in a self-contained header and include it where needed:
// sensors.h
#ifndef SENSORS_H
#define SENSORS_H
#include <Arduino.h>
int readSensor();
#endif
Then include "sensors.h" in both the implementation file and the .ino file. Arduino’s build documentation explains concatenation, automatic Arduino.h inclusion, and prototype generation limits (sketch build process).
Rank #3
- 30+ Guided Electronics Projects: Start with LEDs and build toward LCD1602 displays, RFID access, motion detection, distance sensing, motor control and environmental monitoring for STEM learning, coding clubs, classrooms and hobby projects
- 200+ Components Across 63 Types: Includes an ELEGOO UNO R3 controller, LCD1602, RC522 RFID, RTC, HC-SR501 PIR sensor, ultrasonic sensor, DHT11, GY-521, MAX7219, keypad, joystick, relay, SG90 servo, stepper motor, breadboard and more
- Begin Without Soldering: Pre-soldered modules, a solderless breadboard, organized storage case and small-parts box reduce setup time and help beginners move from lesson to lesson while keeping LEDs, ICs, wires and sensors easy to find
- Learn, Modify and Create: Program the ELEGOO UNO R3 board with Arduino IDE using the included PDF tutorial and example code, then adjust sensor thresholds, timing, display text and motor behavior to turn guided lessons into original projects
- Flexible Power and Project Setup: Includes a 9 V, 1 A power supply, breadboard power module, 9 V battery and USB cable to support controller, breadboard and module experiments without sourcing basic setup accessories separately
A constant or macro is conditional
#ifdef USE_SENSOR
int sensorPin = A0;
#endif
void loop() {
analogRead(sensorPin); // Fails if USE_SENSOR is not defined
}
Define the feature or provide an unconditional declaration appropriate to your design. Prefer const or constexpr for ordinary constants instead of broad macros. Do not add volatile merely to fix visibility; it is for values changed by interrupts or other hardware contexts.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Check braces, tabs, boards, and architectures
Unbalanced braces can change scope
An extra } can end a function early; a missing one can place declarations in an unintended block. In Arduino IDE 2, use Tools > Auto Format, click braces to highlight their matches, and recompile after correcting one small region. Temporarily comment out large sections or reduce the sketch to the smallest failing example.
Multiple tabs and source files are not interchangeable
.ino tabs in one sketch are combined and receive Arduino preprocessing. A normal .cpp or header does not automatically receive prototypes or an implicit Arduino.h. Include headers explicitly, define a global in exactly one .cpp file, and use extern in the header:
// declarations.h
#ifndef DECLARATIONS_H
#define DECLARATIONS_H
extern int sharedValue;
void updateValue();
#endif
// declarations.cpp
#include "declarations.h"
int sharedValue = 0;
void updateValue() { sharedValue++; }
Defining int sharedValue = 0; directly in a shared header can produce multiple-definition linker errors.
The API may belong to another board or library
Names such as analogWriteResolution(12) or WiFi.begin(...) are not universal Arduino APIs. The selected board determines the core, compiler, build variables, and architecture-specific symbols. Select the exact board under Tools > Board; install its package through Tools > Board > Boards Manager; then verify that the library and API support that architecture. A board change cannot repair a genuine spelling or scope error, but it matters when the unresolved symbol is board-specific.
Rank #4
- All-in-One Starter Kit for Beginners: Part of the Powered by Arduino program, this kit includes an original Arduino UNO R4 WiFi, 300+ high-quality components, 50+ hands-on projects (30 basic, 13 fun, and 8 IoT), and 100+ free video lessons co-created with renowned educator Paul McWhorter. Designed for beginners ages 8+, it provides a complete, step-by-step path to learn Arduino, electronics, coding, and IoT. RoHS compliant for added safety and quality, it also makes a thoughtful gift for tech enthusiasts, students, and aspiring makers for birthdays, holidays, and special occasions
- Powerful Arduino Uno R4 WiFi Board: Upgraded from the Arduino Uno R3, the Arduino Uno R4 WiFi features a 32-bit processor, more memory, and built-in WiFi and Bluetooth, enabling connection to third-party apps for more interactive and practical projects.
- 300+ Components for Endless Possibilities: With 300+ components and sensors, this kit is perfect for portable projects. It features step-by-step tutorials, open-source code, and compatibility with other Arduino boards like Uno R3 and Nano, offering endless customization and learning opportunities.
- Engaging Projects for Every Skill Level: Featuring 50 projects (30 basic, 13 fun, 8 IoT) with IoT app integration like Arduino IoT Cloud , this kit supports Arduino C++ programming, making it perfect for students, teachers, and engineers to learn, code, and create at any skill level.
- Dedicated Support for Beginners: Alongside online resources and video tutorials, SunFounder provides technical support and troubleshooting forums to help beginners solve programming challenges with ease.
Compare the tutorial’s board model, library name and version, header, class, example, and wiring assumptions. Arduino’s build and library rules describe architecture compatibility and library selection (build process; library specification).
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Distinguish this error from nearby failures
| Message | Usually means | First action |
|---|---|---|
'x' was not declared in this scope |
The name is unknown at its use site | Check declaration, spelling, order, and scope |
fatal error: x.h: No such file or directory |
The header cannot be found | Install the library or correct the header name |
undefined reference to x |
A declaration was seen, but no implementation was linked | Check definitions and source files |
multiple definition of x |
The same object was defined in more than one translation unit | Use one definition and extern declarations elsewhere |
expected '}' at end of input |
Braces are unbalanced | Auto-format and inspect matching braces |
No such file or directory for a board toolchain |
A board package or compiler component is unavailable | Install and select the correct board package |
A five-minute recovery checklist
- Click Verify (Compile).
- Read the first detailed error containing
was not declared in this scope. - Copy the quoted identifier exactly.
- Search all tabs and files for every occurrence.
- Confirm that it is declared, spelled identically, and declared before its first use.
- Check whether its declaration is trapped inside another function, brace block, or
#ifdef. - Check the required
#includeand install the library through Sketch > Include Library > Manage Libraries. - Check the selected board and architecture.
- Use Tools > Auto Format and inspect braces.
- Compile again. If the message becomes a missing-header error, resolve the library; if it becomes an undefined-reference or multiple-definition error, resolve linking.
- If it still fails, create a minimal sketch containing only the declaration and failing use, then add code back incrementally.
Command-line verification with Arduino CLI
Arduino CLI users can identify boards and compile with the exact fully qualified board name (FQBN) supplied by their installed package:
arduino-cli board list
arduino-cli board listall
arduino-cli compile --fqbn <vendor:architecture:board> /path/to/sketch
Do not substitute a guessed FQBN; board packages use different identifiers. The CLI build compiles source files into intermediate objects and then links the firmware (Arduino build process).
Declaration versus definition
A declaration tells the compiler that a name and type exist; a definition allocates storage or supplies the function body:
Free tools Windows power users keep installed
One-click scans. No signup required.
extern int sensorValue; // declaration only
int sensorValue = 0; // one definition
Most single-file sketches need the straightforward definition. extern becomes useful when one global is defined in a .cpp file and consumed by another. A successful compile only establishes that names and syntax are valid; runtime behavior, timing, resets, and hardware wiring are separate issues.
Best Value
- The most economical kit comes with everything compatible with Arduino to starting programming for beginners .
- This is the upgraded starter kits come with a 9V 1A Power Adapter (At least $5.99 on amazon) to replace a 9V Battery , and the Lcd1602 module come with pin header(not need to be soldered by yourself).
- Include High Quality Base Board base on Arduino UNO R3 compatible with Arduino IED and Sensors, Servo, Motor, ULN2003 driver board, lcds, etc.
- Free PDF Tutorial and Datasheet are available to download from our official website or you can contact our customer service.
- All of the Components and Integrated Circuits are individually packaged and labeled, and packing in a plastic box which is bigger enough for you.
Frequently Asked Questions
Why does a variable work in setup() but not loop()?
It was probably declared inside setup(), so its scope ends when setup() ends. Move the declaration to a shared outer scope only if both functions need the same persistent state.
Should I make every undeclared variable global?
No. Make a name global only when multiple functions or callbacks need shared state; otherwise declare it in the smallest block that uses it.
Why did adding an include change the error?
The compiler may now recognize the class but expose a separate installation, API-version, architecture, or linker problem. Resolve the first remaining detailed error.
Why does code work in an .ino tab but fail in a .cpp file?
Arduino preprocessing supplies conveniences such as generated prototypes and, when appropriate, Arduino.h for .ino compilation. Add explicit prototypes and includes in ordinary source files.
The Bottom Line
Find the exact identifier in the first compiler error, then verify declaration, spelling, order, scope, braces, headers, conditional compilation, and board support in that order. Most cases are fixed without replacing hardware or buying anything.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

