2

Week 2: Arduino IDE & First Programs

Master the Arduino development environment and create your first programs

32-Week Course • Semester 1

Learning Objectives

By the end of this lesson, you will:

  • • Navigate the Arduino IDE with confidence
  • • Understand program structure (setup and loop)
  • • Create and upload your first Arduino programs
  • • Use serial communication for debugging

Skills You'll Develop:

  • • IDE navigation and customization
  • • Code writing and editing techniques
  • • Program compilation and uploading
  • • Serial Monitor usage for output

Section 1: Programming Environment Exploration

Understanding Programming Environments

A programming environment is where you write, test, and debug your code. Let's explore the key components that make programming efficient and enjoyable:

Essential Programming Environment Features:

  • Code Editor: Where you write your programs with syntax highlighting
  • File Management: Organize and save your projects
  • Error Detection: Identifies mistakes in your code before running
  • Output Console: Shows results and messages from your programs
  • Debugging Tools: Help you find and fix problems in your code

Online Simulator Benefits

For now, we'll use online simulators that provide all these features without requiring any software installation:

Why Start with Simulators:

  • Instant Access: No downloads or installations required
  • Safe Learning: Experiment without fear of breaking anything
  • Visual Feedback: See your code control virtual components
  • Built-in Examples: Learn from pre-made projects and tutorials
  • Sharing Capability: Easily share your projects with others

Section 2: Arduino Program Structure

The Two Essential Functions

Every Arduino program (called a "sketch") must have two main functions. Understanding these is crucial for all Arduino programming:

setup() Function

  • • Runs only once when the program starts
  • • Used for initialization tasks
  • • Set pin modes, start serial communication
  • • Initialize variables and libraries

loop() Function

  • • Runs continuously after setup() completes
  • • Contains the main program logic
  • • Repeats forever until power is removed
  • • Where sensors are read and outputs controlled

Basic Program Template

Here's the basic structure that every Arduino program follows:

$// Global variables and constants go here
int ledPin = 13;
int delayTime = 1000;

void setup() {
  // Initialization code runs once
  Serial.begin(9600);           // Start serial communication
  pinMode(ledPin, OUTPUT);      // Set pin 13 as output
  Serial.println("Program starting...");
}

void loop() {
  // Main program code runs repeatedly
  digitalWrite(ledPin, HIGH);   // Turn LED on
  delay(delayTime);            // Wait
  digitalWrite(ledPin, LOW);    // Turn LED off
  delay(delayTime);            // Wait
  Serial.println("LED blinked");
}

Section 3: Your First Programs

Program 1: Digital Counter & Timer

Let's start with a program that demonstrates counting, timing, and serial communication - all without requiring any hardware:

$// Digital Counter & Timer Program
int counter = 0;              // Main counter variable
int cycleCount = 0;           // Tracks complete cycles
unsigned long startTime;      // Program start time

void setup() {
  Serial.begin(9600);         // Start serial communication at 9600 baud
  startTime = millis();       // Record when program started
  Serial.println("=== Digital Counter & Timer Started ===");
  Serial.println("This program demonstrates counting and timing");
  Serial.println("Watch the Serial Monitor for updates!");
  Serial.println();
}

void loop() {
  // Calculate runtime
  unsigned long runtime = millis() - startTime;
  
  // Display counter status
  Serial.print("Counter: ");
  Serial.print(counter);
  Serial.print(" | Runtime: ");
  Serial.print(runtime / 1000);
  Serial.println(" seconds");
  
  counter++;                  // Increment counter
  delay(1000);               // Wait 1 second
  
  // Reset counter after 10 counts
  if (counter >= 10) {
    cycleCount++;
    Serial.println("--- Cycle Complete! ---");
    Serial.print("Total cycles completed: ");
    Serial.println(cycleCount);
    Serial.println();
    counter = 0;              // Reset counter
  }
}

Program 2: Data Processing & Simulation

This program demonstrates data processing, mathematical calculations, and formatted output - all using simulated data:

$// Data Processing & Simulation Program
unsigned long startTime;
int dataPoint = 0;
float temperature = 23.5;
float humidity = 45.0;
int readings = 0;

void setup() {
  Serial.begin(9600);
  startTime = millis();         // Record start time
  
  Serial.println("=== Environmental Data Simulator ===");
  Serial.println("This program simulates and processes sensor data");
  Serial.println("No hardware required - all data is calculated!");
  Serial.println();
}

void loop() {
  // Calculate runtime
  unsigned long runtime = millis() - startTime;
  readings++;
  
  // Simulate realistic sensor data using math
  temperature = 22.0 + sin(readings * 0.1) * 5.0;  // Oscillating temperature
  humidity = 50.0 + cos(readings * 0.15) * 15.0;   // Oscillating humidity
  dataPoint = random(100, 1000);                   // Random data point
  
  // Display formatted data with calculations
  Serial.println("--- Environmental Reading ---");
  Serial.print("Reading #");
  Serial.print(readings);
  Serial.print(" | Runtime: ");
  Serial.print(runtime / 1000);
  Serial.println(" seconds");
  
  Serial.print("Temperature: ");
  Serial.print(temperature, 1);  // 1 decimal place
  Serial.println(" °C");
  
  Serial.print("Humidity: ");
  Serial.print(humidity, 1);
  Serial.println(" %");
  
  Serial.print("Data Point: ");
  Serial.println(dataPoint);
  
  // Calculate and display average temperature
  static float tempSum = 0;
  tempSum += temperature;
  float avgTemp = tempSum / readings;
  Serial.print("Average Temp: ");
  Serial.print(avgTemp, 2);
  Serial.println(" °C");
  
  Serial.println();             // Empty line for readability
  delay(2000);                  // Wait 2 seconds between readings
}

Section 4: Hands-On Activity - Create Your Simulation Program

Your Programming Challenge

Now it's time to create your own Arduino simulation program! Choose one of these themes and create a program that uses only Serial Monitor output - no hardware required:

🚦 Traffic Light Simulator

Simulate traffic light sequences with timing and status messages in the Serial Monitor

💓 Heartbeat Monitor Simulator

Simulate heartbeat patterns with variable timing and pulse counting via text output

🌡️ Weather Station Simulator

Create realistic weather data using mathematical functions and display formatted reports

🎮 Game Score Tracker

Simulate a game scoring system with player stats, levels, and achievements

Program Requirements

Your simulation program must include:

  • ✓ Proper setup() and loop() structure
  • ✓ Serial communication with formatted output
  • ✓ At least two variables to track program state
  • ✓ Mathematical calculations or data processing
  • ✓ Appropriate delay() timing for realistic simulation
  • ✓ Comments explaining what your code does
  • ✓ Use of millis() for timing or counters for tracking

Example: Weather Station Simulator

Here's an example to inspire your creativity:

$// Weather Station Simulator Example
float temperature = 20.0;
float humidity = 50.0;
float pressure = 1013.25;
int readings = 0;
unsigned long lastUpdate = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("=== Weather Station Simulator ===");
  Serial.println("Generating realistic weather data...");
  Serial.println("No sensors required - all mathematically calculated!");
  Serial.println();
}

void loop() {
  // Update every 3 seconds
  if (millis() - lastUpdate >= 3000) {
    readings++;
    
    // Simulate realistic weather changes using math
    temperature = 18.0 + sin(readings * 0.05) * 8.0 + random(-10, 11) / 10.0;
    humidity = 45.0 + cos(readings * 0.08) * 20.0 + random(-50, 51) / 10.0;
    pressure = 1010.0 + sin(readings * 0.03) * 15.0 + random(-20, 21) / 10.0;
    
    // Keep values in realistic ranges
    humidity = constrain(humidity, 20.0, 90.0);
    pressure = constrain(pressure, 980.0, 1040.0);
    
    // Display formatted weather report
    Serial.println("--- WEATHER REPORT ---");
    Serial.print("Reading #");
    Serial.print(readings);
    Serial.print(" | Time: ");
    Serial.print(millis() / 1000);
    Serial.println(" seconds");
    
    Serial.print("Temperature: ");
    Serial.print(temperature, 1);
    Serial.println(" °C");
    
    Serial.print("Humidity: ");
    Serial.print(humidity, 1);
    Serial.println(" %");
    
    Serial.print("Pressure: ");
    Serial.print(pressure, 2);
    Serial.println(" hPa");
    
    // Weather condition analysis
    if (temperature > 25) {
      Serial.println("Condition: HOT ☀️");
    } else if (temperature < 10) {
      Serial.println("Condition: COLD ❄️");
    } else {
      Serial.println("Condition: MILD 🌤️");
    }
    
    Serial.println();
    lastUpdate = millis();
  }
}

📝 Assessment & Homework

📊 Quick Assessment

  • • Demonstrate Arduino IDE navigation and usage
  • • Explain setup() vs loop() function purposes
  • • Show Serial Monitor debugging techniques
  • • Create a themed program with variables

🏠 Homework Assignment

  • • Enhance your themed program with new features
  • • Practice Serial Monitor data analysis
  • • Research Arduino programming best practices
  • • Document your code with meaningful comments

Homework Assignments

Assignment 1: Program Enhancement

Take your themed program from the hands-on activity and add these features:

  • • Add a counter that tracks total cycles
  • • Include a startup message with your name
  • • Add at least one more variable to control timing
  • • Include status updates every 10 cycles

Assignment 2: Serial Monitor Exploration

Experiment with the Serial Monitor and document:

  • • Different baud rates (9600, 115200) and their effects
  • • Using Serial.print() vs Serial.println()
  • • Formatting numbers with different decimal places
  • • Creating organized output with spacing and lines

Submission Guidelines

  • Code Files: Save your programs with descriptive names (e.g., "TrafficLight_YourName.ino")
  • Documentation: Include comments explaining your code and design choices
  • Serial Output: Copy and paste sample Serial Monitor output with your submission
  • Reflection: Write 2-3 sentences about what you learned and any challenges faced
  • Due Date: Submit before next week's lesson
← Previous: Week 1
📝 Take Quiz Next: Week 3 →