Arduino Programming Simplified
1. Introduction to Arduino
- Arduino is an open-source microcontroller platform.
- Popular board: Arduino Uno.
- Install Arduino IDE from arduino.cc
Arduino Uno Board Overview
- Digital Pins: 0-13
- Analog Pins: A0-A5
- Power Pins: 5V, 3.3V, GND
- USB port: Connect to computer
2. Basic Concepts
Variables and Data Types
int ledPin = 13; // integer variable for LED pin
float voltage = 5.0; // float variable
Setup and Loop Functions
void setup() {
pinMode(13, OUTPUT); // configure pin 13 as output
}
void loop() {
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}
3. Digital I/O
Commands
- pinMode(pin, OUTPUT/INPUT)
- digitalWrite(pin, HIGH/LOW)
- digitalRead(pin)
Example: Blink LED
void setup() {
pinMode(13, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);
}
4. Using for Loop
Syntax
for(initialization; condition; increment) {
// code to repeat
}
Example: Blink LED 5 Times
for(int i = 0; i < 5; i++){
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);
}
5. Using while Loop
Syntax
while(condition) {
// code to repeat while condition is true
}
Example: Blink LED Until Button Pressed
int buttonPin = 2;
int ledPin = 13;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
while(digitalRead(buttonPin) == LOW){
digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW);
delay(500);
}
}
6. Using if Statement
Syntax
if(condition) {
// code if true
} else {
// code if false
}
Example: Turn on LED if Button Pressed
if(digitalRead(buttonPin) == HIGH){
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
7. Combining Loops and Conditions
Example: Blink LED 10 times only if button pressed
if(digitalRead(buttonPin) == HIGH){
for(int i = 0; i < 10; i++){
digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW);
delay(500);
}
}
8. Sensors and Inputs
Example: Reading Analog Sensor
int sensorPin = A0;
int sensorValue = 0;
void setup(){
Serial.begin(9600);
}
void loop(){
sensorValue = analogRead(sensorPin);
Serial.println(sensorValue);
delay(500);
}
9. Additional Tips
- Use Serial Monitor to debug: Serial.begin(9600) and Serial.print()
- Organize code with functions
- Start with small projects before moving to complex ones
10. Reference
Arduino Uno Pinout
- Digital: 0-13
- Analog: A0-A5
- Power: 5V, 3.3V, GND
- PWM: 3, 5, 6, 9, 10, 11
Quick Command Reference
- pinMode(pin, OUTPUT/INPUT)
- digitalWrite(pin, HIGH/LOW)
- digitalRead(pin)
- analogRead(pin)
- analogWrite(pin, value)
- delay(ms)
- for, while, if loops