0% found this document useful (0 votes)
82 views

Lab 2 - Uso de Display 7 Segmentos en Arduino. Entradas Analogicas

This document provides examples of using 7-segment displays, analog inputs, and other displays with Arduino. It discusses: 1. Using a 7-segment display directly or with a decoder, including code to write numbers to the display. 2. Taking analog input from a potentiometer and using the reading to control an LED brightness. 3. Other displays like Grove 4-Digit and MAX7219 chips that can drive 7-segment displays with fewer pins. Code examples are provided to demonstrate their use.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

Lab 2 - Uso de Display 7 Segmentos en Arduino. Entradas Analogicas

This document provides examples of using 7-segment displays, analog inputs, and other displays with Arduino. It discusses: 1. Using a 7-segment display directly or with a decoder, including code to write numbers to the display. 2. Taking analog input from a potentiometer and using the reading to control an LED brightness. 3. Other displays like Grove 4-Digit and MAX7219 chips that can drive 7-segment displays with fewer pins. Code examples are provided to demonstrate their use.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Lab 2 – Uso de Display 7 segmentos en Arduino.

Entradas Analogicas

I. Usando el Display de 7 segmentos

Utiliza un display de 7 segmentos como el de la figura:

a. Manejando display sin decodificador.

byte seven_seg_digits[10][7] = {

{ 1,1,1,1,1,1,0 }, // = 0

{ 0,1,1,0,0,0,0 }, // = 1

{ 1,1,0,1,1,0,1 }, // = 2
{ 1,1,1,1,0,0,1 }, // = 3

{ 0,1,1,0,0,1,1 }, // = 4

{ 1,0,1,1,0,1,1 }, // = 5

{ 1,0,1,1,1,1,1 }, // = 6

{ 1,1,1,0,0,0,0 }, // = 7

{ 1,1,1,1,1,1,1 }, // = 8

{ 1,1,1,0,0,1,1 } // = 9

};

void setup() {
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
writeDot(0); // start with the "dot" off
}

void writeDot(byte dot) {


digitalWrite(9, dot);
}

void sevenSegWrite(byte digit) {


byte pin = 2;
for (byte segCount = 0; segCount < 7; ++segCount) {
digitalWrite(pin, seven_seg_digits[digit][segCount]);
++pin;
}
}

void loop() {
for (byte count = 10; count > 0; --count) {
delay(1000);
sevenSegWrite(count - 1);
}
delay(4000);
}

b. Otro ejemplo del mismo caso

1 Arduino .
8 resistencias de 1kOhm.
display de 7 segmentos (Cátodo común).

Primero es conectar el cátodo a la GND de la placa. Después hay que


conectar los ánodos a las salidas digitales de la placa intercalando en serie las
resistencias de 220 Ohm.

El código de funcionamiento será el siguiente:

/*
Contador de 7-segmentos
*/

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 h = 9;

// The setup() method runs once, when the sketch starts

void setup() {
// initialize the digital pin as an output:
pinMode(a, OUTPUT);
pinMode(b, OUTPUT);
pinMode(c, OUTPUT);
pinMode(d, OUTPUT);
pinMode(e, OUTPUT);
pinMode(f, OUTPUT);
pinMode(g, OUTPUT);
pinMode(h, OUTPUT);
}
void Representar(int valor){
switch(valor){
case 0:

digitalWrite(a, HIGH);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(e, HIGH);
digitalWrite(f, HIGH);
digitalWrite(d, HIGH);
break;

case 1:
digitalWrite(c, HIGH);
digitalWrite(b, HIGH);
break;

case 2:
digitalWrite(a, HIGH);
digitalWrite(b, HIGH);
digitalWrite(d, HIGH);
digitalWrite(e, HIGH);
digitalWrite(g, HIGH);
break;

case 3:
digitalWrite(a, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, HIGH);
digitalWrite(b, HIGH);
digitalWrite(g, HIGH);
break;

case 4:
digitalWrite(b, HIGH);
digitalWrite(g, HIGH);
digitalWrite(c, HIGH);
digitalWrite(f, HIGH);
break;

case 5:
digitalWrite(a, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, HIGH);
digitalWrite(f, HIGH);
digitalWrite(g, HIGH);
break;

case 6:
digitalWrite(a, HIGH);
digitalWrite(d, HIGH);
digitalWrite(e, HIGH);
digitalWrite(f, HIGH);
digitalWrite(g, HIGH);
digitalWrite(c, HIGH);
break;

case 7:
digitalWrite(a, HIGH);
digitalWrite(c, HIGH);
digitalWrite(b, HIGH);
break;

case 8:
digitalWrite(a, HIGH);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(d, HIGH);
digitalWrite(e, HIGH);
digitalWrite(f, HIGH);
digitalWrite(g, HIGH);
break;

case 9:
digitalWrite(a, HIGH);
digitalWrite(b, HIGH);
digitalWrite(c, HIGH);
digitalWrite(g, HIGH);
digitalWrite(f, HIGH);
break;

default:
digitalWrite(h, HIGH);
break;
}
}
void LimpiarDisplay(){
digitalWrite(a, LOW);
digitalWrite(b, LOW);
digitalWrite(c, LOW);
digitalWrite(d, LOW);
digitalWrite(e, LOW);
digitalWrite(f, LOW);
digitalWrite(g, LOW);
}
void loop(){
for(int i=0;i<=9;i++){
LimpiarDisplay();
Representar(i);
delay(500);
}
}

Consta de los procedimientos:

• setup() Inicializa los pines que vamos a utilizar como de salida.


• Representar(int valor) Recibe un entero y lo representa en el display.
• Limpiardisplay() Apaga todos los leds para representar el siguiente
dato.
• loop() Contiene el contador de 0 a 9.

II. Grove - 4-Digit Display

Grove - 4-Digit Display module is a 12-pin module. In this module, we utilize a


TM1637 to scale down the number of controlling pins to 2. That is to say, it
controls both the content and the luminance via only 2 digital pins of Arduino
or Seeeduino. For projects that require alpha-numeric display, this can be a
nice choice.

Características

• 4 digit red alpha-numeric display


• Grove compatible interface (3.3V/5V)
• 8 adjustable luminance levels

Especificaciones
Item Min Typical Max Unit

Voltage 3.3 5.0 5.5 VDC

Current 0.2 27 80 mA

Dimensions 42x24x14 mm

Net Weight 7±1 g

Grove interface - Can be connected to digital port on Grove - Base Shield.

4 - digit display - Common anode digital tube.

Pin definition: CLK DIO VCC GND

Download the 4-Digit Display library and TimerOne library. Unzip and put them in the libraries file
of Arduino IDE by the path: ..\arduino-1.0\libraries.

Correr los programas de ejemplo de las librería DigitalTube

a. ClockDisplay
b. NumberFlow
c. Stopwatch
III. MAX7219

It’s a integrated circuit from Maxim are for driving either 64 individual Led's, or up to 8 digits of 7-
segment displays. The drivers implement a SPI compatible slave interface that can be controlled
from the Arduino using only 3 of the digital output pins. An extensive datasheet for the IC's is
available from the Maxim homepage. Since both chips are very similar, I will use the term
MAX72XX for both the MAX7221 and the MAX7219.

Un circuito de ejemplo puede ser el siguiente:


#define Rb5 7 // CS

#define Rb6 8 // DATA

#define Rb7 9 // CLK

void setup() {

pinMode(Rb5, OUTPUT);

pinMode(Rb6, OUTPUT);

pinMode(Rb7, OUTPUT);

void loop() {

init_MAX7219();

int digit;

int count = 9999;

// convert to BCD send to MAX7219

for (int i=0; i<=count; i++) {

int j = i;

// get 1st digit of j

digit = j % 10; // MOD J

writeMAX7219(1, digit);

// get 2nd digit of j

j = j / 10;

digit = j % 10; // MOD j

writeMAX7219(2, digit);

// get 3rd digit of j


j = j / 10;

digit = j % 10; // MOD j

writeMAX7219(3, digit);

// get 4th digit of j

j = j / 10;

digit = j % 10; // MOD j

writeMAX7219(4, digit);

delay(200);

} // end for

// shift data to MAX7219

// Rb7 -> CLK, Rb6 -> DATA, Rb5 -> CS not

void ssrOut(unsigned char val) {

int j;

for(j=1; j<=8; j++) { // shift out MSB first

unsigned char temp = val & 0x80; // MSB out first

if (temp == 0x80) digitalWrite(Rb6, 1); // Rb6 DATA

else digitalWrite(Rb6, 0);

digitalWrite(Rb7, 1);

delayMicroseconds(20);

digitalWrite(Rb7, 0);

val = val << 1; // shift one place left

} // next j

}
void pulseCS(void) {

digitalWrite(Rb5, 1);

delay(1);

digitalWrite(Rb5, 0);

void init_MAX7219(void) {

digitalWrite(Rb5, 0); // CS NOT

// set decode mode

ssrOut(0x09); // address

// ssrOut(0x00); // no decode

ssrOut(0xFF); // 4-bit BCD decode eight digits

pulseCS();

// set intensity

ssrOut(0x0A); // address

ssrOut(0x0D); // 5/32s

pulseCS();

// set scan limit 0-7

ssrOut(0x0B); // address

// ssrOut(0x07); // 8 digits

ssrOut(0x03); // 4 digits

pulseCS();
// clear MAX7219

for(int i=1; i<=8; i++) {

ssrOut(i);

ssrOut(0x00);

pulseCS();

// set for normal operation

ssrOut(0x0C); // address

// ssrOut(0x00); // Off

ssrOut(0x01); // On

pulseCS();

void writeMAX7219(char address, char data) {

if ((address < 1) || (address > 8)) return;

ssrOut(address); // valid numbers 1-8

ssrOut(data);

pulseCS();

II. Entradas analógicas


Uso de Potenciómetro en Arduino
Junto con los pines digitales, Arduino también tiene 6 pines que se pueden
utilizar para entrada analógica. Estas entradas reciben un voltaje (de 0 a 5
voltios) y lo convierten en un número digital entre 0 (0 voltios) y 1024 (5
voltios) (10 bits de resolución). Un dispositivo muy útil que explota estas
entradas es un potenciómetro (también llamado una resistencia variable).
Cuando está conectado con 5 voltios a través de sus patillas exteriores del pin
del medio leerá algún valor entre 0 y 5 voltios depende del ángulo al que se
gira (es decir, 2,5 voltios en el medio). A continuación, puede utilizar los
valores devueltos como una variable en el programa
Materiales:
1 Potenciometro de 10Kohms
1 Resistencia de 220ohms / 330ohms
1 LED Amarillo
Cables
Diagrama esquemático:

Implementación
El código queda de la siguiente manera:
/* Analog Input
* Demonstrates analog input by reading an analog sensor on analog
* pin 0 and turning on and off a light emitting diode(LED) connected to
digital pin 13.
* The amount of time the LED will be on and off depends on the value
obtained by
* analogRead().
*/
int sensorPin = 0; // select the input pin for the potentiometer
int ledPin = 13; // select the pin for the LED
int sensorValue = 0; // variable to store the value coming from the sensor
void setup() {
pinMode(ledPin, OUTPUT); //declare the ledPin as an OUTPUT:
}
void loop() {
sensorValue = analogRead(sensorPin);// read the value from the sensor:
digitalWrite(ledPin, HIGH); // turn the ledPin on
delay(sensorValue); // stop the program for <sensorValue> milliseconds:
digitalWrite(ledPin, LOW); // turn the ledPin off:
delay(sensorValue); // stop the program for for <sensorValue> milliseconds:
}

Se muestra una imagen del circuito implementado:


Lectura de voltaje analógico
Este ejemplo muestra cómo leer una entrada analógica en el pin 0, convertir
los valores de analogRead () en tensión, e imprimirlo al monitor serial.
Materiales
• Arduino Board
• a variable resistor, like a potentiometer

Al girar el eje del potenciómetro, se cambia la cantidad de resistencia a cada


lado del control que está conectado al pin central del potenciómetro. Esto
cambia el voltaje en el pin central. Cuando la resistencia entre el centro y el
lado conectado a 5 voltios es cercana a cero (y la resistencia en el otro lado
es cerca de 10 Kohms), el voltaje en la patilla central se acerca a 5 voltios.
Cuando las resistencias se invierten, la tensión en la patilla central se acerca a
0 voltios, o tierra. Esta tensión es la tensión analógica que estás leyendo
como una entrada.
Arduino tiene un circuito interno llamado convertidor analógico-a-digital
(ADC) que lee este cambio de voltaje y lo convierte en un número entre 0 y
1023. Cuando el eje del potenciometro gira completamente en una dirección,
hay 0 voltios en un pin, y el valor de entrada es 0. Cuando el eje se gira todo
el camino en la dirección opuesta, hay 5 voltios que van a la clavija y el valor
de entrada es 1023. En el medio, analogRead () devuelve un número entre 0
y 1023 que es proporcional a la cantidad de voltaje que se aplica al pin.
Esquematico

Codigo
Serial.begin(9600);
int sensorValue = analogRead(A0);

Para cambiar los valores de 0 a 1023 a un rango que corresponde a la tensión


del pin está leyendo, usted tendrá que crear otra variable, un float, y hacer
un poco de matemáticas. Para escalar los números comprendidos entre 0.0 y
5.0, se divide por 5,0 1023,0 y que se multiplican por sensorValue:
float voltage= sensorValue * (5.0 / 1023.0);
Serial.println(voltage)
Ahora, al abrir el monitor serial en el entorno de desarrollo Arduino
(haciendo clic en el botón a la derecha del botón "Upload" en la cabecera del
programa), debería ver un flujo constante de números que van desde 0,0
hasta 5,0. A medida que gira el eje, los valores cambiarán, correspondiente a
la tensión de entrada en pin A0.
/*
ReadAnalogVoltage
Reads an analog input on pin 0, converts it to voltage, and prints the result
to the serial monitor.
Attach the center pin of a potentiometer to pin A0, and the outside pins to
+5V and ground.
This example code is in the public domain.
*/

// the setup routine runs once when you press reset:


void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}

// the loop routine runs over and over again forever:


void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 -
5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage);
}

Las figuras que muestran el funcionamiento del circuito son:


Circuito con LDR

En el presente circuito se mostraran las características del LDR y su uso en un


circuito en Arduino. Mientras que conseguir la entrada de un potenciómetro
puede ser útil para humanos experimentos controlados, ¿qué es lo que
utilizamos cuando queremos un experimento controlado ambientalmente?
Se utiliza exactamente los mismos principios pero en lugar de un
potenciómetro (resistencia basada en torsión ) se utiliza una foto resistencia
(resistencia basada en la luz). Arduino no puede directamente medir la
resistencia (se detecta voltaje), así que se crea un divisor de tensión
(http://ardx.org/VODI). El voltaje exacto en el pin de detección es calculable,
pero para los propósitos de esta experiencia(sólo sensor de luz relativa) se
puede experimentar con los valores y ver lo que funciona para nosotros. Un
valor bajo se producirá cuando el sensor está bien iluminado, mientras que
un valor alto se producirá cuando está en la oscuridad.

El diagrama pictorico sera el siguiente:


El codigo que muestra el funcionamiento de este circuito esta a continuacion:
/*
* A programa that will change the
* intensity of an LED based on the amount of
* light incident on the photo resistor.
*
*/

//PhotoResistor Pin
int lightPin = 0; //the analog pin the photoresistor is connected to
//the photoresistor is not calibrated to any units so
//this is simply a raw sensor
//value (relative light)
//LED Pin
int ledPin = 9;//the pin the LED is connected to we are controlling brightness
so
//we use one of the PWM (pulse
//width modulation pins)
void setup()
{
pinMode(ledPin, OUTPUT); //sets the led pin to output
}

/*
* loop() - this function will start after setup
* finishes and then repeat
*/
void loop()
{
int lightLevel = analogRead(lightPin); //Read the lightlevel
lightLevel = map(lightLevel, 0, 900, 0, 255); //adjust the value 0 to 900 to 0
to 255
lightLevel = constrain(lightLevel, 0, 255);
//make sure the value is betwween 0 and 255
analogWrite(ledPin, lightLevel); //write the value
}

Invertir la respuesta:
Tal vez sería más interesante una respuesta opuesta. Eso se puede hacer
fácilmente ya que sólo se cambiaria:

analogWrite(ledPin, lightLevel); ----> analogWrite(ledPin, 255 - lightLevel);

Upload and watch the response change:

Luces nocturnas
En lugar de controlar el brillo del LED en respuesta a la luz, puede activar o
desactivar el led, basándose en un valor umbral. Cambie el código de loop ()
con.

void loop(){
int threshold = 300;
if(analogRead(lightPin) > threshold){
digitalWrite(ledPin, HIGH);
}else{
digitalWrite(ledPin, LOW);
}
}

You might also like