> For the complete documentation index, see [llms.txt](https://monasheng.gitbook.io/zerotohero/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://monasheng.gitbook.io/zerotohero/arduino-zero-to-hero/arduino-programming/arduino-c.md).

# Arduino C

{% embed url="<https://youtu.be/0I8kjwwsVbw>" %}

## File Structure

In Arduino, you create programs as text-files containing C code, called *sketches*. Arduino sketches have the extension `.ino` and live in a folder that has the same name as the sketch.

{% hint style="info" %}
:man\_mage: **Important:** This file structure is automatically created and handled by the Arduino IDE when you make a new sketch and click `File -> Save as...`
{% endhint %}

<figure><img src="/files/A1lS69SXFl1t1W9zL4HZ" alt=""><figcaption><p>When you save a sketch with the Arduino IDE, it creates a parent folder to house the <code>.ino</code> file.</p></figcaption></figure>

While you can edit Arduino `.ino` files in any text editor (e.g. notepad, notepad++, VS Code), beginners should try to work within the Arduino IDE as much as possible.

## Code Structure

Within an Arduino sketch, code is typically structured into 4 sections, which should appear in the sketch following order:

1. a [#preamble](#preamble "mention"), which contains a [#title-block](#title-block "mention"), any [#library-inclusions](#library-inclusions "mention"), declarations of [#global-variables](#global-variables "mention"), and [#definitions](#definitions "mention"),
2. a [#setup-function](#setup-function "mention"), which contains any code that should run only once upon boot-up of the Arduino,
3. a [#loop-function](#loop-function "mention"), which contains any code that should run in a continuous loop, so long as the Arduino remains powered, and,
4. any other user function definitions, which may be invoked in either the [#setup-function](#setup-function "mention") or [#loop-function](#loop-function "mention").

This order is also how the Arduino executes the code:

<figure><img src="/files/Tu5LskMPX4rjKoAXBJ24" alt=""><figcaption><p>Arduino code execution flowchart. Note that calls to user functions can be made within <code>setup()</code> or <code>loop()</code>, but these are not automatically executed unless called.</p></figcaption></figure>

It can be helpful to physically structure your code in this order, using comments to break it up for readability. For instance:

{% code overflow="wrap" fullWidth="false" %}

```arduino
/* Preamble ---------------------------------------------- */
//...

/* setup() (runs once) ----------------------------------- */
void setup() {
//...
}

/* loop() (runs continuously) ---------------------------- */
void loop() {
//...
}

/* User Function Definitions ----------------------------- */
//...

```

{% endcode %}

### Preamble

Any code outside and above the [#setup-function](#setup-function "mention") is generally referred to as the *preamble*. This code is executed before `setup()`, and typically includes anything that needs to persist across multiple functions/variable scopes.

#### Title Block

You should include a *title block* at the start of your [#preamble](#preamble "mention"). This block should (at least) communicate what the sketch does, who the author is, and when it was last modified.

```arduino
/* Preamble ---------------------------------------------- */

// Sketch Title: myFirstSketch
//  Author: Alex Gregg
//  Last Modified: May 21, 2024
//  Description: This sketch calculates the square root of pi
```

#### Definitions

[C Refresher/OnRamp](/zerotohero/arduino-zero-to-hero/arduino-programming/c-refresher-onramp.md#constant-definitions) also take place in the preamble, usually immediately after the title block.

{% code overflow="wrap" %}

```arduino
/* Preamble ---------------------------------------------- */

// Sketch Title: myFirstSketch
//  Author: Alex Gregg
//  Last Modified: May 21, 2024
//  Description: This sketch calculates area of a circle

#define CONST_PI 3.14159 // Define Pi to 5 d.p.
```

{% endcode %}

#### Library Inclusions

The preamble also houses any calls to include [C Refresher/OnRamp](/zerotohero/arduino-zero-to-hero/arduino-programming/c-refresher-onramp.md#off-the-shelf-libraries), via the `#include` function, usually at the very top of the sketch.&#x20;

```arduino
/* Preamble ---------------------------------------------- */

// Sketch Title: myFirstSketch
//  Author: Alex Gregg
//  Last Modified: May 21, 2024
//  Description: This sketch calculates area of a circle

#define CONST_PI 3.14159 // Define Pi to 5 d.p.

#include <math.h> // Include the math library (for the square - sq() function)
```

#### Global Variables

Ordinarily, variables can only be seen/modified by the function in which they are declared.&#x20;

It is possible however to make variables visible to all functions by declaring and/or initialising them in the preamble. Such variables are called *global*.

{% code overflow="wrap" %}

```arduino
/* Preamble ---------------------------------------------- */

// Sketch Title: myFirstSketch
//  Author: Alex Gregg
//  Last Modified: May 21, 2024
//  Description: This sketch calculates area of a circle

#define CONST_PI 3.14159 // Define Pi to 5 d.p.

#include <math.h> // Include the math library (for the square - sq() function)

int firstRadius = 1; // This is a global variable, and can be seen by every function

/* setup() (runs once) ----------------------------------- */
void setup() {
  int secondRadius = 2; // This is a local variable, and can only be seen by setup()
  Serial.begin(9600); // Initialize serial communication
  
  Serial.print(CONST_PI * sq(firstRadius)); // Works because firstRadius is global
  Serial.print(CONST_PI * sq(secondRadius)); // Works because secondRadius is defined in setup() and this call is also in setup()
}

/* loop() (runs continuously) ---------------------------- */
void loop() {
  int thirdRadius = 3; // This is a local variable, and can only be seen by loop()
  
  Serial.print(CONST_PI * sq(firstRadius)); // Works because firstRadius is global
  Serial.print(CONST_PI * sq(thirdRadius)); // Works because thirdRadius is defined in loop() and this call is also in loop()
  // Serial.print(CONST_PI*sq(secondRadius)); // WILL NOT WORK because secondRadius is defined in setup() and this call is in loop()
}

/* User Function Definitions ----------------------------- */
// N/A
```

{% endcode %}

Global variables can be extremely useful, reducing the need to pass information in/out of functions.&#x20;

They can also be quite dangerous - obfuscating/hiding where things might be initialised/changed/updated. Use these with caution!

### `setup()` Function

The `setup()` function appears immediately after the preamble, and is run *only once* upon boot-up of the MCU. In a `setup()` function, you would typically include:

1. Any initialisation of MCU pins as inputs/outputs via the `pinmode()` function,
2. Calls to initialise the [Serial Monitor](/zerotohero/arduino-zero-to-hero/core-skills/serial-monitor.md) via the `Serial.begin()` function, and,
3. Calls to initialise off-the-shelf libraries, e.g. to control servos, interact with sensors, etc.

{% embed url="<https://www.arduino.cc/reference/tr/language/structure/sketch/setup/>" %}

### `loop()` Function

The `loop()` function appears after `setup()`, and is run over and over again as long as the Arduino is powered.

You will write the majority of your sketch logic in the `loop()` function, as this constitutes the 'steady state' behaviour of the MCU.

Well-written, [Clean Code](/zerotohero/arduino-zero-to-hero/core-skills/clean-code.md) will use [Clean Code](/zerotohero/arduino-zero-to-hero/core-skills/clean-code.md#functional-programming) to maintain a small, readable, `loop()` function that consists mostly or only of calls to user functions, usually on some interval.&#x20;

{% embed url="<https://www.arduino.cc/reference/en/language/structure/sketch/loop/>" %}

### User Function Definitions

User function definitions are usually placed at the bottom of a sketch, after the `loop()` function. It can helpful to separate function definitions with comments for human-readability - see [Clean Code](/zerotohero/arduino-zero-to-hero/core-skills/clean-code.md)
