--- 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/> ![](https://cdn.sparkfun.com/assets/c/8/5/b/e/51c495ebce395f1b5a000000.png) Analog signal plots are smooth:<br/> ![](https://cdn.sparkfun.com/assets/3/7/6/6/0/51c48875ce395f745a000000.png) Digitaly encoded signals are discrete representation of analog values with step that vary their size depending on the resolution:<br/> ![](https://cdn.sparkfun.com/assets/0/2/8/4/6/51c85fbece395fbc03000000.png) Depending on the amount of bits we use we have a more precise curve. ![](http://pediaa.com/wp-content/uploads/2015/08/Difference-Between-Analog-and-Digital-Signals-A2D_2_bit_vs_3_bit.jpg) ### 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. ![](https://i.imgur.com/1bCNhoa.png) ### Input analógico Leyendo un potenciometro con [analogRead()](https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/) ![](https://i.imgur.com/sr6fs4J.png) ~~~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/) ![](https://i.imgur.com/AQssrUm.png) ~~~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 ![](https://i.imgur.com/aoce8uz.png) ~~~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 ![](https://cdn.sparkfun.com/assets/learn_tutorials/4/7/2/Arduino101_GooglePhotoCell_bb3.png =500x) ```arduino void setup() { pinMode(A0, INPUT); Serial.begin(115200); } void loop() { int light = analogRead(A0); Serial.println(light); delay(50); } ``` ![](https://i.imgur.com/wRjxyBJ.png) ### Sonido Microphone ![](https://i.imgur.com/NPPuRNi.png) ```arduino void setup() { pinMode(A0, INPUT); Serial.begin(115200); } void loop() { int noise = analogRead(A0); Serial.println(noise); delay(50); } ``` ![](https://www.smarthome-tricks.de/wp-content/uploads/2019/03/esp8266_arduinoide_plotter_00.png) ### Touch Capacitive sensors **¿Que es una librería?** Instalación en Arduino IDE de la librería Capacitive Sensor ![](https://i.imgur.com/5f4X03E.png) Circuito con una resistencia de 1M ![](https://i.imgur.com/wxsJ4Yh.png) ~~~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); } ~~~ ![](https://i.imgur.com/06TUsCk.png) ### Posición Ultrasonic sensor ![](https://i.imgur.com/GORFGcd.png) ~~~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 ![](https://therandombit.files.wordpress.com/2010/12/speaker2_fritzing.png) ```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 ![](https://cdn-learn.adafruit.com/assets/assets/000/002/310/medium800/learn_arduino_fritzing_sweep.jpg?1396781578) ```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 ![](https://i.imgur.com/R7wpNF6.png) ![](https://i.imgur.com/dqFnf97.png) 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 ![](https://miro.medium.com/max/1200/1*8j2PmhExz4q87OoddaH7ag.png) 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. ![](https://wcs.smartdraw.com/flowchart/img/basic-symbols.jpg?bn=1510011061) ![](https://d2slcw3kip6qmk.cloudfront.net/marketing/pages/chart/examples/flowchart-templates/simple-flowchart.svg) 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!"); } } } } ~~~ ![](https://hackmd.io/_uploads/SyjoaNTb6.png =300x)