A Brief Introduction to Arduino Programming

Intro to Arduino Programming

Arduino programming uses a simplified version of C++, making it easy for beginners while still powerful for advanced projects. This tutorial covers the basics and key concepts to help you create functional code for your Arduino.

Key Components of Arduino Programming

1. The Structure of an Arduino Sketch

Arduino programs, or "sketches," follow a simple structure made up of two main functions:

  • setup() Function
    This function runs once at the start of the program. It is used to initialize settings, such as setting up pins.
void setup() {
    // Code here runs once
}
  • loop Function()
    This function runs repeatedly in a loop. It’s where the main logic of your program goes.
void loop() {
    // Code here runs repeatedly
}

2. Understanding Basic Arduino Commands

  • Pin Modes
    Tell the Arduino how to use its pins:
pinMode(pinNumber, INPUT); // Set a pin as an input
pinMode(pinNumber, OUTPUT); // Set a pin as an output
  • Digital Read and Write
    Control or read from digital pins:
digitalWrite(pinNumber, HIGH); // Set pin HIGH (on)
digitalWrite(pinNumber, LOW); // Set pin LOW (off)
  • Delays
    Pause the program for a specific amount of time:
delay(milliseconds);   // Wait for the specified time
//Note that the unit is milliseconds (one thousandth of a second). So, to get 3 seconds, we use 3000 in the delay() function.
  • Serial Communication
    Used to send and receive data to and from your computer:
Serial.begin(9600);   //Initialize Serial Monitor at 9600 baud
Serial.println("Message");   // Send a message to the Serial Monitor

3. Variables and Constants

  • Common Variable Types:
int number = 42; // Integer
float decimal = 3.14; // Floating-point number
char letter = 'A'; // Character
  • Constants:
    Use const to define values that do not change:
const int ledPin = 13; // LED connected to pin 13

4. Control Structures

  • Conditionals
    Perform actions based on conditions:
if (condition) {
        // Code to run if condition is true
} else {
        // Code to run if condition is false
}
  • Loops
    We use loops to repeat actions multiple times
for (int i = 0; i < 10; i++) {
       // Code runs 10 times
}
while (condition) {
       // Code runs while condition is true
}