Arduino Programming Basics
From Variables to Libraries
1. What is Arduino?
Arduino is a microcontroller platform that lets you read inputs (buttons, sensors) and control outputs
(LEDs, motors) using a simplified version of C/C++.
2. Variables
Variables store data used in your sketch.
int led = 13;
float temp = 23.5;
bool state = true;
char letter = 'A';
String name = "Ali";
3. Constants
Use constants when the value does not change.
const int BUTTON_PIN = 2;
#define LED_PIN 13
4. Data Types
Type Description Example
int Integer (-32,768 to 32,767) int x = 100;
float Decimal number float f = 2.3;
bool True or false bool b = true;
char Single ASCII character char c = ’A’;
String Sequence of characters String s = ”Hi”;
5. Input/Output Pins
pinMode(13, OUTPUT); // set pin 13 as output
digitalWrite(13, HIGH); // turn on LED
int val = digitalRead(2); // read digital input
int sensorVal = analogRead(A0); // analog input (0{1023)
1
6. Control Structures
If Statement
if (val > 100) {
digitalWrite(13, HIGH);
}
For Loop
for (int i = 0; i < 5; i++) {
Serial.println(i);
}
Switch Statement
switch(mode) {
case 1: doA(); break;
case 2: doB(); break;
}
7. Functions
void blinkLED() {
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);
}
8. Serial Communication
Serial.begin(9600); // start serial
Serial.println("Hello!"); // print to Serial Monitor
9. Arrays
int leds[] = {3, 5, 6};
for (int i = 0; i < 3; i++) {
digitalWrite(leds[i], HIGH);
delay(200);
}
10. Libraries
Libraries provide prewritten code for sensors, displays, and communication.
2
Installing
Use Sketch > Include Library > Manage Libraries in the Arduino IDE.
Example: DHT Sensor
#include <DHT.h>
DHT dht(2, DHT11);
void setup() {
dht.begin();
Serial.begin(9600);
}
void loop() {
float h = dht.readHumidity();
float t = dht.readTemperature();
Serial.print("Humidity: ");
Serial.print(h);
Serial.print("% Temp: ");
Serial.println(t);
delay(2000);
}
Popular Libraries
• DHT – Temperature and humidity sensors
• Servo – Control servo motors
• Wire – I2C communication
• LiquidCrystal – LCD displays
• SoftwareSerial – Additional serial ports
11. Useful Functions
Function Description
delay(ms) Wait for given milliseconds
millis() Time since program started
map(val, inMin, inMax, outMin, outMax) Map value range
constrain(x, a, b) Limit x between a and b
random(min, max) Generate random number
Next Steps
Try building:
• A traffic light system
• A temperature display with LCD
• Servo-controlled robotic arm