Cheatsheets

linux, html or python: This section is my personal library of cheatsheets.


Linux

kurzer Text über den Fotos – aber nur als „Hook“

Priority Command / Flag What it does Typical example Useful flags / notes
Very often ssh Connects to another computer over the network and gives you its terminal. ssh name@host.local -p = use another port,
-i = use a key file
Very often ls Shows the files and folders in the current folder. ls -l = detailed list,
-a = show hidden files,
-h = human-readable sizes
Very often cd Changes to another folder. cd ~/bme280_logger cd .. = go one folder up,
cd ~ = go home,
cd - = go back to last folder
Very often pwd Shows where you are right now in the file system. pwd No common flags needed for beginners
Very often sudo Runs a command with administrator rights. You need it for important system changes. sudo apt update Use with care: it gives a command more power
Very often nano Opens a simple text editor in the terminal. nano test_bme280.py Ctrl+O = save,
Ctrl+X = exit
Very often clear Clears the terminal screen. clear Ctrl+L does nearly the same thing
Very often mkdir Creates a new folder. mkdir logs -p = also create parent folders if needed
Very often touch Creates an empty file. touch notes.txt Also updates the file time if the file already exists
Very often cp Copies a file or folder. cp test.py backup.py -r = copy folders too,
-v = show what is being copied
Very often mv Moves a file/folder or renames it. mv old.txt new.txt Same command for moving and renaming
Very often rm Deletes a file or folder. rm old.txt -r = delete folders too,
-f = force delete,
-i = ask before deleting
Very often cat Prints the content of a file to the terminal. cat config.txt Good for short files; bad for very long files
Very often tail Shows the last lines of a file. Very useful for logs. tail log.txt -f = keep watching for new lines live
Very often head Shows the first lines of a file. head log.txt Useful for quick checks
Very often python / python3 Runs a Python script. python3 test_bme280.py On Raspberry Pi,
python3 is usually the safe choice
Often apt update Downloads the newest package lists. It does not install updates yet. sudo apt update Usually run before upgrade or install
Often apt upgrade Installs available updates for installed software. sudo apt upgrade -y = answer “yes” automatically
Often apt full-upgrade Does a bigger system update and may replace or remove packages if needed. sudo apt full-upgrade -y Useful for full system maintenance
Often apt install Installs new software packages. sudo apt install -y i2c-tools -y = skip the confirmation question
Often apt remove Removes installed software packages. sudo apt remove package-name Removes software, but sometimes leaves config files behind
Often find Searches for files and folders. find . -name "*.py" . means “start here”
Often grep Searches for text inside files or command output. grep error log.txt -i = ignore upper/lower case,
-r = search inside folders too
Often less Opens a file for easy reading, one screen at a time. less long_log.txt Press q to quit
Often history Shows your previous commands. history Very useful when you forgot what you typed earlier
Often !! Runs the last command again. sudo !! Classic trick: rerun the last command with sudo
Often python3 -m venv .venv Creates a Python virtual environment for a project. python3 -m venv .venv Keeps project Python packages separate and tidy
Often source .venv/bin/activate Activates the virtual environment. source .venv/bin/activate After that, Python and pip use the virtual environment
Often jobs Shows programs running in the background in your current terminal. jobs Useful after starting a script with &
Often fg Brings a background job back to the front. fg Good if you want to stop it with Ctrl+C
Often & Starts a command in the background. python3 logger.py & The terminal stays usable after starting the program
Regularly reboot Restarts the Raspberry Pi. sudo reboot Useful after updates or config changes
Regularly shutdown Turns the Raspberry Pi off safely. sudo shutdown -h now -h = halt/power off,
-r = reboot
Regularly raspi-config Opens Raspberry Pi settings like SSH, I2C, SPI, hostname and more. sudo raspi-config Very important on Raspberry Pi systems
Regularly ip a Shows network information like IP addresses. ip a Good when you want to know how the Pi is connected
Regularly hostname Shows the computer name. hostname Useful for SSH and network setup
Regularly ping Tests whether another device or website can be reached over the network. ping raspberrypi.com Press Ctrl+C to stop it
Regularly i2cdetect -y 1 Scans the I2C bus and shows connected I2C devices like the BME280. i2cdetect -y 1 Needs i2c-tools installed; on Raspberry Pi, bus 1 is the normal one
Regularly ps aux Shows running processes. ps aux Useful when you want to find a running script
Regularly top Shows live system activity like CPU, memory and running processes. top Press q to quit
Regularly htop A friendlier and clearer version of top. htop May need installation first: sudo apt install htop
Sometimes kill Stops a running process by its process ID. kill 1234 -9 = force stop; use only if normal stop fails
Sometimes man Shows the manual page for a command. man ls Good when you want the official explanation
Sometimes --help Shows a short help text for many commands. ls --help Faster than reading the full manual page
Sometimes Ctrl+C Stops the currently running command. python3 logger.py then press Ctrl+C Extremely important in daily terminal use
Sometimes TAB Auto-completes file names and commands. Type cd Doc and press TAB Saves time and avoids typing mistakes
Sometimes Arrow Up Shows your previous command in the terminal. Press Perfect for repeating or editing old commands
Important flags -r Recursive. Usually means “also go through folders and everything inside them”. cp -r myfolder backup/ Common with cp,
rm,
grep
Important flags -f Force. Do it without asking, even if it may be risky. rm -f file.txt Dangerous with delete commands
Important flags -y Automatically answer “yes” to questions. sudo apt install -y i2c-tools Useful in package management
Important flags -i Interactive. Usually asks before doing something risky. rm -i file.txt Good for safer deleting
Important flags -v Verbose. Shows more details about what the command is doing. cp -v a.txt b.txt Useful when learning
Important flags -h Human-readable. Shows file sizes in an easy form like KB, MB, GB. ls -lh Very handy when checking file sizes
Important flags -a Shows all files, including hidden ones. ls -a Hidden files often start with a dot, like .bashrc
Important flags -l Long format. Shows more details like permissions, owner and size. ls -l Often combined as ls -lah

Important beginner notes:

↑ top


HTML

HTML is the structural backbone of a webpage. It does not make things “pretty” by itself — it tells the browser what something is: a heading, a paragraph, a link, an image, a section, a form field.

This cheatsheet focuses on the HTML things you actually use all the time: document structure, text elements, links, images, lists, semantic layout, forms, metadata and a few common traps.


Document basics

Basic document structure

Use: The minimum clean HTML skeleton for a normal page.

<!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>My page</title>
    </head>
    <body>
      ...
    </body>
    </html>

Use this as the default starting point for every new HTML file.

<head> vs <body>

Head: invisible page metadata, title, CSS, SEO.

Body: everything visible on the page.

<head>
      <title>Cheatsheets</title>
    </head>

    <body>
      <h1>Hello</h1>
    </body>

Attributes

Attributes add extra information to an element, for example href, src, alt, class or id.

<a href="about.html" class="button">About</a>

Text & structure

Headings: h1 to h6

Use: Page and section structure.

<h1>Main page title</h1>
    <h2>Section title</h2>
    <h3>Subsection title</h3>

Use headings for structure, not just because they look big.

Paragraph: p

Use: Normal blocks of text.

<p>This is a paragraph of text.</p>

Emphasis: strong and em

Use: Meaningful emphasis, not just decoration.

<p>This is <strong>important</strong> and this is <em>emphasized</em>.</p>

Line break and rule: br, hr

Use: Small structural helpers.

<p>Line one<br>Line two</p>

    <hr>

Do not use <br> as a lazy substitute for CSS spacing.


Link: a

Use: Navigation to pages, sections or external websites.

<a href="about.html">About me</a>

External link in new tab

<a 
      href="https://example.com" 
      target="_blank" 
      rel="noopener noreferrer">
      External page
    </a>

Jump link with id

<a href="#contact">Go to contact</a>

    <section id="contact">
      <h2>Contact</h2>
    </section>

Image: img

Use: Photos, graphics, illustrations.

<img 
      src="images/boat.jpg" 
      alt="Small sailing boat in calm evening light">

The alt text matters. “image” is useless. Describe what is actually there.

figure and figcaption

<figure>
      <img src="drone.jpg" alt="Drone on a field">
      <figcaption>First outdoor drone test.</figcaption>
    </figure>

Lists & grouping

Unordered list: ul

<ul>
      <li>HTML</li>
      <li>CSS</li>
      <li>JavaScript</li>
    </ul>

Ordered list: ol

<ol>
      <li>Create file</li>
      <li>Add structure</li>
      <li>Open in browser</li>
    </ol>

div

Use: Neutral block container for grouping content.

<div class="card">
      <h2>News</h2>
      <p>Today I learned HTML.</p>
    </div>

span

Use: Neutral inline wrapper inside text.

<p>This is <span class="highlight">highlighted</span> text.</p>

class vs id

class: reusable group name.

id: unique identifier on the page.

<h2 class="section-title">Projects</h2>
    <section id="about">...</section>

Semantic layout

Semantic page structure

These elements describe the role of a block. Much better than endless anonymous div soup.

<header>...</header>
    <nav>...</nav>
    <main>...</main>
    <section>...</section>
    <article>...</article>
    <footer>...</footer>

Example semantic layout

<header>
      <h1>My website</h1>
      <nav>
        <a href="#about">About</a>
        <a href="#projects">Projects</a>
      </nav>
    </header>

    <main>
      <section id="about">
        <h2>About</h2>
        <p>Some text.</p>
      </section>

      <article>
        <h2>Latest post</h2>
        <p>New entry here.</p>
      </article>
    </main>

    <footer>
      <p>© 2026 Julian</p>
    </footer>

Forms

Basic form

<form action="/send" method="post">
      <label for="name">Name</label>
      <input type="text" id="name" name="name">

      <label for="message">Message</label>
      <textarea id="message" name="message"></textarea>

      <button type="submit">Send</button>
    </form>

Always connect label for="..." with the matching input id.

Common input types

<input type="text">
    <input type="email">
    <input type="password">
    <input type="checkbox">
    <input type="radio">
    <input type="file">

Buttons

<button type="button">Click</button>
    <button type="submit">Submit</button>
    <button type="reset">Reset</button>

Head & metadata

Character encoding

<meta charset="UTF-8" />

Without this, umlauts and special characters may break.

Responsive viewport

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

Without this, mobile layout may look completely wrong.

CSS, JS and favicon

<link rel="stylesheet" href="style.css">
    <link rel="icon" href="favicon.ico">
    <script src="script.js" defer></script>

Meta description

<meta 
      name="description" 
      content="Personal website about electronics, sailing and projects." 
    />

Practical rules

↑ top


CSS

CSS gives structure its visual form. HTML says what something is; CSS decides how it looks, how much space it gets, how it behaves on small screens and how elements interact visually.

This cheatsheet focuses on the CSS things you actually use all the time on real websites: selectors, box model, spacing, colors, typography, layout, responsive design, hover states and a few traps that waste absurd amounts of time.


Basic rule structure

Basic CSS syntax

Use: Every CSS rule has a selector and one or more declarations.

.card {
      background: white;
      border: 1px solid #ddd;
      padding: 1rem;
    }

Selector = what to target. Property = what to change. Value = how to change it.

How CSS connects to HTML

<div class="card">Hello</div>
.card {
      padding: 1rem;
      background: #fff;
    }

HTML provides the hook. CSS styles the hook.

Comments

/* This is a CSS comment */
    .card-title {
      font-size: 1.2rem;
    }

Use comments for structure, not for writing a tragic novel into your stylesheet.


Selectors

Element selector

p {
      line-height: 1.6;
    }

Targets all <p> elements.

Class selector

.card {
      border-radius: 16px;
    }

Targets all elements with class="card".

ID selector

#top {
      scroll-margin-top: 1rem;
    }

Targets one unique element with that ID.

Descendant selector

.card p {
      margin-bottom: 1rem;
    }

Targets paragraphs inside .card.

Multiple selectors

h1, h2, h3 {
      line-height: 1.25;
    }

Same rule for several elements.

Pseudo-classes

a:hover {
      text-decoration: underline;
    }

    a:focus-visible {
      outline: 2px solid rgba(11, 95, 255, 0.45);
    }

Useful for hover, keyboard focus, active states and more.


Box model

The box model

Every element is basically a box made of:

  • content
  • padding = inner space
  • border = visible edge
  • margin = outer space
.box {
      margin: 1rem;
      padding: 1rem;
      border: 1px solid #ccc;
    }

box-sizing: border-box

*,
    *::before,
    *::after {
      box-sizing: border-box;
    }

This is one of the least glamorous and most useful lines in modern CSS.

Margin vs padding

.card {
      padding: 1.25rem;   /* inside */
      margin: 1rem 0;     /* outside */
    }

Padding creates breathing room inside. Margin separates elements from each other.


Spacing & sizing

Common spacing values

.section {
      margin: 2rem 0;
      padding: 1rem 1.25rem;
    }

Very often you only need margin, padding and a bit of restraint.

Width and height

.content {
      max-width: 980px;
      width: 100%;
    }

    .hero {
      min-height: 160px;
    }

max-width is usually better than fixed width for content areas.

Useful units

  • px = fixed pixels
  • rem = relative to root font size
  • % = relative to parent
  • vw / vh = viewport width / height
  • fr = fractional grid space
  • ch = character width approximation
.hero-quote {
      max-width: 42ch;
      font-size: 1.35rem;
    }

Shorthand spacing

margin: 1rem;          /* all sides */
    margin: 1rem 2rem;     /* top/bottom | left/right */
    margin: 1rem 2rem 3rem;/* top | left/right | bottom */
    margin: 1rem 2rem 3rem 4rem; /* top | right | bottom | left */

Text & fonts

Font basics

body {
      font-family: system-ui, -apple-system, "Segoe UI", Roboto, Arial, sans-serif;
      font-size: 1rem;
      line-height: 1.6;
    }

Good typography is half the website. The other half is not ruining it.

Common text properties

.site-title {
      font-size: 1.4rem;
      font-weight: 700;
      letter-spacing: 0.2px;
      text-align: left;
    }

Muted text

.hint,
    .card-meta {
      color: var(--muted);
      font-size: 0.95rem;
    }

Muted text is for secondary information, not for making everything look tired.

Text decoration

a {
      text-decoration: underline;
      text-underline-offset: 3px;
      text-decoration-thickness: 1px;
    }

Colors & backgrounds

Text and background colors

body {
      color: #1f2328;
      background: #f7f7f7;
    }

Border and radius

.card {
      border: 1px solid #e5e7eb;
      border-radius: 16px;
    }

RGBA transparency

.overlay {
      background: rgba(0, 0, 0, 0.35);
    }

Useful for overlays, subtle borders and layered backgrounds.

Background images

.hero {
      background: url("../img/photo.jpg") center / cover no-repeat;
    }

center / cover no-repeat is a classic trio for full-area background images.


Display & positioning

display

.thing {
      display: block;
    }
  • block = takes full width
  • inline = stays inside text flow
  • inline-block = inline but sizeable
  • flex = flexible row/column layout
  • grid = grid layout
  • none = hidden

Positioning

.parent {
      position: relative;
    }

    .child {
      position: absolute;
      top: 0;
      right: 0;
    }

relative creates a positioning context. absolute places something precisely inside it.

inset: 0

.overlay {
      position: absolute;
      inset: 0;
    }

Elegant shorthand for top/right/bottom/left = 0.

z-index

.background {
      z-index: -1;
    }

    .overlay {
      z-index: 2;
    }

Controls stacking order. Only useful on positioned elements.


Flexbox & grid

Flexbox row layout

.header-inner {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      gap: 1rem;
    }

Use flex for one-dimensional layouts: row or column.

Flex wrap

.top-nav {
      display: flex;
      gap: 0.9rem;
      flex-wrap: wrap;
    }

Very handy when items should wrap instead of colliding like drunken shopping carts.

Grid layout

.tile-grid {
      display: grid;
      gap: 1rem;
      grid-template-columns: repeat(3, minmax(0, 1fr));
    }

Use grid for two-dimensional layouts with rows and columns.

Centering with grid

.hero {
      display: grid;
      place-items: center;
    }

Ridiculously convenient for centering content both horizontally and vertically.


Basic link styling

a {
      color: var(--text);
      text-decoration: underline;
    }

Hover state

a:hover {
      text-decoration-color: currentColor;
    }

Hover gives feedback. Overdo it and the page starts performing circus tricks.

Focus-visible

a:focus-visible {
      outline: 2px solid rgba(11, 95, 255, 0.45);
      outline-offset: 2px;
    }

Keyboard users exist. Design accordingly.

Transitions

.tile-image {
      transition: transform 180ms ease;
    }

    .tile:hover .tile-image {
      transform: scale(1.06);
    }

Use transitions sparingly. A website is not a casino machine.


Responsive design

Media query

@media (max-width: 900px) {
      .tile-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
      }
    }

Use media queries when layout must adapt to smaller screens.

Mobile stacking

@media (max-width: 560px) {
      .header-inner {
        flex-direction: column;
        align-items: flex-start;
      }

      .tile-grid {
        grid-template-columns: 1fr;
      }
    }

Responsive images

img {
      max-width: 100%;
      height: auto;
      display: block;
    }

This prevents images from exploding out of their containers like idiots.

Viewport meta tag reminder

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Responsive CSS without this meta tag is often dead on arrival.


Variables

Define variables in :root

:root {
      --bg: #f7f7f7;
      --surface: #ffffff;
      --text: #1f2328;
      --muted: #6b7280;
      --border: #e5e7eb;
      --radius: 16px;
    }

Very useful for consistent colors, spacing and theme changes.

Use variables with var()

body {
      color: var(--text);
      background: var(--bg);
    }

    .card {
      background: var(--surface);
      border-radius: var(--radius);
    }

Calculated values

.media-placeholder {
      border-radius: calc(var(--radius) - 4px);
    }

calc() lets values relate to each other instead of drifting into random numerology.


Practical rules

↑ top


Python

Python is a general-purpose language with a clean syntax and a low barrier to entry. It is excellent for automation, scripting, data handling, small tools, quick experiments and hardware-related projects.

This cheatsheet focuses on the Python things you actually use all the time: variables, data types, conditions, loops, functions, files, modules, virtual environments and a few common traps.


Basics

Hello world

print("Hello, world!")

Use: Prints text to the console.

Variables

name = "Julian"
    age = 28
    temperature = 21.5
    is_online = True

Python variables do not need explicit type declarations.

Comments

# This is a comment

    """
    This is a multi-line docstring
    or documentation string.
    """

Use comments for explanations, not for narrating every line like a bad sports commentator.

Indentation matters

if True:
        print("Indented correctly")

    print("Outside the block")

In Python, indentation is not decoration. It defines the structure.


Data types

Common data types

text = "hello"      # str
    number = 42         # int
    pi = 3.1415         # float
    active = True       # bool
    nothing = None      # NoneType

Check a type

value = 42
    print(type(value))

Useful when you are not sure what you are actually handling.

Convert between types

age_text = "28"
    age_number = int(age_text)

    temperature = "21.5"
    temperature_number = float(temperature)

    number = 42
    text = str(number)

Strings

Basic string operations

name = "Julian"

    print(name.lower())
    print(name.upper())
    print(len(name))
    print(name[0])

f-strings

name = "Julian"
    age = 28

    print(f"My name is {name} and I am {age} years old.")

This is usually the cleanest way to build readable output strings.

Useful string methods

text = "  Hello World  "

    print(text.strip())         # remove outer spaces
    print(text.replace("World", "Python"))
    print(text.startswith("  He"))
    print(text.endswith("  "))
    print(text.split())

Multi-line strings

message = """Line one
    Line two
    Line three"""

    print(message)

Conditions

if, elif, else

temperature = 18

    if temperature > 25:
        print("Warm")
    elif temperature > 15:
        print("Mild")
    else:
        print("Cold")

Comparison operators

x == 10   # equal
    x != 10   # not equal
    x > 10
    x < 10
    x >= 10
    x <= 10

Logical operators

if age >= 18 and country == "AT":
        print("Allowed")

    if is_admin or is_editor:
        print("Can edit")

    if not active:
        print("Inactive")

Truthy and falsy values

if []:
        print("List has content")

    if not []:
        print("List is empty")

Empty strings, empty lists, zero and None are treated as false.


Loops

for loop

for i in range(5):
        print(i)

Prints 0 to 4.

Loop through a list

colors = ["red", "green", "blue"]

    for color in colors:
        print(color)

while loop

count = 0

    while count < 3:
        print(count)
        count += 1

Useful, but easy to abuse into infinite nonsense if you forget to update the condition.

break and continue

for i in range(10):
        if i == 3:
            continue
        if i == 7:
            break
        print(i)

continue skips one iteration, break stops the loop completely.

enumerate()

items = ["a", "b", "c"]

    for index, item in enumerate(items):
        print(index, item)

Very useful when you need both index and value.


Functions

Basic function

def greet(name):
        print(f"Hello, {name}!")

    greet("Julian")

Return values

def add(a, b):
        return a + b

    result = add(3, 4)
    print(result)

return gives a value back to the caller.

Default arguments

def greet(name="world"):
        print(f"Hello, {name}!")

    greet()
    greet("Julian")

Keyword arguments

def describe(name, age):
        print(f"{name} is {age} years old.")

    describe(age=28, name="Julian")

Lists, tuples, dicts, sets

Lists

colors = ["red", "green", "blue"]

    colors.append("yellow")
    colors.remove("green")
    print(colors[0])
    print(len(colors))

Lists are ordered and mutable.

Tuples

point = (10, 20)
    print(point[0])

Tuples are ordered but immutable.

Dictionaries

person = {
        "name": "Julian",
        "age": 28,
        "city": "Graz"
    }

    print(person["name"])
    print(person.get("age"))

Dictionaries store key-value pairs.

Sets

numbers = {1, 2, 3, 3}
    print(numbers)

Sets contain unique values only.

List comprehensions

squares = [x * x for x in range(5)]
    print(squares)

Compact and powerful, though beginners should not turn every line into cryptic wizardry.


Files

Read a file

with open("notes.txt", "r", encoding="utf-8") as file:
        content = file.read()

    print(content)

with open(...) is the standard clean pattern.

Write a file

with open("output.txt", "w", encoding="utf-8") as file:
        file.write("Hello, file!")

"w" overwrites the file if it already exists.

Append to a file

with open("log.txt", "a", encoding="utf-8") as file:
        file.write("New line\n")

"a" adds content at the end instead of replacing the file.

Read line by line

with open("data.txt", "r", encoding="utf-8") as file:
        for line in file:
            print(line.strip())

Errors & exceptions

Basic try / except

try:
        number = int("abc")
    except ValueError:
        print("That was not a valid integer.")

else and finally

try:
        value = int("42")
    except ValueError:
        print("Invalid")
    else:
        print("Success:", value)
    finally:
        print("This always runs")

Raise your own error

age = -1

    if age < 0:
        raise ValueError("Age cannot be negative")

Modules & imports

Import a module

import math

    print(math.sqrt(16))

Import specific things

from math import sqrt

    print(sqrt(25))

Common useful modules

import os
    import sys
    import json
    import csv
    import pathlib
    import datetime

These are everyday tools for files, paths, data, dates and system interaction.

Main guard

def main():
        print("Program starts here")

    if __name__ == "__main__":
        main()

Useful so code only runs when the file is executed directly.


Virtual environments

Create a virtual environment

python3 -m venv .venv

Creates an isolated Python environment for a project.

Activate it on Linux / Raspberry Pi

source .venv/bin/activate

Install packages

pip install requests

Usually do this after activating the virtual environment.

Freeze dependencies

pip freeze > requirements.txt

Install from requirements

pip install -r requirements.txt

Deactivate

deactivate

Practical rules

↑ top


Arduino

Arduino is a beginner-friendly microcontroller platform for reading sensors, controlling outputs and building small interactive hardware projects. It combines simple hardware access with a lightweight C/C++-style programming model.

This cheatsheet focuses on the Arduino things you actually use all the time: sketch structure, variables, pins, digital and analog I/O, timing, serial monitor, functions, libraries and a few common traps.


Basics

Basic sketch structure

void setup() {
      // runs once at startup
    }

    void loop() {
      // runs again and again
    }

setup() runs once. loop() runs forever until power is removed or the board is reset.

Hello world on Serial

void setup() {
      Serial.begin(9600);
      Serial.println("Hello, Arduino!");
    }

    void loop() {
    }

A classic first test. If this does not work, something basic is wrong: board, port, cable or baud rate.

Comments

// Single-line comment

    /*
      Multi-line comment
    */

Use comments to explain intent, not to narrate every obvious line like a village herald.

Semicolon matters

int ledPin = 13;   // correct
    int ledPin = 13    // wrong

Unlike Python, Arduino/C++ wants semicolons. Forget them and the compiler sulks immediately.


Variables & data types

Common data types

int sensorValue = 0;
    float temperature = 21.5;
    bool ledState = true;
    char letter = 'A';

These are the types you will meet constantly in small Arduino projects.

Useful integer types

byte smallValue = 255;
    unsigned long currentTime = 0;

unsigned long is especially important for timing with millis().

const for fixed values

const int ledPin = 13;
    const int buttonPin = 2;

Use const for pin numbers and fixed settings. It keeps the code clearer and safer.

Global vs local variables

int counter = 0;   // global

    void loop() {
      int localValue = 5;  // local
      counter++;
    }

Global variables are visible everywhere. Local variables only exist inside their function or block.


Pins & pin modes

pinMode()

void setup() {
      pinMode(13, OUTPUT);
      pinMode(2, INPUT);
    }

Before using a pin, tell the microcontroller what role it should play.

Common pin modes

pinMode(13, OUTPUT);
    pinMode(2, INPUT);
    pinMode(3, INPUT_PULLUP);
  • OUTPUT = drives LED, relay, etc.
  • INPUT = reads an external signal
  • INPUT_PULLUP = input with internal pull-up resistor

Why INPUT_PULLUP matters

pinMode(3, INPUT_PULLUP);

Very useful for buttons. It avoids floating input chaos and saves an external resistor in many cases.


Digital input & output

Turn an LED on and off

const int ledPin = 13;

    void setup() {
      pinMode(ledPin, OUTPUT);
    }

    void loop() {
      digitalWrite(ledPin, HIGH);
      delay(1000);
      digitalWrite(ledPin, LOW);
      delay(1000);
    }

HIGH usually means on, LOW means off.

Read a button

const int buttonPin = 2;

    void setup() {
      pinMode(buttonPin, INPUT_PULLUP);
      Serial.begin(9600);
    }

    void loop() {
      int state = digitalRead(buttonPin);
      Serial.println(state);
    }

With INPUT_PULLUP, a pressed button often reads LOW, not HIGH. Slightly perverse, but normal.

React to a button press

const int buttonPin = 2;
    const int ledPin = 13;

    void setup() {
      pinMode(buttonPin, INPUT_PULLUP);
      pinMode(ledPin, OUTPUT);
    }

    void loop() {
      if (digitalRead(buttonPin) == LOW) {
        digitalWrite(ledPin, HIGH);
      } else {
        digitalWrite(ledPin, LOW);
      }
    }

Analog input & PWM output

Read an analog value

int sensorValue = 0;

    void setup() {
      Serial.begin(9600);
    }

    void loop() {
      sensorValue = analogRead(A0);
      Serial.println(sensorValue);
      delay(500);
    }

On many Arduino boards, analogRead() returns values from 0 to 1023.

PWM output with analogWrite()

const int ledPin = 9;

    void setup() {
      pinMode(ledPin, OUTPUT);
    }

    void loop() {
      analogWrite(ledPin, 128);
    }

On classic Arduino boards, PWM values usually go from 0 to 255.

Map one range to another

int sensorValue = analogRead(A0);
    int brightness = map(sensorValue, 0, 1023, 0, 255);

    analogWrite(9, brightness);

map() is useful when sensor ranges and output ranges do not match.

constrain()

int value = 300;
    value = constrain(value, 0, 255);

Keeps a value inside a defined range.


Serial monitor

Start Serial communication

void setup() {
      Serial.begin(9600);
    }

The baud rate in the Serial Monitor must match this value.

Serial.print() vs Serial.println()

Serial.print("Value: ");
    Serial.println(42);

print() stays on the same line. println() adds a line break.

Print several values clearly

int temp = 23;
    int humidity = 55;

    Serial.print("Temp: ");
    Serial.print(temp);
    Serial.print(" C, Humidity: ");
    Serial.print(humidity);
    Serial.println(" %");

Serial for debugging

Serial.println("Reached setup()");
    Serial.println(sensorValue);

Serial output is one of the most useful debugging tools in Arduino land. Primitive, but gold.


Timing

delay()

delay(1000);

Pauses the program for 1000 milliseconds = 1 second.

Blink without delay using millis()

const int ledPin = 13;
    unsigned long previousMillis = 0;
    const unsigned long interval = 1000;
    bool ledState = false;

    void setup() {
      pinMode(ledPin, OUTPUT);
    }

    void loop() {
      unsigned long currentMillis = millis();

      if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;
        ledState = !ledState;
        digitalWrite(ledPin, ledState);
      }
    }

This is the classic non-blocking timing pattern. Very important once projects get even mildly serious.

millis() basics

unsigned long now = millis();

Returns the number of milliseconds since the board started running.

micros()

unsigned long t = micros();

Like millis(), but in microseconds. Useful for faster timing needs.


Conditions & logic

if, else

int value = analogRead(A0);

    if (value > 500) {
      Serial.println("High");
    } else {
      Serial.println("Low");
    }

Comparison operators

x == 10
    x != 10
    x > 10
    x < 10
    x >= 10
    x <= 10

Logical operators

if (temp > 20 && humidity < 70) {
  Serial.println("Comfortable");
}

if (buttonPressed || sensorTriggered) {
  Serial.println("Action");
}

if (!enabled) {
  Serial.println("Disabled");
}

Loops & iteration

for loop

for (int i = 0; i < 5; i++) {
  Serial.println(i);
}

Useful for repeated actions, arrays and test output.

while loop

int x = 0;

while (x < 3) {
  Serial.println(x);
  x++;
}

Works fine, but be careful: a bad while loop can lock your program into stupidity.

Loop over an array

int values[] = {10, 20, 30, 40};

for (int i = 0; i < 4; i++) {
  Serial.println(values[i]);
}

Functions

Basic function

void blinkOnce() {
  digitalWrite(13, HIGH);
  delay(200);
  digitalWrite(13, LOW);
}

Functions help split code into reusable, readable chunks.

Function with parameters

void blinkLed(int pin, int duration) {
  digitalWrite(pin, HIGH);
  delay(duration);
  digitalWrite(pin, LOW);
}

Function with return value

int readSensor() {
  return analogRead(A0);
}

Using a function

void loop() {
  int value = readSensor();
  Serial.println(value);
  delay(500);
}

Libraries

Include a library

#include <Wire.h>

Libraries add functionality for sensors, displays, communication and more.

Typical pattern with an object

#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
  lcd.init();
  lcd.backlight();
  lcd.print("Hello");
}

void loop() {
}

Many Arduino libraries create an object first, then you call methods on it.

Common built-in or standard libraries

#include <Wire.h>     // I2C
#include <SPI.h>      // SPI
#include <EEPROM.h>   // EEPROM
#include <Servo.h>    // Servo motors

I2C basics with Wire

#include <Wire.h>

void setup() {
  Wire.begin();
}

void loop() {
}

Very common for sensors like BME280, displays and RTC modules.


Practical rules

↑ top


↑ top⌂ home