Cómo conectar un display de 7 segmentos con Arduino
El display de 7 segmentos es un dispositivo utilizado para mostrar números y algunas letras. Puede ser de ánodo común o cátodo común. Aquí tienes una guía básica para usar ambos tipos con Arduino.
Conexión
Los pines de un display 7 segmentos están distribuidos de la siguiente forma:

Comprendamos de que cada segmento es como tener 1 led, donde este led es un dispositivo digital que recibe valores altos y bajos (1-0), en este caso para encender o apagar un segmento basta con enviar esa señal tal cual como si fueramos a encender o apagar un led. Con ello vamos a mirar un poco de como seria la conexión de un display 7 segmentos ánodo común:

El ánodo común lo he conectado a 5V (cable rojo).
Como puedes ver, el resto de conexiones llevan una resistencia y van cada una a un pin digital del Arduino. Quedan así:
- A: DIGITAL 2 (cable naranja)
- B: DIGITAL 3 (cable verde)
- C: DIGITAL 4 (cable azul)
- D: DIGITAL 5 (cable morado)
- E: DIGITAL 6 (cable marrón)
- F: DIGITAL 7 (cable amarillo)
- G: DIGITAL 8 (cable rosa)
Los segmentos no dejan de ser leds, por tanto una resistencia nos ayudará a prolongar la vida útil del display. Ten en cuenta que no estarán todos los segmentos siempre encendidos, dependerá del dígito que se muestre, por eso conectar una resistencia por segmento nos garantiza que todos se iluminen con la misma intensidad.
Bien esta seria la conexión de un display de 7 segmentos ánodo común, ahora veamos como sería dado el caso que tuviesemos un display catodo común:

El cátodo común lo he conectado a tierra (GND) (cable negro).
Si te fijas, es la única diferencia con respecto al de ánodo común. El resto de conexiones son exactamente iguales.
Lo ves? No hay mucha diferencia entre conexiones.
Ahora vamos al código:
Código Arduino:
En este ejemplo vamos a mostrar los números de 0 a 9 sin implementar funciones y con una espera entre cada cambio de número de 2 segundos:
Nota: recuerda si estás trabajando con un display ánodo común (0) o LOW encendera y (1) o HIGH apagar el segmento, de otro modo si usas el cátodo común (0) o LOW apagara y (1) o HIGH encendera.
const int A = 2;
const int B = 3;
const int C = 4;
const int D = 5;
const int E = 6;
const int F = 7;
const int G = 8;
void setup() {
pinMode(A, OUTPUT);
pinMode(B, OUTPUT);
pinMode(C, OUTPUT);
pinMode(D, OUTPUT);
pinMode(E, OUTPUT);
pinMode(F, OUTPUT);
pinMode(G, OUTPUT);
}
void loop() {
/*Número 0*/
digitalWrite(A, 0);
digitalWrite(B, 0);
digitalWrite(C, 0);
digitalWrite(D, 0);
digitalWrite(E, 0);
digitalWrite(F, 0);
digitalWrite(G, 1);
/*Fin 0*/
delay(2000);
/*Número 1*/
digitalWrite(A, 1);
digitalWrite(B, 0);
digitalWrite(C, 0);
digitalWrite(D, 1);
digitalWrite(E, 1);
digitalWrite(F, 1);
digitalWrite(G, 1);
/*Fin1*/
delay(2000);
/*Número 2*/
digitalWrite(A, 0);
digitalWrite(B, 0);
digitalWrite(C, 1);
digitalWrite(D, 0);
digitalWrite(E, 0);
digitalWrite(F, 1);
digitalWrite(G, 0);
/*Fin2*/
delay(2000);
/*Número 3*/
digitalWrite(A, 0);
digitalWrite(B, 0);
digitalWrite(C, 0);
digitalWrite(D, 0);
digitalWrite(E, 1);
digitalWrite(F, 1);
digitalWrite(G, 0);
/*Fin3*/
delay(2000);
/*Número 4*/
digitalWrite(A, 1);
digitalWrite(B, 0);
digitalWrite(C, 0);
digitalWrite(D, 1);
digitalWrite(E, 1);
digitalWrite(F, 0);
digitalWrite(G, 0);
/*Fin4*/
delay(2000);
/*Número 5*/
digitalWrite(A, 0);
digitalWrite(B, 1);
digitalWrite(C, 0);
digitalWrite(D, 0);
digitalWrite(E, 1);
digitalWrite(F, 0);
digitalWrite(G, 0);
/*Fin5*/
delay(2000);
/*Número 6*/
digitalWrite(A, 0);
digitalWrite(B, 1);
digitalWrite(C, 0);
digitalWrite(D, 0);
digitalWrite(E, 0);
digitalWrite(F, 0);
digitalWrite(G, 0);
/*Fin6*/
delay(2000);
/*Número 7*/
digitalWrite(A, 0);
digitalWrite(B, 0);
digitalWrite(C, 0);
digitalWrite(D, 1);
digitalWrite(E, 1);
digitalWrite(F, 1);
digitalWrite(G, 0);
/*Fin7*/
delay(2000);
/*Número 8*/
digitalWrite(A, 0);
digitalWrite(B, 0);
digitalWrite(C, 0);
digitalWrite(D, 0);
digitalWrite(E, 0);
digitalWrite(F, 0);
digitalWrite(G, 0);
/*Fin8*/
delay(2000);
/*Número 9*/
digitalWrite(A, 0);
digitalWrite(B, 0);
digitalWrite(C, 0);
digitalWrite(D, 1);
digitalWrite(E, 1);
digitalWrite(F, 0);
digitalWrite(G, 0);
/*Fin9*/
delay(2000);
}El código anterior me muestra los número de 0 a 9 con un tiempo de cambio de 2 segundos. Ahora vamos implementar un código un poco más robusto en cuanto a estructura pero con el cual obtendremos el mismo resultado:
const int DIGITOS[10][7] = {
/*0*/ {0,0,0,0,0,0,1},
/*1*/ {1,0,0,1,1,1,1},
/*2*/ {0,0,1,0,0,1,0},
/*3*/ {0,0,0,0,1,1,0},
/*4*/ {1,0,0,1,1,0,0},
/*5*/ {0,1,0,0,1,0,0},
/*6*/ {0,1,0,0,0,0,0},
/*7*/ {0,0,0,1,1,1,1},
/*8*/ {0,0,0,0,0,0,0},
/*9*/ {0,0,0,0,1,0,0}
};
const int OFF = HIGH;
const int A = 2;
const int B = 3;
const int C = 4;
const int D = 5;
const int E = 6;
const int F = 7;
const int G = 8;
const int N = 7;
const int SEGMENTOS[N] = {A,B,C,D,E,F,G};
void setup()
{
for (int i=0; i<N; i++){
pinMode(SEGMENTOS[i], OUTPUT);
digitalWrite(SEGMENTOS[i], OFF);//apagar
}
}
void print(int d){
for (int i=0; i<N; i++){
digitalWrite(SEGMENTOS[i], DIGITOS[d][i]);
}
}
void loop()
{
for(int i=0; i<10; i++){
print(i);
delay(2000);// esperar 1000 milisegundos
}
}
Que estamos haciendo? el código anterior realizamos la muestra de cada número a traves del encendido y apagado de cada segmento de manera individual, en este caso estamos creando un array donde almacenamos todos los segmentos presentes en el display para luego hacer un recorrido y de acuerdo al valor que le pasemos se muestra el valor del resultado.
El array tiene 10 elementos, uno por cada dígito (0-9). Como ya sabes, las posiciones de los arrays siempre empiezan en 0, por tanto cada posición corresponderá con el dígito que queremos mostrar. Una vez hemos accedido a la posición que nos interesa, nos encontraremos en dicha posición otro array con 7 elementos, uno por cada segmento. Cada posición de este array contendrá valor 0 o 1 dependiendo de si tenemos que encender o apagar el segmento. La combinación de los 7 visualizará el dígito en el display. Yo he ordenado los segmentos de A a G, por tanto la posición 0 será A, la 1 será B, etc. Si lo prefieres lo puedes hacer al revés.
Función void setup()
Como hemos conectado cada segmento a un pin digital hay que configurar los pines afectados como salida (OUTPUT), para ello usaremos la función pinMode (SEGMENTOS[i], OUTPUT). La ventaja de haber guardado todos los pines dentro del array SEGMENTOS es que ahora podemos iterar con un bucle for y usar pinMode con cada uno de los valores del array accediendo a estos con el indice i proporcionado por el bucle.
Además, vamos a enviar el valor de la constante OFF, que declaramos al principio, a cada pin, utilizando la función digitalWrite (SEGMENTOS[i], OFF). Si te acuerdas, habíamos declarado la constante OFF con valor HIGH para el ánodo común y con valor LOW para el cátodo común. Estos valores no son arbitrarios, son los que necesitamos en cada tipo de display para apagar los segmentos. Como digitalWrite se llama por cada iteración del bucle, estamos enviando el valor OFF a cada segmento definido en el array SEGMENTOS. De esta forma, cuando arranquemos el Arduino, todos los segmentos estarán apagados.
Funciones
Lo siguiente que haremos será definir una función que nos ayude a mostrar el dígito que queramos en el display. Yo la he llamado print, pero la puedes llamar como quieras:
La función print recibe como parámetro un entero (int d), que será el dígito que queremos mostrar en el display.
Se ejecuta digitalWrite (SEGMENTOS[i], DIGITOS[d][i]) por cada iteración del bucle for (una iteración por segmento). Como puedes ver, el primer parámetro es SEGMENTOS[i] puesto que tenemos que indicarle el pin digital sobre el que realizaremos la escritura. El segundo parámetro es DIGITOS[d][i]. Puesto que d es el dígito a mostrar (será un número entre 0 y 9) nos servirá de indice para acceder a la posición correspondiente dentro del array DIGITOS y así poder acceder a los valores de sus segmentos utilizando el indice i.
Función void loop()
El indice i del bucle for tomará todos los valores comprendidos entre 0 y 9 (ambos incluidos), por lo que el valor de i será el dígito a mostrar. Simplemente hay que llamar a la función print que definimos antes y pasarle como argumento el indice i. La función print ya se encarga de mostrar el dígito en el display. Además, delay(2000) nos ayudará a visualizar el resultado, puesto que generará un retardo de 1 segundo antes de la siguiente iteración del bucle, haciendo que cada dígito se muestre durante ese segundo en el display.
Pública tu duda o comentario
Resuelve tus dudas con la comunidad.


(20) Comentarios
isthisacryforhelppannew
If you want the Is This a Cry for Help PDF, get it here for a great reading experience. This digital version is perfect for you. Secure your download today. https://isthisacryforhelppdf.site/ Is This A Cry For Help Issuu
withthefireonhighpannew
Literature lovers are flocking to this title for its honest portrayal of teen life. You can read the With the Fire on High PDF on your favorite device today. It is a story that proves passion can open doors that seem permanently closed. https://withthefireonhighpdf.site/ With The Fire On High Book Online
clapwhenyoulandpdfannew
Experience the emotional depth of this novel in verse. The story of Camino and Yahaira is one of resilience and hope. For a seamless reading experience, the Clap When You Land PDF is a popular choice. https://clapwhenyoulandpdf.site/ Clap When You Land Page Count
bornoftroublepdfannew
Born of Trouble is the ultimate story of overcoming the odds. This powerful narrative is now available in a digital pdf format. Join the protagonist as they fight for their future in a world that seems set against them. It is a story that will inspire and move you. https://bornoftroublepdf.site/ Born Of Trouble Chapter 1 Pdf
anarchiveofromanceannew
Reading in a foreign language is a challenge, but rewarding. An international archive of romance offers books in many languages. I download the PDF in a language I am studying to practice my reading comprehension in a fun and engaging way. https://anarchiveofromancepdf.top/ An Archive Of Romance Pdf Google Drive
anarchiveofromanceannew
I am always on the lookout for hidden literary treasures. An underground archive of romance often holds books that mainstream publishers ignored. I love supporting these indie gems by downloading the PDF and spreading the word about the incredible stories I find. https://anarchiveofromancepdf.top/ An Archive Of Romance Pdf Reddit
anarchiveofromanceannew
Organizing your digital files can be satisfying for a perfectionist. I label every file I get from an archive of romance to keep my collection tidy. Having a standardized PDF format for all my books makes it much easier to manage my library and find exactly what I want to read. https://anarchiveofromancepdf.top/ Read An Archive Of Romance Full Novel
youcanscreampdfannew
You can uncover secrets that make you scream. This PDF is the key. It is a digital file that opens up a world of mystery. Download it today and start uncovering the truth behind the story. It is a compelling read you won't regret. https://youcanscreampdf.top/ You Can Scream Full Story Download
youcanscreampdfannew
Don't let a busy schedule stop you; you can read this PDF in short bursts. It is a story that will make you scream for more time to read. The digital format allows you to bookmark your place and return exactly where you left off. https://youcanscreampdf.top/ You Can Scream Digital Copy
anarchiveofromanceannew
I love the "surprise me" button feature some sites have. An archive of romance with a randomizer is fun. I let the site pick a random PDF for me to download, forcing me to try sub-genres or authors I might not have picked myself. https://anarchiveofromancepdf.top/ An Archive Of Romance Fantasy Pdf
youcanscreampdfannew
If you want a book that makes you scream, you can download the PDF. It is easy. The file is small. simple and effective. https://youcanscreampdf.top/ You Can Scream Torrent
anarchiveofromanceannew
Digital libraries are a savior for students and voracious readers alike. If you are looking for light reading, a vast archive of romance offers endless entertainment. The ability to grab a PDF file means you can start reading immediately, avoiding the wait times associated with shipping physical books. https://anarchiveofromancepdf.top/ An Archive Of Romance Pdf Download
inyourdreamspdfannew
Don't miss out on the book everyone is talking about; grab the In Your Dreams PDF to see what the hype is all about. The electronic version ensures that you can start the first chapter immediately and enjoy the story in its highest quality format. https://inyourdreamspdf.top/ In Your Dreams Sarah Adams Mobi
sunriseonthereapinannew
Sunrise on the Reaping by Suzanne Collins delivers the powerful backstory fans have craved for years. This PDF reveals young Haymitch's heartbreaking experiences during the fiftieth Games. Discover why he became cynical. Download free instantly without any registration barriers today. https://sunriseonthereapingpdf.top/ When Does Sunrise On The Reaping Come Out?
heiroffirepdfannew
Experience dialogue that reveals character while advancing plot efficiently. https://heiroffirepdf.top/ What Chapter Does Sorscha Die In Heir Of Fire
ironflamepdfannew
Iron Flame roars real! Violet's realm rules. Download free today! https://ironflamepdf.top/ Iron Flame Release Date
acourtofmistandfurannew
If you loved A Court of Thorns and Roses, you need the sequel. Get the A Court of Mist and Fury PDF for your collection. This story takes everything to a new level of intensity and emotion. Read it on your preferred device with our easy download. https://acourtofmistandfurypdf.top/ Synopsis Of A Court Of Mist And Fury
fourthwingpdfannew
The final battle is a masterpiece of tension. Read it in the Fourth Wing PDF. It leaves you breathless and wanting the sequel immediately. https://fourthwingpdf.top/ Does Liam Die In Fourth Wing
acourtofthornsandrannew
Every legend has a seed of truth, and Feyre is about to find hers. Get the A Court of Thorns and Roses PDF to uncover the secrets of the High Fae. This digital book is perfect for late-night reading sessions under the covers. https://acourtofthornsandrosespdf.top/ How Many Books In A Court Of Thorns And Roses
https://vivod-iz-zapoya-1.ru/
Этот информационный обзор станет отличным путеводителем по актуальным темам, объединяющим важные факты и мнения экспертов. Мы исследуем ключевые идеи и представляем их в доступной форме для более глубокого понимания. Читайте, чтобы оставаться в курсе событий! Углубиться в тему - https://vivod-iz-zapoya-1.ru/