Engineering · Arduino · Programming
Variables, Functions & Libraries
Blink hard-codes everything. Real sketches store readings in variables, turn repeated steps into functions you can call by name, and borrow other people's tested code with a single #include line instead of reinventing it.
int lightLevel = 0;
int brightness = 0;
void setup() {
pinMode(9, OUTPUT);
Serial.begin(9600);
}
int scaleReading(int raw) {
return map(raw, 0, 1023, 0, 255);
}
void loop() {
lightLevel = analogRead(A0);
brightness = scaleReading(lightLevel);
analogWrite(9, brightness);
}
Arduino Studio · write it, run it, upload it
Build a sketch in blocks
Every Arduino sketch has two parts: setup() runs once, loop() runs forever. Snap blocks into them, press Upload & run, and the simulated board below obeys, wired exactly like the class kit.
Loading the block editor…
Loading…
On a real board…
Pins 2–13
Variables
Serial Monitor
The same sketch in C++ · uploading it to a real UNO
This is exactly what your blocks mean, written the way the Arduino IDE expects. Press Download .ino, open it in the Arduino IDE (it will offer to put it in a folder of the same name), choose Board: Arduino Uno and the port, then press Upload. Wire the parts as listed at the top of the sketch. Servo sketches use the Servo library, which comes with the IDE.
The simulator is a model: it runs your blocks hundreds of times a second rather than thousands, and its sensors are sliders. Test each sketch on the real board before trusting it.
Storing information
Variables & data types
A variable is a named box that holds a value your sketch can read and change. Every variable in C++ (the language Arduino sketches are written in) needs a data type that says what kind of value it can hold.
| Type | Holds | Example |
|---|---|---|
int | Whole numbers, roughly ±32,000 | int pin = 9; |
float | Decimal numbers | float tempC = 21.5; |
bool | true / false only | bool isPressed = false; |
char | A single character | char grade = 'A'; |
Match each scenario to the data type that fits it best.
Storing a temperature reading of 21.5°C
Tracking whether a button is currently pressed
Counting how many times a sensor has triggered
Storing a raw analogRead() value (0–1023)
Try it in the Arduino Studio: Button dice keeps a long variable counting your rolls.
Reading the analog world
analogRead() and map()
A sensor's raw reading rarely matches the range you want to use it in. analogRead() returns a value from 0 to 1023; analogWrite() (PWM brightness) expects 0 to 255. map() rescales one range into another. Drag the slider to simulate a light sensor and watch both numbers — and the LED — update.
lightLevel = analogRead(A0); brightness = map(lightLevel, 0, 1023, 0, 255); analogWrite(9, brightness);
Try it in the Arduino Studio: Knob dimmer reads A0, maps it to 0–255 and prints it to the Serial Monitor.
Reusable steps
Writing your own function
A function packages a sequence of steps under one name. scaleReading(raw) takes a parameter (an input value named raw) and returns a result — so loop() can call it instead of repeating the math every time. Press run to trace which code actually executes when loop() calls the function.
loop()
void loop() { lightLevel = analogRead(A0); brightness = scaleReading(lightLevel); analogWrite(9, brightness); }
scaleReading()
int scaleReading(int raw) { return map(raw, 0, 1023, 0, 255); }
Ready — press run to trace execution.
Try it in the Arduino Studio: SOS defines dot() and dash() once and calls them nine times.
Don't reinvent the wheel
Libraries: borrowing tested code
A library is someone else's code, packaged so you can use it with one line — #include <LibraryName.h> — instead of writing the low-level details yourself. Three you'll meet constantly:
<Servo.h>Turns a few lines of manual pulse-timing into myServo.write(90); — set an angle and go.
<Wire.h>Handles the I2C protocol so two-wire sensors and displays can be addressed by a simple ID number.
<DHT.h>Decodes a temperature/humidity sensor's raw timing signal into clean °C and % values.
Libraries are installed once (Library Manager) and included once per sketch — but which board you've selected can still matter, since some libraries only work with certain chips (a Wi-Fi library for the ESP32 won't run on an Uno).
Try it in the Arduino Studio: Servo sweep uses <Servo.h>; open the C++ view to see the #include.
Class build · sensor + controller + motors
Program a bumper robot
Start with the State Machines simulator: predict what an obstacle event should do. This classroom robot uses a front bumper switch rather than a vacuum's sensors. It drives until the bumper is pressed, reverses briefly, turns, and drives again. The three states are the plan; a switch input triggers the transition, and two motors carry out each state's action.
One specific build
- Arduino Uno, two DC motors and wheels on a chassis, a normally open bumper switch, and a TB6612FNG dual motor driver. Need a protective housing? Mount the board with a custom 3D-printed case from Forge.
- Bumper: one terminal to D2, the other to GND.
INPUT_PULLUPreads HIGH until the switch closes. - Driver:
STBY→D4,PWMA→D5,PWMB→D6,AIN1→D7,AIN2→D8,BIN1→D9,BIN2→D10; outputs A and B go to the two motors. - Driver
VCC→Uno 5V; driverVM→motor-rated battery +; connect battery −, driver GND, and Uno GND together. Use the motor and driver ratings to choose the battery. Never power motors from an Uno output pin.
Test in stages
- Keep motor power disconnected while wiring. Ask a teacher to check polarity, the common ground, and the driver pin labels.
- Lift the wheels off the table. Upload the sketch, connect motor power, and check that DRIVE spins both wheels forward. If a wheel reverses, disconnect power before swapping that motor's two leads.
- Press the bumper: both wheels should reverse, then turn in opposite directions, then drive forward. Set the bot on a clear floor and repeat from the same starting point.
- Run at least ten obstacle tests. Record each success or failure and the condition that changed. Use the Probability Simulator to discuss why a few successes do not establish reliability.
Starter sketch for this exact wiring: state remembers the current behavior, enteredAt remembers when it began, and setMotors() keeps the motor commands in one function. Your kit's shield may have different pins or a different driver; use its own wiring guide before adapting the sketch.
const byte BUMPER = 2, STBY = 4;
const byte PWMA = 5, PWMB = 6;
const byte AIN1 = 7, AIN2 = 8, BIN1 = 9, BIN2 = 10;
enum State { DRIVE, BACK_UP, TURN };
State state = DRIVE;
unsigned long enteredAt = 0;
void motor(byte pwm, byte in1, byte in2, int speed) {
speed = constrain(speed, -255, 255);
digitalWrite(in1, speed > 0 ? HIGH : LOW);
digitalWrite(in2, speed < 0 ? HIGH : LOW);
analogWrite(pwm, abs(speed));
}
void setMotors(int left, int right) {
motor(PWMA, AIN1, AIN2, left);
motor(PWMB, BIN1, BIN2, right);
}
void setup() {
pinMode(BUMPER, INPUT_PULLUP);
const byte outputs[] = {STBY, PWMA, PWMB, AIN1, AIN2, BIN1, BIN2};
for (byte pin : outputs) pinMode(pin, OUTPUT);
digitalWrite(STBY, HIGH);
setMotors(0, 0);
}
void loop() {
unsigned long now = millis();
if (state == DRIVE) {
if (digitalRead(BUMPER) == LOW) {
state = BACK_UP;
enteredAt = now;
setMotors(-150, -150);
} else {
setMotors(160, 160);
}
} else if (state == BACK_UP && now - enteredAt >= 450) {
state = TURN;
enteredAt = now;
setMotors(150, -150);
} else if (state == TURN && now - enteredAt >= 500) {
state = DRIVE;
setMotors(160, 160);
}
} Improve and explain: Mark each test on your state diagram, including the bumper event and both timer events. Change one timing or speed value, predict what will happen, and test again. On your student page, include the diagram, the relevant code, a photo or short video, and what your test data made you change.
Quick check
Test your vocabulary
1. Which data type should store 21.5°C?
2. What range does analogRead() return on an Uno?
3. What does map(value, 0, 1023, 0, 255) do?
4. In int scaleReading(int raw) { … }, what is raw?
5. What does #include <Servo.h> do?