Input Components: Buttons and Analog Inputs

SA
StudyAI
AI-generated study notes
· Published Updated

From the foundational concepts of Arduino programming and a comprehensive catalog of common electronic components used in prototyping. The objective is to establish a baseline for building interactive electronic projects using the Arduino UNO R3 platform. curriculum

TL;DR

You'll learn how to read simple on/off signals from buttons and how to interpret variable signals from analog sensors like potentiometers. Understanding these inputs is fundamental for making your Arduino projects interactive and responsive to the real world. We'll cover the necessary wiring and basic Arduino code to get you started with both digital and analog input readings.

1. The Mental Model

Imagine a button as a simple light switch: it's either on or off, sending a clear digital signal. An analog input, like a dimmer switch, provides a range of values, allowing your Arduino to sense varying levels or positions. These two types of inputs are how your Arduino "sees" what's happening outside of its own circuits.

2. The Core Material

When your Arduino interacts with the outside world, it needs to understand signals. Buttons provide digital input, meaning they're either HIGH (on) or LOW (off). Analog inputs, however, can read a range of values, typically from 0 to 1023 on the Arduino UNO.

Digital Inputs: Buttons

Detailed view of audio equipment showing inputs and digital controls in a studio setting.
Photo by Vladimir Srajber on Pexels

A push button, in its simplest form, acts as a momentary switch. When pressed, it completes a circuit; when released, it breaks it. To read a button reliably, you need to use a pull-up or pull-down resistor. This resistor ensures the pin has a defined state (HIGH or LOW) when the button isn't pressed, preventing "floating" readings. The Arduino UNO has built-in pull-up resistors you can enable in your code, which simplifies wiring.

Wiring a Button with Internal Pull-up:
1. Connect one side of the button to an Arduino digital pin (e.g., pin 2).
2. Connect the other side of the button to GND (Ground).

When the button is not pressed, the internal pull-up resistor pulls the pin HIGH.
When the button is pressed, it connects the pin directly to GND, making the pin LOW.

Code for Digital Input:

const int buttonPin = 2; // The digital pin the button is connected to

void setup() {
  Serial.begin(9600);
  // Set the buttonPin as an INPUT and enable the internal pull-up resistor
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop() {
  // Read the state of the button
  int buttonState = digitalRead(buttonPin);

  // Since we're using INPUT_PULLUP, the button is LOW when pressed
  if (buttonState == LOW) {
    Serial.println("Button is pressed!");
  } else {
    Serial.println("Button is released.");
  }
  delay(100); // Small delay to prevent too many readings
}

Analog Inputs: Potentiometers and Sensors

A detailed close-up of electronic components on a circuit board showcasing resistors and capacitors.
Photo by Abolfazl Pahlavan on Pexels

Analog inputs are used to read values that aren't just on or off, like the position of a knob, the brightness of light, or a temperature. The Arduino UNO has several analog input pins (A0-A5). These pins use an Analog-to-Digital Converter (ADC) to convert a voltage level into a digital number. For the Arduino UNO, this range is typically 0V to 5V, which is mapped to a digital value from 0 to 1023.

Wiring an Analog Input (e.g., Potentiometer):
A potentiometer has three pins:
1. Connect one outer pin to 5V.
2. Connect the other outer pin to GND.
3. Connect the middle (wiper) pin to an Arduino analog input pin (e.g., A0).

Turning the knob changes the voltage on the middle pin, which your Arduino reads.

Code for Analog Input:

const int analogInputPin = A0; // The analog pin the potentiometer is connected to

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

void loop() {
  // Read the analog value from the pin
  int sensorValue = analogRead(analogInputPin);

  // Print the raw sensor value
  Serial.print("Analog value: ");
  Serial.println(sensorValue);

  // You can map this value to a different range if needed, e.g., 0-255 for brightness
  // int mappedValue = map(sensorValue, 0, 1023, 0, 255);
  // Serial.print("Mapped value (0-255): ");
  // Serial.println(mappedValue);

  delay(50); // Small delay for stable readings
}

Here's how button logic typically flows:

graph TD
    A["Button Not Pressed (INPUT_PULLUP)"] --> B{digitalRead(buttonPin) == LOW?};
    B -- Yes --> C["Button Pressed Action"];
    B -- No --> D["Button Released Action"];
    C --> A;
    D --> A;

3. Worked Example

Let's combine these: use a button to toggle an LED on/off, and a potentiometer to control its brightness.

Wiring:
- Connect one side of a push button to digital pin 2. Connect the other side to GND.
- Connect the middle pin of a potentiometer to analog pin A0. Connect one outer pin to 5V and the other to GND.
- Connect the long leg (anode) of an LED to digital pin 9 (PWM pin) via a 220-ohm resistor. Connect the short leg (cathode) to GND.

Code:

const int buttonPin = 2;       // Button connected to digital pin 2
const int potentiometerPin = A0; // Potentiometer connected to analog pin A0
const int ledPin = 9;          // LED connected to digital pin 9 (PWM)

bool ledOn = false; // Variable to keep track of LED state
int lastButtonState = HIGH; // Variable to store the previous button state
long lastDebounceTime = 0; // The last time the output pin was toggled
long debounceDelay = 50; // The debounce time; increase if the output flickers

void setup() {
  pinMode(buttonPin, INPUT_PULLUP); // Use internal pull-up for the button
  pinMode(ledPin, OUTPUT);          // Set LED pin as an output
  Serial.begin(9600);
}

void loop() {
  // Read the current state of the button
  int reading = digitalRead(buttonPin);

  // If the button state has changed and enough time has passed for debounce
  if (reading != lastButtonState) {
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // Only toggle if the button is currently pressed (LOW with INPUT_PULLUP)
    if (reading == LOW && lastButtonState == HIGH) { // Detect a press (falling edge)
      ledOn = !ledOn; // Toggle the LED state
      Serial.print("LED state: ");
      Serial.println(ledOn ? "ON" : "OFF");
    }
  }

  // Save the current button state for the next loop iteration
  lastButtonState = reading;

  if (ledOn) {
    // Read the potentiometer value (0-1023)
    int potValue = analogRead(potentiometerPin);
    // Map the potentiometer value to the LED brightness range (0-255)
    int brightness = map(potValue, 0, 1023, 0, 255);
    analogWrite(ledPin, brightness); // Set LED brightness
  } else {
    analogWrite(ledPin, 0); // Turn LED off
  }

  delay(10); // Small delay for overall stability
}

This example introduces "debouncing" for the button, which is essential to prevent multiple presses from being registered when you press the button just once.

4. Key Takeaways

  • Digital inputs like buttons are either HIGH or LOW, perfect for on/off states.
  • Analog inputs read a range of values (0-1023 on UNO) from sensors like potentiometers.
  • Always use a pull-up or pull-down resistor for digital inputs to prevent "floating" pins.
  • The INPUT_PULLUP mode simplifies button wiring by using the Arduino's internal resistors.
  • digitalRead() is used for digital pins, and analogRead() is used for analog pins.
  • Debouncing is crucial for buttons to prevent false readings due to physical button bounce.

Common Mistakes:
- Not using a pull-up/pull-down resistor for buttons, leading to erratic readings.
- Connecting an analog sensor to a digital pin or vice-versa without understanding the difference.
- Forgetting to initialize Serial.begin() when trying to print to the Serial Monitor.
- Not adding a resistor to an LED, which can burn out the LED or damage the Arduino pin.

5. Now Try It

Wire up a button to digital pin 4 and an LED to digital pin 13 (the built-in LED). Write a program where pressing the button turns the LED on, and releasing it turns the LED off. Then, modify this so that each press of the button toggles the LED's state (on to off, or off to on), making sure to use the INPUT_PULLUP mode and implement basic debouncing as shown in the worked example. What does success look like? The LED should cleanly switch states with each single button press, without flickering or unexpected behavior.

Frequently asked about Input Components: Buttons and Analog Inputs

You'll learn how to read simple on/off signals from buttons and how to interpret variable signals from analog sensors like potentiometers. Understanding these inputs is fundamental for making your Arduino projects interactive and responsive to the real world. Read the full notes above for the details.

Input Components: Buttons and Analog Inputs is a core topic in foundational concepts of Arduino programming and a comprehensive catalog of common electronic components used in prototyping. The objective is to establish a baseline for building interactive electronic projects using the Arduino UNO R3 platform.. Most exam papers test it via a mix of definitions, worked examples, and applied problems. The notes above cover the high-yield sub-topics, common pitfalls, and the kind of questions examiners typically set.

Yes — every note in the StudyAI Campus Hub is free to read in full, right here on this page, with no account needed. If you clone the plan into your own dashboard, the free plan shows a preview of each note there; Basic and above unlock the full notes in your dashboard, along with practice quizzes, flashcards and offline study. You can always come back here to read the complete note for free.

Study this next


Get the full foundational concepts of Arduino programming and a comprehensive catalog of common electronic components used in prototyping. The objective is to establish a baseline for building interactive electronic projects using the Arduino UNO R3 platform. curriculum

Clone the complete plan to your dashboard for unlimited AI-generated notes, practice quizzes, and a personalised revision schedule.

Save this course free