GK SOLUTIONS
AI • IoT • Arduino • Projects & Tutorials
DEFEAT THE FEAR

Analog vs Digital

  • Digital: ON or OFF (1 or 0)
  • Analog: Range of values (0 to 1023 for input, 0 to 255 for output)

Analog Input: Reading a Potentiometer

int potPin = A0;

void setup() {
    Serial.begin(9600);
}

void loop() {
    int value = analogRead(potPin);  // 0 to 1023
    Serial.println(value);
    delay(100);
}

Analog Output: PWM (LED Brightness)

PWM (Pulse Width Modulation) simulates analog output. Only works on pins marked with ~ (3, 5, 6, 9, 10, 11).

int ledPin = 9;  // Must be a PWM pin (~)

void setup() {
    pinMode(ledPin, OUTPUT);
}

void loop() {
    // Fade LED in
    for (int i = 0; i <= 255; i++) {
        analogWrite(ledPin, i);  // 0=off, 255=full brightness
        delay(10);
    }
    // Fade LED out
    for (int i = 255; i >= 0; i--) {
        analogWrite(ledPin, i);
        delay(10);
    }
}

Combine: Potentiometer Controls LED

int potPin = A0;
int ledPin = 9;

void setup() {
    pinMode(ledPin, OUTPUT);
}

void loop() {
    int potValue = analogRead(potPin);           // 0-1023
    int brightness = map(potValue, 0, 1023, 0, 255);  // Scale to 0-255
    analogWrite(ledPin, brightness);
}

✅ Quick Quiz

❓ What range does analogRead() return?

❓ What does the map() function do?

❓ What does PWM stand for?