---
tags: salle, PMA, creatividad, done
---
# Introducción a la electrónica II
[TOC]
## Analog <> Digital [*](https://learn.sparkfun.com/tutorials/analog-vs-digital)
To allow our devices to be aware of their surroundings we use sensors that translate the information of the enviroment in electric signals. This signals are normally analog, and because the electronic systems (mostly microcontrollers) we use to process this information and take descitions live mostly in digital world we need to translate analog values in digital ones.
To express or actuate in the real world our devices need to do the oposite: convert our digital information in analog outputs (leds, motors, etc)
Our world is analog, it has an infinite number of values for light, sound, etc.
Digital signals are finite, depending on the resolution we use we have more or less values.
Ploting signals against time let us understand them
Digital binary signals only have two posible values:<br/>

Analog signal plots are smooth:<br/>

Digitaly encoded signals are discrete representation of analog values with step that vary their size depending on the resolution:<br/>

Depending on the amount of bits we use we have a more precise curve.

### Converting the analog world to digital: The ADC [*](https://learn.sparkfun.com/tutorials/analog-to-digital-conversion)
Arduino [analogRead](https://www.arduino.cc/en/Reference/AnalogRead) function.
ADC resolution: Arduino uno 10 bits -> 1024 different values.
Converting digital value to a voltage:
digital value | voltage | formula
--- | --- | ---
1023 | 5v | 5 / (1023/1023)
512 | 2.5v | 5 / (1023/512)
256 | 1.25v | 5 / (1023/256)
128 | 0.625 | 5 / (1023/128)
### From digital to analog: PWM
Como el Arduino sólo puede tener dos valores posibles como outputs (LOW y HIGH) la única manera de emitir un valor análogo es alternar la salida entre LOW y HIGH a una velocidad suficientemente alta como para que no alcancemos a ver los cambios, y lo que vemos es el promedio de los dos valores.

### Input analógico
Leyendo un potenciometro con [analogRead()](https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/)

~~~arduino
void setup() {
Serial.begin(115200);
}
void loop() {
int value = analogRead(A0);
Serial.println(value);
delay(50);
}
~~~
:::info
Explicar el uso del Arduino **Serial Monitor y Serial Plotter**
:::
### Output analógico
Usar PWM para hacer fade con un led utilizando la función [analogWrite](https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/)

~~~arduino
int ledPin = 9;
int bright = 0;
int fadeAmount = 5;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
analogWrite(ledPin, bright);
bright = bright + fadeAmount;
if (bright >= 255 || bright <= 0) {
fadeAmount = -fadeAmount;
}
delay(30);
}
~~~
### Input y output analógico

~~~arduino
int ledPin = 9;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
int val = analogRead(A0);
analogWrite(ledPin, val / 4);
}
~~~
## Sensores
Introducción a conceptos de **Sensores**.
### Luz
Light dependant resistor

```arduino
void setup() {
pinMode(A0, INPUT);
Serial.begin(115200);
}
void loop() {
int light = analogRead(A0);
Serial.println(light);
delay(50);
}
```

### Sonido
Microphone

```arduino
void setup() {
pinMode(A0, INPUT);
Serial.begin(115200);
}
void loop() {
int noise = analogRead(A0);
Serial.println(noise);
delay(50);
}
```

### Touch
Capacitive sensors
**¿Que es una librería?**
Instalación en Arduino IDE de la librería Capacitive Sensor

Circuito con una resistencia de 1M

~~~arduino
#include <CapacitiveSensor.h>
CapacitiveSensor cs_4_2 = CapacitiveSensor(4,2); // 10M resistor between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil if desired
void setup() {
Serial.begin(115200);
}
void loop() {
long sensor = cs_4_2.capacitiveSensor(30);
Serial.println(sensor);
// if (sensor > 200) {
// Serial.println("Tocando!!!");
// } else {
// Serial.println("nada!!!");
// }
delay(10);
}
~~~

### Posición
Ultrasonic sensor

~~~clike
// Define pin's number
#define echoPin D7 // Pin number connected to Echo
#define trigPin D8 // Pin number connected to Trigger
// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(115200);
}
void loop() {
// Clears the trigPin condition
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
// Displays the distance (in cm) on the Serial Monitor
Serial.println(distance);
delay(100);
}
~~~
## Actuadores
### Sonido
**Some Music**
Piano con Comunicación Serial por USB

```arduino
int buzzPin = 6;
int noteNum = 7;
char keys[] = {'d','r','m','f','s','l','i'};
int freq[] = {262,294,330,369,391,440,493};
void setup() {
pinMode(buzzPin, OUTPUT);
Serial.begin(115200);
}
void loop() {
if (Serial.available()) {
char n = Serial.read();
if (n == '.') noTone(pin);
else {
for (int i=0; i<noteNum; i++) {
if (n == keys[i]) {
tone(pin, freq[i]);
Serial.println(keys[i]);
}
}
}
delay(200);
}
}
/*
* d-do 262
* r-re 294
* m-mi 330
* f-fa 369
* s-sol 391
* l-la 440
* s-si 493
*/
// La cucaracha
// d.d.d.f..l..d.d.d.f..l..f.f.m.m.r.r.ddd..d.d.d.mm.s.
```
### Movimiento
Servomotores

```arduino
#include <Servo.h>
int servoPin = 9;
int angle = 0;
Servo servo;
void setup() {
servo.attach(servoPin);
}
void loop() {
// scan from 0 to 180 degrees
for(angle = 0; angle < 180; angle++) {
servo.write(angle);
delay(15);
}
// now scan back from 180 to 0 degrees
for(angle = 180; angle > 0; angle--) {
servo.write(angle);
delay(15);
}
}
```
### Luz
Addressable leds
Adafruit [Uber Guide](https://learn.adafruit.com/adafruit-neopixel-uberguide/the-magic-of-neopixels)
Instalar la librería Neopixel


Para probar se puede cargar el ejemplo **Strandtest** de la librería de Neopixel. Solamente hay que modificar el Pin al que conectamos los datos de los leds y el numero de leds que vamos a controlar.
Para calcular la energía total que le debemos proveer al nuestra tira de leds tenemos que calcular 20mAh x led:
_300 leds = 300 x 20mAh = 6000mAh = 6 Amperios_
El arduino puede proveer por el pin de 5v 500mAh, esto quiere decir que podemos darle energía a alrededor de 25 leds sin tener problemas.
Ejemplo para la tira completa con un led moviendose a lo largo.
~~~arduino
#include <Adafruit_NeoPixel.h>
#define LED_PIN 6
#define LED_COUNT 20
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
void setup() {
strip.begin();
strip.show();
strip.setBrightness(128); // Set BRIGHTNESS to about 1/5 (max = 255)
}
void loop() {
for(int i=0; i<strip.numPixels(); i++) {
strip.clear();
strip.setPixelColor(i, 0, 50, 255);
strip.show();
delay(20);
}
}
~~~
## Comunicación
**Introducción a las comunicaciones digitales** Capas de redes, protocolos, encripción.
* Comunicaciones digitales
* Tecnologías
* Inalámbricas [video](https://www.youtube.com/watch?v=METB1o4UAT8)
* Red móvil
* Wifi 802.11
* Radio frecuencias
* Bluetooth
* Alámbricas
* Telégrafo
* Teléfono
* Ethernet
* Fibra óptica
* Protocolos
* Clave morse (algún ejercicio que demuestre la separación entre el protocolo y la red física)
* Serial (UART)
* TCP/IP
* HTTP
* MQTT
## From ideas to code
### Funciones básicas de Arduino
* Internal arduino functions
* [pinMode()](https://www.arduino.cc/en/Reference/PinMode)
* [digitalWrite()](https://www.arduino.cc/en/Reference/DigitalWrite)
* [digitalRead()](https://www.arduino.cc/en/Reference/DigitalRead)
* [delay()](https://www.arduino.cc/en/Reference/Delay)
* [analogRead()](https://www.arduino.cc/en/Reference/AnalogRead)
* [analogWrite()](https://www.arduino.cc/en/Reference/AnalogWrite) PWM
* [millis()](https://www.arduino.cc/en/Reference/Millis)
* Arduino [reference](https://www.arduino.cc/reference/en/)
* Herramientas en programación
* Condicionales
* [if...then](https://www.arduino.cc/reference/en/language/structure/control-structure/if/) → [else](https://www.arduino.cc/reference/en/language/structure/control-structure/else/)
* [switch...case](https://www.arduino.cc/reference/en/language/structure/control-structure/switchcase/)
* Loops
* [for](https://www.arduino.cc/reference/en/language/structure/control-structure/for/)
* [do...while](https://www.arduino.cc/reference/en/language/structure/control-structure/dowhile/)
### Lenguajes de programación
Alto y bajo nivel

Compilados e interpretados
### Algoritmos y diagramas de flujo
>Un Algoritmo es un conjunto de instrucciones o reglas definidas y no-ambiguas, ordenadas y finitas que permite, típicamente, solucionar un problema, realizar un cómputo, procesar datos y llevar a cabo otras tareas o actividades. Dados un estado inicial y una entrada, siguiendo los pasos sucesivos se llega a un estado final y se obtiene una solución.
{%youtube 6hfOvs8pY1k%}
#### Representacion de algoritmos en diagramas de flujo.


Ejemplo de un algoritmo para prender o apagar la calefaccion con base en la temperatura y la presencia de personas.
```flow
st=>start: Start
e=>end: Turn ON heating
op=>operation: INPUT detect people
op2=>operation: detect people
cond=>condition: temp < 20 ?
cond2=>condition: people > 1 ?
in=>operation: INPUT Read Temp
st->in->cond->op->cond2
cond(yes)->op
cond(no)->in
cond2(yes)->e
cond2(no)->in
```
:::success
**Ejercicio**
Dibujar el diagrama de flujo y escribir el código:
* Push button y led
* Si el led está apagado: al picar el botón se enciende.
* Si el led está prendido: al picar el botón se apaga.
:::
~~~=arduino
int boton_pin = 2;
int led_pin = 9;
int boton_previo = false;
bool estado_led = false;
void setup() {
pinMode(boton_pin, INPUT_PULLUP);
pinMode(led_pin, OUTPUT);
Serial.begin(115200);
digitalWrite(led_pin, estado_led);
}
void loop() {
// Leer el boton
bool boton = digitalRead(boton_pin);
// si boton_previo es diferente a boton
if (boton_previo != boton) {
Serial.print("El botón cambio a: ");
Serial.println(boton);
// boton_previo = boton
boton_previo = boton;
// esta el boton presionado?
if (boton == true) {
// esta el led encendido?
if (estado_led == true) {
// apagar led
digitalWrite(led_pin, false);
estado_led = false;
Serial.println("Apagando el led!");
// si esta apagado
} else {
// prender led
digitalWrite(led_pin, true);
estado_led = true;
Serial.println("Prendiendo el led!");
}
}
}
}
~~~
