Language & I/O reference

Theory Reference

Full language, I/O and circuit theory reference for this course. Read the matching sections before practical lessons.

About this reference

Use this page as a lookup while you build. Practical lessons still own wiring and full sketches. When a lesson says Read this first, jump to the linked topic below.

note

How to use this reference

Topics here cover Arduino sketch language, core I/O functions, timing, Serial, and the starter circuit ideas used early in the course. Hardware beyond this scope (I2C, DHT, RTC, ultrasonic, IR, RFID and similar) is taught in the dedicated lessons for those modules.

Uno Rev3 and UNO R4 Minima board photos are official Arduino® images from store.arduino.cc (CC BY-SA). Arduino® is a trademark of Arduino S.r.l.

Board guide: Uno R3 and R4 Minima

Know the board under your hands: power pins, I/O, on-board LEDs, and what changes if you use an Uno R4 Minima. This course defaults to Uno R3.

table

Arduino Uno R3

Classic Uno Rev3 with ATmega328P, USB-B, and 5 V logic. Default board for this course. Product overview: Arduino store - Uno Rev3 (store.arduino.cc/products/arduino-uno-rev3).

Arduino Uno Rev3 board
Uno R3 - locate 5V, 3.3V, GND, VIN, AREF, L LED and TX/RX LEDs.Photo: Arduino® official product photo (Uno Rev3).Arduino® is a trademark of Arduino S.r.l.
ItemUno R3
MicrocontrollerATmega328P @ 16 MHz
Memory32 KB Flash, 2 KB SRAM, 1 KB EEPROM
Logic / USB5 V logic; USB-B programming
Digital I/OD0-D13 (PWM on ~ : 3, 5, 6, 9, 10, 11)
AnalogueA0-A5, 10-bit ADC (0-1023) by default
VIN / barrelAbout 7-12 V recommended
I/O current designAbout 20 mA per pin (40 mA absolute max)
Built-in LED (L)Digital pin 13 / LED_BUILTIN
TX / RX LEDsFlash on USB serial activity
table

Arduino Uno R4 Minima

Same Uno form factor and 5 V class, Renesas RA4M1 MCU, USB-C, more memory and extras (DAC, RTC, CAN, HID). Select “UNO R4 Minima” in the IDE. Product overview: Arduino store - UNO R4 Minima (store.arduino.cc/products/uno-r4-minima).

Arduino Uno R4 Minima board
Uno R4 Minima - USB-C and a faster MCU; still 5 V logic on the Uno header layout.Photo: Arduino® official product photo (UNO R4 Minima).Arduino® is a trademark of Arduino S.r.l.
ItemUno R4 Minima
MicrocontrollerRA4M1 (Arm Cortex-M4) @ 48 MHz
Memory256 KB Flash, 32 KB SRAM, 8 KB EEPROM
Logic / USB5 V logic; USB-C programming
Digital I/O14 pins; 6 PWM
Analogue6 inputs; higher resolution available (up to 14-bit)
VIN / barrelAbout 6-24 V
I/O current designAbout 8 mA per pin - use drivers for heavier loads
Built-in LED (L)Digital pin 13 / LED_BUILTIN
ExtrasDAC, RTC, CAN (external transceiver), HID, SWD
Watch out: Do not assume classic Uno “20 mA per pin” on R4 Minima. Check current before driving LEDs or loads directly from a pin.
note

Power pins: 5V, 3.3V, VIN, AREF, GND

Shared ideas on Uno R3 and R4 Minima power headers.

What each pin is for

5VRegulated 5 V

Powers the MCU and many 5 V modules when the board is supplied from USB or VIN/barrel. Do not casually feed an external supply into the 5V pin.

3V33.3 V rail

Limited current for 3.3 V modules (about 50 mA on classic R3). Never put 5 V into a 3.3 V-only device.

GNDCommon ground

Every external circuit must share GND with the Uno.

VINBoard input

Raw input path (barrel jack). R3: about 7-12 V recommended. R4 Minima: about 6-24 V. Not a sensor logic output.

AREFADC reference

Default analogue range is about 0-5 V. Leave open until a lesson uses analogReference().

IOREFI/O voltage sense

Tells shields the board’s I/O voltage (5 V here). Rarely used in beginner wiring.

Watch out: Never apply more than 5 V to a digital or analogue I/O pin on these Unos.
table

Uno R3 versus R4 Minima

Same shield layout family; different MCU, memory, USB and pin-current budget.

FeatureUno R3Uno R4 Minima
MCU / clockATmega328P / 16 MHzRA4M1 / 48 MHz
Flash / SRAM32 KB / 2 KB256 KB / 32 KB
USBUSB-BUSB-C
VIN typical7-12 V6-24 V
I/O current design~20 mA~8 mA
API sketchesCourse defaultOften OK; pick correct board; watch libraries

1. Sketch structure and syntax

Every Uno sketch needs a clear shape: declarations, one-time setup, then a repeating loop. Syntax rules keep the compiler happy; a shared style keeps sketches readable and consistent with Arduino examples.

concept

Program structure: setup() and loop()

void setup() {
  /* once */
}

void loop() {
  /* forever */
}

Global declarations (constants, variables, objects) usually sit above setup. setup() runs once after reset or power-up for configuration such as pinMode and Serial.begin. loop() then runs for the life of the program: read inputs, decide, write outputs. Both functions must exist even if one body is empty.

concept

Functions

returnType name(parameters) {
  // statements
}

A function is a named block that runs when called. setup and loop are functions. Write your own to name a task, pass parameters, return a value, and reuse logic. void means no return value. Keep functions short so each one is easy to test.

note

Code conventions overview

A shared style keeps sketches organised, easy to mark, and closer to official Arduino examples and libraries. The rules below cover naming, braces, spacing, and pin constants. Follow them in this course unless a brief says otherwise.

table

Naming conventions

Use clear, descriptive names-not single letters or vague labels. Match the style to the kind of name.

ElementStyleGood examplesAvoid
VariablescamelCasesensorValue, ambientTemp, buttonStatex, n, val, data, temp, a
Pin / constantsSNAKE_CASELED_PIN, BUTTON_PIN, MAX_SPEEDp, pin, led, 13 (magic number)
FunctionscamelCasereadSensor(), calculateAverage(), updateDisplay()doStuff(), fn(), process()
Custom types / classesPascalCaseMotorController, ButtonStatething, myclass, data
Tip: Names are case-sensitive. ledPin and LEDPIN are different identifiers.

Good names versus weak names

A good name tells the next reader (or marker) what the value means without hunting through the sketch.

AvoidPreferWhy
int x = analogRead(A0);int sensorValue = analogRead(A0);Says what is stored, not just a letter
int temp = 22;float ambientTemp = 22.0;temp could mean temporary or temperature
const int pin = 2;const int BUTTON_PIN = 2;Names the role; UPPERCASE marks a fixed pin
digitalWrite(13, HIGH);digitalWrite(LED_PIN, HIGH);No magic number; one change updates every use
void doIt() { … }void updateAlarm() { … }Function names should say the action
bool flag;bool alarmActive;flag says nothing about the meaning
Tip: If you must use a short loop index, i or j is fine inside a small for loop. Everywhere else, prefer a name that reads like English.
syntax

Curly braces and indentation

void loop() {
  if (sensorValue > 500) {
    digitalWrite(LED_PIN, HIGH);
  } else {
    digitalWrite(LED_PIN, LOW);
  }
}

Braces mark the start and end of a block: function bodies, if branches, loop bodies. Every opening brace needs a matching close.

Course brace style

2 spacesIndent size

Indent each nested block by 2 spaces (Arduino IDE default). Do not mix tabs and spaces in one file.

{Opening brace

Place { on the same line as the if, else, for, while, switch, or function declaration.

}Closing brace

Place } on its own line, lined up with the statement that opened the block.

Tip: Indentation helps humans; the compiler only cares that braces match.
syntax

Spacing guidelines

// Good
int total = count + 5;
if (value == HIGH) {
  digitalWrite(LED_PIN, HIGH);
}
analogWrite(LED_PIN, 128);

// Avoid
int total=count+5;
if(value==HIGH){
  digitalWrite(LED_PIN,HIGH);
}
analogWrite(LED_PIN,128);

Spacing stops code looking clumped and makes operators and conditions easier to scan.

Where to put spaces

= + ==Binary operators

One space before and after operators such as =, +, -, ==, >, && and ||.

if (Control keywords

Space after if, while, for and switch-but not between a function name and its (.

,Commas

Space after commas in argument lists: analogWrite(LED_PIN, 128);

syntax

Hardware pins and constants

// Good
const int BUTTON_PIN = 2;
const int RELAY_PIN = 7;

void setup() {
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  pinMode(RELAY_PIN, OUTPUT);
}

// Avoid
void setup() {
  pinMode(2, INPUT_PULLUP);
  pinMode(7, OUTPUT);
}

Define pin numbers once at the top of the sketch with const int (preferred) or #define. Never scatter raw “magic numbers” through pinMode, digitalWrite or analogRead calls-changing a wire then means hunting every occurrence.

Tip: Name the role, not only the number: BUTTON_PIN is clearer than PIN2.
syntax

Semicolon

statement;

Most statements end with a semicolon. A missing semicolon is a common compile error and may be reported on the next line. Do not place a semicolon immediately after if (...), for (...), or while (...) unless you intentionally want an empty statement.

Watch out: A stray semicolon after if (buttonPressed); creates an empty body. The following braces then always run.
syntax

Comments

// line comment
/* multi-line
   block comment */

Comments are ignored by the compiler. Prefer comments that state intent, units, pin roles and safety assumptions-not only what the next line obviously does.

2. Variables, types and arrays

Choose a type that fits the range you need, name values clearly, and keep scope as narrow as practical.

concept

Variables

A variable names stored data the program can read and change. Prefer clear camelCase names such as sensorValue. Use UPPERCASE constants such as LED_PIN for pin numbers and other values that must not change. See Naming conventions for the full style table.

syntax

Variable declaration

int sensorValue = 0;

Declare before use: type, name, and optional initial value. Declaration allocates storage and tells the compiler how to interpret the bits.

concept

Variable scope

Scope is where a name is visible. Globals above setup are visible to many functions. Locals inside a function or block exist only there. Prefer the narrowest useful scope so lifetimes stay clear and names do not collide.

type

Type: byte

byte x;  // 0 … 255

8-bit unsigned integer. Useful for pin numbers and small counters. Cannot store fractions.

type

Type: int

int x;  // about -32768 … 32767 on Uno

On the classic Uno (ATmega328P), int is 16-bit signed. Everyday integer type for many sketches. Watch for overflow when totals grow.

type

Type: long / unsigned long

long x;
unsigned long t;

Wider integers (32-bit on the Uno). Use when values may exceed int range. millis() returns unsigned long-store timestamps in unsigned long.

type

Type: float

float v = reading * 5.0 / 1023.0;

Approximate decimal numbers for voltages and averages. Integer division discards the remainder unless at least one operand is floating-point (for example total / 4.0).

concept

Arrays

int leds[] = {2, 3, 4, 5};
// leds[0] == 2

Several values of one type under one name, accessed by index. The first index is 0. Never read or write past the last valid index.

3. Operators and control flow

Calculate, compare, and choose which statements run. One wrong operator (= vs ==) is a classic bug.

syntax

Arithmetic operators

a + b    // add
a - b    // subtract
a * b    // multiply
a / b    // divide
a % b    // remainder (modulo)

x = x + 1;
x += 1;   // same idea, shorter
i++;      // add 1 to i
i--;      // subtract 1 from i

Use these to calculate with numbers stored in variables or written as literals.

Basic operators

+Addition

Adds two numbers. Example: 3 + 2 = 5.

-Subtraction

Subtracts the right number from the left. Example: 10 - 4 = 6.

*Multiplication

Multiplies two numbers. Example: 3 * 4 = 12.

/Division

Divides the left number by the right. With whole numbers (int), the fraction is dropped: 7 / 2 = 3, not 3.5. Use a decimal such as 7.0 / 2 if you need 3.5.

%Modulo (remainder)

Answers: after dividing, what is left over? Example: 10 % 3 = 1, because 3 fits into 10 three times (9) with 1 left. Odd/even checks: 7 % 2 = 1 (odd), 8 % 2 = 0 (even). Also useful for wrapping counters and alternating patterns.

Compound and shortcut operators

+= -= *= /=Compound assignment

Update a variable using its current value. x += 1 means take x, add 1, and store the result back in x (same as x = x + 1). Likewise x -= 2, x *= 2, or x /= 2.

++ --Increment / decrement

Shortcuts to add or subtract 1. i++ adds 1 to i; i-- subtracts 1. Common in for loops when counting one step at a time.

Tip: If you need a decimal result from division, make at least one value floating-point (for example total / 4.0), otherwise int maths drops the fraction.
syntax

Comparison operators

a == b   // equal to
a != b   // not equal to
a <  b   // less than
a <= b   // less than or equal
a >  b   // greater than
a >= b   // greater than or equal

Comparison operators ask a yes/no question about two values. The answer is true or false, and is usually used inside if or a loop condition.

Comparisons

==Equal to

True only when both sides are the same. Example: sensorValue == 0 is true only when sensorValue is exactly 0.

!=Not equal to

True when the sides differ. Example: buttonState != HIGH is true when the button is not HIGH.

<Less than

True when the left value is smaller than the right.

>Greater than

True when the left value is larger than the right.

<=Less than or equal

True when the left value is smaller than or the same as the right.

>=Greater than or equal

True when the left value is larger than or the same as the right. Example: reading >= 512 is true in the upper half of the 0-1023 analogue range.

Assignment vs comparison

=Assign

Stores a value into a variable. state = HIGH puts HIGH into state.

==Compare

Checks whether two values are already equal, without changing them. state == HIGH asks: is state already HIGH?

Watch out: if (state = HIGH) assigns HIGH and is almost always a mistake. The condition becomes true because the assigned value is HIGH. Use == for comparisons.
syntax

Logical operators

A && B   // AND - both must be true
A || B   // OR  - either may be true
!A       // NOT - reverse true/false

Logical operators combine or reverse true/false conditions. They are the usual tools inside if and while tests when more than one input matters.

Combining conditions

&&AND

True only when both sides are true. Example: (buttonA == LOW) && (buttonB == LOW) is true only when both buttons are pressed (active-low wiring).

||OR

True when either side is true (or both). Example: (alarm) || (override) is true if the alarm is on, or override is on, or both.

!NOT

Flips true to false and false to true. Example: if (!ready) means “if ready is false”. Also useful as ledOn = !ledOn; to toggle a Boolean each time.

Reading complex tests

( )Parentheses

Group parts of a condition so the meaning is obvious. Prefer if ((a == LOW) && (b == HIGH)) over a long chain without brackets.

Tip: Evaluate one condition at a time on paper if a compound if feels confusing: write true/false under each part, then apply && or ||.
api

Constants: true, false, HIGH, LOW

true / false
HIGH / LOW

Boolean values and digital logic levels. On a 5 V Uno, HIGH is about 5 V and LOW about 0 V. Used with digitalWrite and as digitalRead results.

api

Constants: INPUT, OUTPUT, INPUT_PULLUP

pinMode(pin, INPUT);
pinMode(pin, OUTPUT);
pinMode(pin, INPUT_PULLUP);

INPUT is high-impedance. OUTPUT drives the pin. INPUT_PULLUP enables the chip's internal pull-up on that pin-common for buttons to GND.

syntax

if / else

if (condition) {
  // …
} else if (other) {
  // …
} else {
  // …
}

Runs a block only when the condition is true. if / else chooses either-or. if / else if / else chains are mutually exclusive-only the first true branch runs.

syntax

for loops

for (int i = 0; i < 10; i++) {
  // body
}

Three parts separated by semicolons: init (once), condition (each pass), change (each pass). Something must eventually make the condition false.

syntax

while and do/while

while (condition) { /* … */ }

do {
  /* … */
} while (condition);

while repeats while the condition stays true-if nothing changes the tested value, it never exits. do/while runs the body at least once, then tests at the end.

4. Digital I/O

Configure pins, read switches, write logic levels. Respect current limits on every OUTPUT.

note

Power and safety rules

Keep these rules in mind whenever you wire outputs or share supplies with motors and modules.

Lab rules

GNDCommon ground

Every circuit that talks to the Uno must share GND with the Uno. Different grounds mean broken signals and odd faults.

20 mAPin current design limit

Design for about 20 mA or less per I/O pin. 40 mA is an absolute maximum, not a normal target.

LoadDrivers for heavy loads

Never power a motor, relay coil, or solenoid from an I/O pin. Use a transistor/MOSFET/driver and a suitable external supply.

DiodeFlyback protection

Inductive loads (relays, motors, solenoids) need a flyback diode across the coil so switching spikes do not damage the switch or the Uno.

ELVExtra-low voltage only

This course uses safe DC levels only. Never connect mains electricity to Arduino projects.

Watch out: Switch power off before moving wires. Confirm supply voltage and common GND before the first power-up.
api

pinMode()

pinMode(pin, mode);

Configure a pin as INPUT, OUTPUT or INPUT_PULLUP in setup. Set modes explicitly even though pins often default toward inputs. Design for about 20 mA or less per I/O on the Uno; 40 mA is an absolute maximum, not a normal target.

Watch out: Short circuits or overloads on OUTPUT pins can damage the microcontroller.

Active-low buttons and pull-ups

Most course button examples use INPUT_PULLUP and a switch to GND. That is active-low: pressed connects the pin to 0 V. Always write if (digitalRead(pin) == LOW) when you mean “pressed” in that wiring style.

SwitchPin readsMeaning (INPUT_PULLUP to GND)
Open (not pressed)HIGH (~5 V)Released - pull-up holds the pin high
Closed (pressed)LOW (~0 V)Pressed - pin shorted to GND
Tip: Active-high is the opposite idea: a button that pulls the pin up to 5 V when pressed, usually with an external pull-down. Know which style you built before you write the if test.
api

digitalRead()

int state = digitalRead(pin);  // HIGH or LOW

Returns HIGH or LOW. With INPUT_PULLUP and a button to GND: open reads HIGH, pressed reads LOW (active-low). Document which polarity your wiring uses.

api

digitalWrite()

digitalWrite(pin, HIGH);
digitalWrite(pin, LOW);

Drive an OUTPUT pin high or low. Use for LEDs (with series resistor), logic inputs, and similar loads-not motors or relays without a driver.

5. Analogue I/O and PWM

Read voltages with the ADC; fake analogue drive with pulse-width modulation on ~ pins.

api

analogRead()

int reading = analogRead(A0);  // 0 … 1023

10-bit ADC on A0-A5. With the default 5 V reference, 0 ≈ 0 V and 1023 ≈ 5 V. Convert with V = reading * 5.0 / 1023.0. Pins used only as ADC inputs do not need pinMode(OUTPUT).

api

analogWrite() and PWM

analogWrite(pin, value);  // value 0 … 255

Hardware PWM on pins marked ~ (Uno: 3, 5, 6, 9, 10, 11). 0 is fully off, 255 fully on; values between set duty cycle. PWM is a fast digital pulse train-not a true DC analogue voltage-but many loads respond to average power.

6. Timing, helpers and Serial

Schedule work without freezing the sketch, and print values for debugging.

api

delay()

delay(ms);

Pauses the sketch for ms milliseconds. Simple for first demos, but nothing else runs during delay. Prefer millis-based timing when several tasks must stay responsive.

Tip: If a button feels dead while an LED blinks with delay(), switch that blink to millis().
api

millis()

unsigned long now = millis();
if (now - last >= interval) {
  last = now;
  // do work
}

Milliseconds since start, as unsigned long. Save a start time; when millis() - start >= interval, run the action and update start. Overflow after many days is fine when both values are unsigned long. Give each independent task its own timestamp.

api

min(), max(), random()

min(a, b);
max(a, b);
randomSeed(seed);
random(min, max);

min/max return the smaller or larger value. randomSeed sets the pseudo-random sequence (often millis() or analogRead on a floating pin). random returns a value in range.

api

Serial.begin() and Serial.println()

Serial.begin(9600);
Serial.println(value);

Opens USB serial (9600 is common for learning) and prints a line to the Serial Monitor. On the Uno, D0 (RX) and D1 (TX) are reserved for that link. Match Monitor baud to begin; use a USB data cable.

7. Circuit theory notes

Starter circuit ideas from the notebook appendix. Build details live in the practical lessons linked under each note.

circuit

Digital output (LED)

Drive an LED from a digital output through a series resistor to GND (or the correct polarity arrangement). The classic hello-world hardware path.

circuit

Digital input (button)

Two-state input. With INPUT_PULLUP, wire the button between pin and GND. Debounce mechanical bounce in software for reliable counts.

circuit

High-current output

Uno pins cannot safely drive motors, relays or large loads directly. Use a transistor or MOSFET as a low-side switch, external supply, common GND, and a flyback diode on inductive loads.

Watch out: Never power a motor from an I/O pin. Shared GND is mandatory between Arduino and the load supply.
circuit

PWM output

Vary duty cycle to dim an LED or set motor-enable speed on a driver. Always use a PWM-capable (~) pin for analogWrite.

circuit

Potentiometer input

Voltage divider from 5 V to GND; wiper to an analogue pin yields 0-1023 for position or setpoint control.

circuit

Variable-resistor sensors

LDRs, thermistors and similar change resistance with light or temperature. Place in a divider with a fixed resistor; read the junction with analogRead. Convert counts with calibration, not guesswork.

circuit

Servo output

Hobby servos need periodic control pulses and adequate 5-6 V motor power with common GND. Prefer the Servo library for angle control unless a lesson asks for hand-timed pulses.

8. Quick reference

Pin map, conversions, common faults, and glossary for oral checks and lab sheets.

table

Uno pin map

Classic Arduino Uno R3 roles used in this course (header layout matches R4 Minima for typical shields).

GroupPins / notes
Digital I/OD0-D13
Analogue inA0-A5
PWM (~)D3, D5, D6, D9, D10, D11
UARTD0 RX, D1 TX
I2CA4 SDA, A5 SCL
SPID10-D13 (SS/MOSI/MISO/SCK)
External interruptsD2, D3
Logic / current5 V logic; R3 design ≤ 20 mA/I/O; R4 Minima ~8 mA/I/O
table

Units and conversions

Formulas students use constantly in labs. Keep units consistent (volts, ohms, amperes, milliseconds).

NeedFormula / rule
ADC count → volts (default 5 V ref)V = reading × 5.0 / 1023.0
Volts → ADC count (approx.)reading ≈ V × 1023.0 / 5.0
LED series resistorR = (Vsupply − Vled) / Iled e.g. (5 − 2) / 0.010 = 300 Ω → use 330 Ω
Ohms lawV = I × R
PWM duty (0-255)About value/255 of the time HIGH; 0 = off, 255 = full on
millis intervalif (millis() − last >= intervalMs) { last = millis(); /* work */ }
Seconds ↔ milliseconds1 s = 1000 ms; delay(500) is half a second
table

Common sketch and wiring faults

Match the symptom to the usual cause before random rewiring.

SymptomLikely causeWhat to check
Compile error near a later lineMissing ; on the previous lineAdd the semicolon; read the first error, not only the last
Weird if behaviour / always trueUsed = instead of ==Comparisons need ==; = assigns
Pin never changes / floating inputForgot pinMode or pull-uppinMode in setup; buttons usually INPUT_PULLUP
Serial garbage or nothingBaud mismatch or charge-only cableMatch Serial.begin and Monitor; use a data USB cable
LED dim/wrong or pin hotNo series resistor / overloadAdd resistor; stay within ~20 mA per pin
Button flickers many timesMechanical bounceDebounce in software (Lesson 08)
Motor resets the boardMotor powered from Uno pin/USB aloneExternal motor supply + common GND + driver
Wrong average / truncated mathsInteger divisionUse a float operand, e.g. total / 4.0
Crash or nonsense after many loopsint overflow or bad array indexUse long/unsigned long; stay inside array bounds
glossary

Glossary

Terms you should be able to explain in assessment.

ADC
Analogue-to-digital converter - turns a voltage into a count.
PWM
Pulse-width modulation - varies duty cycle of a digital pulse train.
UART
Asynchronous serial link (USB Serial on the Uno uses D0/D1).
GPIO
General-purpose input/output pin.
Pull-up
Resistor that holds an open input at a defined HIGH level.
Active-low
The active condition is logic LOW (common for INPUT_PULLUP buttons to GND).
Duty cycle
Fraction of time a PWM signal is HIGH.
Debounce
Ignoring extra edges from a bouncing mechanical switch so one press counts once.
Flyback diode
Diode across an inductive coil that safely absorbs turn-off voltage spikes.

Revision check

Download .ino sketch

Predict the Serial output before you upload. Then confirm in the Serial Monitor.

// Predict the Serial output before uploading.
int values[] = {2, 4, 6, 8};

void setup() {
  Serial.begin(9600);
  int total = 0;
  for (byte i = 0; i < 4; i++) {
    total += values[i];
  }
  Serial.println(total);
  Serial.println(total / 4.0);
}

void loop() {}

Expected reasoning

  1. The integer total is 20.
  2. Using 4.0 forces a floating-point average of 5.00.
  3. Use this sketch to practise predicting results before uploading.

Check your understanding

Q1. What runs once after reset, and what runs repeatedly?

Show answer

setup() runs once; loop() repeats.

Q2. What is the difference between = and ==?

Show answer

= assigns; == compares equality.

Q3. Why prefer millis over long delay calls in multi-task sketches?

Show answer

delay blocks loop; millis schedules work without stopping other tasks.

Q4. List the Uno PWM pins used with analogWrite.

Show answer

D3, D5, D6, D9, D10 and D11.

Q5. What is the recommended design current per Uno I/O pin?

Show answer

About 20 mA or less; 40 mA is an absolute maximum.

Extension challenge: Create a one-page handwritten cheat sheet from this reference, then answer oral questions without looking.

Reference: Brian Evans Arduino Notebook (CC BY-NC-SA 3.0)