Bird
0
0
Arduinoprogramming~5 mins

Seven-segment display control in Arduino

Choose your learning style9 modes available
Introduction

A seven-segment display shows numbers using light segments. Controlling it lets you show digits on devices like clocks or counters.

Displaying numbers on a digital clock.
Showing scores in a game.
Counting items on a simple counter.
Displaying temperature readings on a small device.
Creating a simple calculator output.
Syntax
Arduino
void setup() {
  // Set pins as outputs
  pinMode(pin1, OUTPUT);
  pinMode(pin2, OUTPUT);
  ...
}

void loop() {
  // Turn on/off segments to show a digit
  digitalWrite(pin1, HIGH or LOW);
  digitalWrite(pin2, HIGH or LOW);
  ...
  delay(time_in_ms);
}

Each segment of the display connects to a pin on the Arduino.

Setting a pin HIGH or LOW turns a segment on or off.

Examples
Turns on one segment and turns off another.
Arduino
digitalWrite(2, HIGH); // Turn on segment connected to pin 2
digitalWrite(3, LOW);  // Turn off segment connected to pin 3
Sets pin 4 as output to control a segment.
Arduino
pinMode(4, OUTPUT); // Prepare pin 4 to control a segment
Pauses the program so the digit stays visible.
Arduino
delay(1000); // Wait for 1 second before changing display
Sample Program

This program lights up the segments to show digits 0 through 9 one by one, each for one second.

Arduino
/*
  Simple Arduino program to display digits 0 to 9 on a common cathode seven-segment display.
  Segments a-g connected to pins 2-8.
*/

const int segmentPins[7] = {2, 3, 4, 5, 6, 7, 8};

// Digit patterns for 0-9 (a-g segments)
const byte digits[10][7] = {
  {HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, LOW},    // 0
  {LOW, HIGH, HIGH, LOW, LOW, LOW, LOW},         // 1
  {HIGH, HIGH, LOW, HIGH, HIGH, LOW, HIGH},      // 2
  {HIGH, HIGH, HIGH, HIGH, LOW, LOW, HIGH},      // 3
  {LOW, HIGH, HIGH, LOW, LOW, HIGH, HIGH},       // 4
  {HIGH, LOW, HIGH, HIGH, LOW, HIGH, HIGH},      // 5
  {HIGH, LOW, HIGH, HIGH, HIGH, HIGH, HIGH},     // 6
  {HIGH, HIGH, HIGH, LOW, LOW, LOW, LOW},        // 7
  {HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH},    // 8
  {HIGH, HIGH, HIGH, HIGH, LOW, HIGH, HIGH}      // 9
};

void setup() {
  for (int i = 0; i < 7; i++) {
    pinMode(segmentPins[i], OUTPUT);
  }
}

void loop() {
  for (int digit = 0; digit < 10; digit++) {
    for (int seg = 0; seg < 7; seg++) {
      digitalWrite(segmentPins[seg], digits[digit][seg]);
    }
    delay(1000); // Show each digit for 1 second
  }
}
OutputSuccess
Important Notes

Make sure to connect the display correctly: common cathode means the common pin goes to ground.

Use current-limiting resistors (around 220Ω) on each segment to protect the LEDs.

Pin numbers in the code must match your actual wiring.

Summary

Seven-segment displays show digits by lighting segments.

Control each segment by setting Arduino pins HIGH or LOW.

Use arrays to store segment patterns for digits to simplify code.