Arduino reads and executes code in a specific way, which involves several steps:
1. **Upload Code:**
- **Code Compilation:** When you write a program (called a sketch) in the Arduino IDE, the IDE first compiles the code. It translates the human-readable code into machine code that the Arduino microcontroller can understand. This process uses the GCC (GNU Compiler Collection) for C/C++.
- **Upload to Microcontroller:** The compiled code is then uploaded to the Arduino board via a serial connection (usually through a USB cable). The bootloader on the Arduino board receives the code and writes it to the microcontroller’s flash memory.
2. **Bootloader:**
- **Initialization:** When you reset the Arduino board or power it on, the bootloader runs first. Its primary job is to check if new code is being uploaded. If not, it then transfers control to the main program stored in the flash memory.
- **Program Execution:** The bootloader passes control to the user’s code, starting execution from the `setup()` function.
3. **Code Execution:**
- **Setup Function:** The `setup()` function is executed once when the Arduino is powered on or reset. It is typically used to initialize variables, pin modes, and start serial communication.
- **Loop Function:** After `setup()` has completed, the `loop()` function runs repeatedly. This is where the main logic of your program is executed. The `loop()` function keeps running in a cycle, allowing your code to continually check inputs and update outputs.
4. **Reading and Writing:**
- **Input Reading:** For tasks like reading sensors or user inputs, the Arduino uses built-in functions (like `analogRead()` or `digitalRead()`) that interact with the microcontroller’s input pins. The microcontroller converts these signals into digital values or processes them as needed.
- **Output Writing:** Similarly, to control output devices (such as LEDs, motors, etc.), Arduino uses functions like `analogWrite()` or `digitalWrite()` to set the state of the output pins.
5. **Libraries and Functions:**
- **Libraries:** Arduino sketches can use libraries that provide additional functions for interacting with hardware or performing complex tasks. These libraries are included at the beginning of the sketch with `#include` directives.
- **Functions:** Besides the `setup()` and `loop()` functions, you can define your own functions to modularize your code and make it more readable and maintainable.
In summary, Arduino reads and executes code by first compiling it into machine code, uploading it to the microcontroller, and then running it starting with the `setup()` function and continually executing the `loop()` function. This process involves interaction with the board’s hardware through predefined functions and libraries.