Arduino Programming

Arduino programming involves writing code to control an Arduino board. The code is written in the Arduino Integrated Development Environment (IDE) using a simplified version of C++.


Structure of an Arduino Program

void setup() {
  // put your setup code here, to run once:
}

void loop() {
  // put your main code here, to run repeatedly:
}
  • setup(): This function runs once when the Arduino is powered on or reset. It’s used to initialize variables, pin modes etc.

  • loop(): This function runs continuously after setup() and is used to actively control the Arduino board.


What is function in Arduino Program?

A function is a reusable block of code that performs a specific task.

In a function there is 5 parts

  • Function Name : The name identifies the function and is used to call it. It should be descriptive and follow the naming conventions.

  • Return Type : This specifies the type of value the function will return. If the function does not return any value, the return type is typically void.

  • Parameters (or Arguments) : These are the inputs to the function. Its allow to pass data into the function.

  • Function Definition : This is where the actual code of the function is written. It includes the function name, return type, parameters, and the body. The function body contains the block of code that performs the function’s task.

  • Function Call : This is how to use or invoke the function in program.


Function Creation Example

int add(int a, int b) {
    return a + b;
}

Function Calling Example

int result = add(5, 3);


Variables & Types

Variables are containers for storing data values. There is 5 types of variables

  • int : Stores integers (whole numbers), such as 123 or -123

  • double : Stores floating point numbers , such as 19.99 or -19.99

  • char : Stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes

  • string : Stores text, such as "Arduino Program". String values are surrounded by double quotes

  • bool : Stores values with two states: true or false


Variable Creation Syntax

type variableName = value;

Example

int myNum = 5;               // Integer (whole number without decimals)
double myFloatNum = 5.99;    // Floating point number (with decimals)
char myLetter = 'D';         // Character
string myText = "Hello";     // String (text)
bool myBoolean = true;       // Boolean (true or false)


Variable Naming Rules

  • Must start with a letter or an underscore (_)

  • Can contain letters, digits, and underscores

  • Case-sensitive (age and Age are different variables)

  • Cannot use reserved keywords (like int, float, if, etc.)


Variable Scope

  • Local Variables: Declared inside a function or block and only accessible within that function or block.

  • Global Variables: Declared outside of all functions and accessible from any function within the file.

int globalVar = 20; // Global variable

void myFunction() {
    int localVar = 10; // Local variable

    globalVar = 30; // Modify global variable
}


Operators & Conditional Statements

Conditional statements allow to control the flow of a program based on certain conditions.


Comparison Operator

  • Less than : a < b

  • Less than or equal to : a ⇐ b

  • Greater than : a > b

  • Greater than or equal to : a >= b

  • Equal to : a == b

  • Not Equal to : a != b


Conditional Statements

  • if statement : The if statement is used to execute a block of code if a specified condition is true.

  • if-else statement : The if-else statement executes one block of code if the condition is true, and another block if the condition is false.

  • else-if statement : The else-if statement allows to test multiple conditions.

  • break and continue statements : The break statement exits a loop or switch statement, while the continue statement skips the rest of the current loop iteration and moves to the next iteration.

  • switch statement : The switch statement is used to execute one of many blocks of code based on the value of a variable.

Example of if statement

int sensorValue = analogRead(A0);

if (sensorValue > 500) {
    digitalWrite(LED_BUILTIN, HIGH); // Turn the LED on
}

Example of if-else statement

int sensorValue = analogRead(A0);

if (sensorValue > 500) {
    digitalWrite(LED_BUILTIN, HIGH); // Turn the LED on
} else {
    digitalWrite(LED_BUILTIN, LOW); // Turn the LED off
}

Example of else-if statement

int sensorValue = analogRead(A0);

if (sensorValue > 800) {
    digitalWrite(LED_BUILTIN, HIGH); // Turn the LED on
} else if (sensorValue > 500) {
    digitalWrite(LED_BUILTIN, LOW);  // Turn the LED off
} else {
    // Do something else, like blinking the LED
    digitalWrite(LED_BUILTIN, HIGH);
    delay(100);
    digitalWrite(LED_BUILTIN, LOW);
    delay(100);
}

Example of switch statement

int buttonState = digitalRead(2);

switch (buttonState) {
    case HIGH:
        digitalWrite(LED_BUILTIN, HIGH); // Turn the LED on
        break;
    case LOW:
        digitalWrite(LED_BUILTIN, LOW); // Turn the LED off
        break;
    default:
        // Handle unexpected cases
        break;
}


Loop Statements

Loop statements in Arduino programming allow to execute a block of code multiple times. This is useful for tasks that require repetitive actions, such as reading sensor data, controlling actuators, or updating displays.


for Loop

The for loop is used to repeat a block of code a specified number of times. It consists of three parts: initialization, condition, and increment.

Syntax

for (initialization; condition; increment) {
    // Code to be executed
}

Example

    for (int i = 0; i < 10; i++) {
        digitalWrite(ledPin, HIGH);  // Turn the LED on
        delay(500);                  // Wait for 500 milliseconds
        digitalWrite(ledPin, LOW);   // Turn the LED off
        delay(500);                  // Wait for 500 milliseconds
    }


Digital I/O

Arduino board have a set of digital pins (0-13) that can be configured as either inputs or outputs.

void pinMode(int pin, int mode); // Define the mode of a pin.

int digitalRead(int pin); // Reads the state of a digital pin. Returns int (HIGH or LOW)

void digitalWrite(int pin, int state); // Writes a state to a digital pin. state are (HIGH or LOW)


Details of Digital I/O Pin

  • void pinMode(int pin, int mode) : Configures a digital pin as INPUT, OUTPUT, or INPUT_PULLUP.

    • mode :

      • INPUT (0) : Configures the pin as an input.

      • OUTPUT (1) : Configures the pin as an output.

      • INPUT_PULLUP (2) : Configures the pin as an input with an internal pull-up resistor enabled.


Analog I/O

Analog input (A0-A5) is used to read continuous values from sensors like potentiometers, temperature sensors, and light sensors.

int analogRead(int pin); // Reads the value of an analog pin in a 10-bit resolution (0-1023)

void analogWrite(int pin, int value); // Writes a value to a PWM supported pin in a 8-bit resolution (0-255).


Details of Analog I/O

  • void analogWrite(int pin, int value) :

    • pin : The PWM-capable pin (3, 5, 6, 9, 10, 11).

    • value : A value between 0 (always off) and 255 (always on).


Time

Time related functions are crucial for creating delays, measuring elapsed time, and scheduling tasks.

void delay(long milliseconds);  // Freezes program execution for specified number of milliseconds.

void delayMicroseconds(int microseconds); // Freezes program execution for specified number of microseconds.

long millis(); // Returns milliseconds passed since program start.

long micros(); // Returns microseconds passed since program start.


Serial Communication

Serial communication is a way for devices to exchange data. It involves sending data one bit at a time over a communication channel. Arduino uses serial communication to communicate with other devices, including computers, sensors, and other microcontrollers.

void begin(unsigned long baudrate); // Initializes the Serial communication with the specified baud rate.

// Example of serial begin
void setup() {
  Serial.begin(9600); // Start serial communication at 9600 baud
}

size_t print("Message"); // Send data to the serial port.
size_t println("Message"); // Send data to the serial port followed by a newline character.

int available(); // Returns the number of bytes available for reading.
int read(); // Reads byte from the serial buffer.
String readString(); // Read a string of characters until a newline character is received.
int parseInt(); // Read the incoming number


// Example of Send Data
void loop() {
  Serial.print("Hello, world!"); // Send data without a newline
  Serial.println("Hello, world!"); // Send data with a newline
  delay(1000); // Wait for a second
}


// Example of Data Reading
void loop() {
  if (Serial.available() > 0) { // Check if data is available to read
    String receivedString = Serial.readString(); // Read the incoming string
    Serial.print("You entered: ");
    Serial.println(receivedString); // Echo the received string
  }
}


Understanding Libraries

Libraries in Arduino are collections of code that make it easy to connect to a sensor, display, module, etc. Libraries provide extra functionality to your Arduino sketches.


Including Libraries

To use a library in sketch, need to include it at the beginning of the code. This is done using the #include directive.

#include <LibraryName.h>


#define

#define normally used for defining constants, creating inline functions, and simplifying code.

The basic syntax of #define is:

#define identifier value
  • identifier is the name of the macro.

  • value is the code or value that replaces the identifier wherever it appears in the code.


Examples

#define LED_PIN 13
#define SENSOR_PIN A0
#define THRESHOLD 500