├── 010_arduino-iniciacion ├── 00 - Introducción │ ├── 01 - instalar-ide-arduino.md │ ├── 02 - nuestro-primer-programa-en-arduino.md │ └── 04 - referencia-lenguaje-arduino.md ├── 01 - Entradas y salidas │ ├── 00 - entradas-digitales-en-arduino.md │ ├── 01 - salidas-digitales-en-arduino.md │ ├── 02 - entradas-analogicas-en-arduino.md │ ├── 03 - salidas-analogicas-pwm-en-arduino.md │ ├── 05 - que-son-y-como-usar-interrupciones-en-arduino.md │ └── 06 - debounce-interrupciones-arduino.md ├── 02 - Electrónica básica │ ├── 00 - encender-un-led-con-arduino.md │ ├── 01 - leer-un-pulsador-con-arduino.md │ ├── 02 - lectura-de-una-resistencia-variable-con-arduino.md │ ├── 03 - lectura-de-un-potenciometro-con-arduino.md │ └── 05 - guardar-variables-entre-reinicios-con-arduino-y-la-memoria-no-volatil-eeprom.md ├── 05 - Comunicación │ ├── 00 - arduino-puerto-serie.md │ ├── 01 - arduino-serial-plotter.md │ ├── 02 - arduino-i2c.md │ └── 03 - arduino-spi.md └── 06 - Comunicar con un PC │ ├── 00 - comunicar-arduino-con-c.md │ └── 01 - controlar-arduino-con-python-y-la-libreria-pyserial.md ├── 020_arduino-intermedio ├── 00 - Entradas y salidas │ ├── 01 - usar-un-optointerruptor-con-arduino.md │ ├── 02 - arduino-encoder-rotativo.md │ ├── 03 - como-usar-extensor-i2c-tca9548a-y-arduino.md │ ├── 04 - arduino-mosfet-irf520n.md │ ├── 05 - arduino-salida-rele.md │ ├── 06 - arduino-rele-estado-solido-ssr.md │ ├── 07 - mas-salidas-y-entradas-en-arduino-con-multiplexor-cd74hc4067.md │ ├── 08 - mas-pines-digitales-con-arduino-y-el-expansor-es-i2c-pcf8574.md │ ├── 09 - como-controlar-hasta-16-gpio-por-i2c-con-extensor-pcf8575-y-arduino.md │ ├── 10 - entrada-analogica-adc-de-16-bits-con-arduino-y-ads1115.md │ ├── 11 - salida-analogica-real-con-arduino-y-dac-de-12bits-mcp4725.md │ └── 12 - resistencia-variable-con-arduino-y-digipot-mcp41xxx.md ├── 01 - Motores │ ├── 00 - controlar-un-servo-con-arduino.md │ ├── 01 - controlar-un-servo-de-rotacion-continua-con-arduino.md │ ├── 02 - controlar-16-servos-o-16-salidas-pwm-en-arduino-con-pca9685.md │ ├── 03 - hasta-32-de-servos-en-arduino-con-el-controlador-usc-32.md │ ├── 04 - arduino-motor-corriente-continua-l298n.md │ ├── 05 - controla-motores-de-gran-potencia-con-arduino-y-bts7960.md │ ├── 06 - arduino-motor-dc-tb6612fng.md │ ├── 07 - motores-paso-paso-arduino-driver-a4988-drv8825.md │ ├── 08 - motor-paso-paso-28byj-48-arduino-driver-uln2003.md │ └── 09 - motores-paso-a-paso-en-silencio-con-arduino-y-los-driver-tmc2100-tmc2130-y-tmc2208.md ├── 02 - Actuadores │ ├── 00 - arduino-actuador-lineal.md │ ├── 01 - arduino-actuador-electromagnetico.md │ ├── 02 - diodo-laser-arduino.md │ ├── 03 - electroiman-arduino.md │ ├── 04 - arduino-peltier.md │ └── 05 - controlar-un-ventilador-con-arduino.md ├── 03 - Optico │ ├── 00 - medir-nivel-luz-con-arduino-y-fotoresistencia-ldr.md │ ├── 01 - medir-cantidad-de-luxes-con-arduino-y-el-luxometro-bh1750.md │ ├── 02 - arduino-detector-lineas-tcrt5000l.md │ ├── 03 - detector-llama-arduino.md │ ├── 04 - medir-color-arduino-colorimetro-tcs3200.md │ └── 05 - arduino-sensor-color-rgb-tcs34725.md ├── 04 - Distancia │ ├── 00 - medir-distancia-con-arduino-y-sensor-de-ultrasonidos-hc-sr04.md │ ├── 01 - detectar-obstaculos-con-sensor-infrarrojo-y-arduino.md │ ├── 02 - arduino-sharp-gp2y0a02yk0f.md │ ├── 03 - medir-distancia-con-arduino-y-el-sensor-gp2y0e03.md │ └── 04 - arduino-sensor-distancia-vl53l0x.md ├── 05 - Inercial │ ├── 00 - medir-inclinacion-con-arduino-y-sensor-tilt-sw-520d.md │ ├── 01 - arduino-acelerometro-adxl345.md │ ├── 02 - arduino-acelerometro-mma7455.md │ ├── 03 - arduino-orientacion-imu-mpu-6050.md │ ├── 04 - brujula-magnetica-con-arduino-compass-digital-hmc5883.md │ ├── 05 - usar-arduino-con-los-imu-de-9dof-mpu-9150-y-mpu-9250.md │ └── 06 - usar-arduino-y-el-imu-9-ejes-l3gd20-lsm303d.md ├── 06 - Movimiento │ ├── 00 - medir-vibracion-con-arduino-y-sensor-sw-18020p.md │ ├── 01 - detector-de-movimiento-con-arduino-y-sensor-pir.md │ └── 02 - arduino-detector-movimiento-rcwl-0516.md ├── 07 - Tactil _ Gestos │ ├── 00 - interruptor-touchless-con-arduino-y-sensor-capacitivo.md │ ├── 01 - arduino-mpr121.md │ └── 02 - detectar-gestos-con-arduino-y-sensor-apds-9960.md ├── 08 - Ambiental │ ├── 00 - medir-temperatura-con-arduino-y-termistor-mf52.md │ ├── 01 - medir-temperatura-con-arduino-y-sensor-lm35.md │ ├── 02 - arduino-dht11-dht22.md │ ├── 03 - usar-el-sensor-de-temperatura-interno-de-arduino.md │ ├── 04 - medir-presion-del-aire-y-altitud-con-arduino-y-barometro-bmp180.md │ ├── 05 - medir-temperatura-y-presion-barometrica-con-arduino-y-bmp280.md │ ├── 06 - arduino-y-el-termometro-infrarrojo-a-distancia-mlx90614.md │ ├── 07 - arduino-detector-gas-mq.md │ ├── 08 - sensor-ambiental-arduino-bme280.md │ ├── 09 - sensor-de-calidad-ambiental-con-arduino-y-bme680.md │ └── 10 - medir-calidad-del-aire-y-co2-con-ccs811-y-arduino.md ├── 09 - Agua _ Liquidos │ ├── 00 - arduino-lluvia.md │ ├── 01 - arduino-humedad-suelo-fc-28.md │ ├── 02 - sensor-de-humedad-del-suelo-capacitivo-y-arduino.md │ ├── 03 - temperatura-liquidos-arduino-ds18b20.md │ ├── 04 - caudal-consumo-de-agua-con-arduino-y-caudalimetro.md │ └── 05 - bomba-de-agua-con-arduino.md ├── 10 - Intensidad _ Tension │ ├── 00 - medir-tension-intensidad-y-potencia-con-arduino-y-ina219.md │ ├── 01 - arduino-intensidad-consumo-electrico-acs712.md │ ├── 02 - arduino-sensor-corriente-sct-013.md │ ├── 03 - medir-voltajes-de-hasta-25v-con-arduino-y-fz0430.md │ ├── 04 - medir-tensiones-de-220v-230v-con-arduino-y-transformador.md │ └── 05 - arduino-cruce-por-cero-h11aa1.md ├── 11 - Display │ ├── 00 - matriz-led-arduino-max7219.md │ ├── 01 - arduino-lcd-hitachi-hd44780.md │ ├── 02 - arduino-lcd-i2c.md │ ├── 03 - conectar-arduino-a-un-display-lcd-nokia-5110.md │ ├── 04 - conectar-arduino-a-una-pantalla-oled-de-0-96.md │ └── 05 - conectar-arduino-a-una-pantalla-tft.md ├── 12 - Comunicacion │ ├── 00 - conectar-arduino-por-bluetooth-con-los-modulos-hc-05-o-hc-06.md │ ├── 01 - arduino-ethernet-shield-w5100.md │ ├── 02 - arduino-ethernet-enc28j60.md │ ├── 03 - comunicacion-inalambrica-en-arduino-con-modulos-rf-433mhz.md │ ├── 04 - comunicacion-inalambrica-a-2-4ghz-con-arduino-y-nrf24l01.md │ ├── 05 - arduino-rs485-max485.md │ ├── 06 - comunicacion-rf-385-433-y-815mhz-con-arduino-y-cc1101.md │ └── 07 - arduino-wifi-esp8266-esp01.md ├── 13 - Controles │ ├── 00 - arduino-teclado-matricial.md │ ├── 01 - arduino-joystick.md │ ├── 02 - arduino-mando-a-distancia-infrarrojo.md │ ├── 03 - arduino-y-mando-a-distancia-de-4-canales-315mhz-ic2262.md │ ├── 04 - conectar-emisora-radio-control-con-arduino.md │ ├── 05 - arduino-mando-wii-wiichuck.md │ └── 06 - controla-arduino-con-el-mando-inalambrico-de-la-ps2.md ├── 14 - Magnetico │ ├── 00 - usar-un-interruptor-magnetico-con-arduino-magnetic-reed.md │ ├── 01 - medir-campos-magneticos-arduino-hall-49e.md │ ├── 02 - detectar-campos-magneticos-con-arduino-y-sensor-hall-a3144.md │ └── 03 - detector-de-metales-con-arduino-y-sensor-inductivo.md ├── 15 - Memoria │ ├── 00 - arduino-eeprom-externa-i2c-at24c256.md │ └── 01 - tarjeta-micro-sd-arduino.md ├── 16 - Tiempo │ └── 00 - reloj-y-calendario-en-arduino-con-los-rtc-ds1307-y-ds3231.md ├── 17 - RFID _ NFC │ ├── 00 - arduino-rfid-mifare-rc522.md │ └── 01 - arduino-nfc-pn532.md ├── 18 - Biometrico │ ├── 00 - lector-de-huellas-dactilares-con-arduino-y-sensor-fpm10a.md │ └── 01 - pulsimetro-y-oximetro-con-arduino-y-max30102.md ├── 19 - Sonido │ ├── 00 - reproducir-sonidos-arduino-buzzer-pasivo-altavoz.md │ ├── 01 - arduino-buzzer-activo.md │ ├── 02 - detectar-sonido-con-arduino-y-microfono-ky-038.md │ ├── 03 - medir-sonido-con-arduino-y-microfono-amplificado-max9812.md │ └── 04 - arduino-mp3-dfplayer-mini.md └── 20 - Gps │ └── 00 - localizacion-gps-con-arduino-y-los-modulos-gps-neo-6.md ├── 030_arduino-avanzado ├── 00 - Programación e IDEs │ ├── 01 - programar-arduino-con-atom-y-platformio-ide.md │ ├── 03 - como-programar-arduino-con-visual-studio-code-y-plaftormio.md │ └── 04 - programar-arduino-con-eclipse.md ├── 01 - Puerto serie avanzado │ ├── 00 - convertir-texto-a-numero-arduino.md │ ├── 01 - cadenas-de-texto-puerto-serie-arduino.md │ ├── 02 - enviar-recibir-numeros-puerto-serie-arduino.md │ ├── 03 - array-puerto-serie-arduino.md │ ├── 04 - arduino-array-separado-comas.md │ ├── 05 - arduino-bytes-puerto-serie.md │ ├── 06 - estructuras-puerto-serie-arduino.md │ ├── 07 - arduino-caracteres-control-puerto-serie.md │ └── 08 - puerto-serie-avanzado-arduino.md ├── 02 - Filtrado │ ├── 00 - reducir-ruido-sensores-arduino-muestreo-multiple.md │ ├── 01 - arduino-filtro-media-movil.md │ ├── 02 - arduino-mediana.md │ ├── 03 - arduino-filtro-mediana-rapido.md │ ├── 04 - arduino-paso-bajo-exponencial.md │ └── 05 - arduino-paso-banda.md ├── 03 - Limpieza de código │ ├── 00 - como-y-por-que-usar-clases-abstrastas-en-arduino.md │ ├── 01 - 4-consejos-para-programar-codigo-mas-limpio-en-arduino.md │ ├── 02 - ponemos-a-prueba-como-de-listo-es-el-compilador-de-arduino.md │ └── 03 - solucion-al-ejercicio-de-codigo-limpio-y-ordenado-en-c-para-arduino.md ├── 04 - Estructuras de datos y algoritmos │ ├── 00 - arduino-array-dinamico.md │ ├── 01 - arduino-linked-list.md │ ├── 02 - buffer-circular-arduino.md │ ├── 03 - arduino-bubble-sort.md │ ├── 04 - arduino-quicksort.md │ └── 05 - arduino-checksum.md ├── 05 - Teoría de control │ ├── 01 - arduino-umbral.md │ ├── 05 - como-implementar-un-controlador-pid-en-arduino.md │ └── 06 - como-hacer-un-control-pid-de-iluminacion-constante-con-arduino.md ├── 06 - Automatización y robótica │ ├── 00 - multitarea-en-arduino-blink-sin-delay.md │ ├── 01 - maquina-de-estados-finitos-arduino.md │ ├── 02 - implementar-una-red-de-petri-en-arduino.md │ ├── 03 - resolver-robots-articulados-con-arduino.md │ ├── 04 - como-usar-freertos-en-arduino.md │ └── 05 - obtener-orientacion-y-altitud-ahrs-con-imu-9dof-y-rtimulib-arduino.md ├── 07 - Comunicación │ ├── 00 - arduino-json.md │ ├── 01 - enviar-y-recibir-mensajes-por-mqtt-con-arduino-y-la-libreria-pubsubclient.md │ ├── 02 - como-conectar-dos-arduino-por-bus-i2c.md │ └── 03 - arduino-i2c-json.md └── 08 - Hardware │ ├── 00 - analogicas-mas-precisas.md │ ├── 01 - como-cambiar-la-frecuencia-de-un-pwm-en-arduino.md │ ├── 02 - como-usar-correccion-gamma-en-fuentes-de-luz-con-arduino.md │ ├── 03 - interrupciones-en-todos-los-pines-de-arduino-con-pcint.md │ └── 04 - como-emular-un-teclado-o-un-raton-con-arduino.md ├── README.md └── img └── screenshot.png /010_arduino-iniciacion/00 - Introducción/01 - instalar-ide-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/instalar-ide-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Arduino IDE en Ubuntu/Linux Mint 8 | ```bash 9 | sudo apt-get install arduino 10 | ``` 11 | 12 | ```bash 13 | sudo rm -r /usr/share/arduino 14 | wget http://http://downloads.arduino.cc/arduino-1.5.4-linux64.tgz 15 | tar zxvf arduino-1.5.4-linux64.tgz 16 | sudo mv ./arduino-1.5.4 /usr/share/arduino 17 | ``` 18 | 19 | 20 | ## Fritzing 21 | ```bash 22 | sudo apt-get install fritzing 23 | ``` 24 | 25 | 26 | ## Oregano 27 | ```bash 28 | sudo apt-get install oregano 29 | ``` 30 | 31 | 32 | -------------------------------------------------------------------------------- /010_arduino-iniciacion/00 - Introducción/02 - nuestro-primer-programa-en-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/nuestro-primer-programa-en-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Estructura básica de programa 8 | ```csharp 9 | //Zona DECLARACIONES 10 | 11 | void setup() 12 | { 13 | // Zona funcion SETUP 14 | } 15 | 16 | void loop() 17 | { 18 | // Zona funcion LOOP 19 | } 20 | ``` 21 | 22 | 23 | ## Cargando un ejemplo 24 | ```csharp 25 | const int pinLED= 13; //asignar variable led como 13 26 | 27 | void setup() 28 | { 29 | pinMode(pinLED, OUTPUT); //definir pin 13 como salida 30 | } 31 | 32 | void loop() { 33 | digitalWrite(pinLED, HIGH); // encender LED 34 | delay(1000); // esperar un segundo 35 | digitalWrite(pinLED, LOW); // apagar LED 36 | delay(1000); // esperar un segundo 37 | } 38 | ``` 39 | 40 | 41 | -------------------------------------------------------------------------------- /010_arduino-iniciacion/01 - Entradas y salidas/00 - entradas-digitales-en-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/entradas-digitales-en-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Código en Arduino 8 | ```csharp 9 | int pin = 2; 10 | int value = 0; 11 | 12 | void setup() { 13 | Serial.begin(9600); //iniciar puerto serie 14 | pinMode(pin, INPUT); //definir pin como entrada 15 | } 16 | 17 | void loop(){ 18 | value = digitalRead(pin); //lectura digital de pin 19 | 20 | //mandar mensaje a puerto serie en función del valor leido 21 | if (value == HIGH) { 22 | Serial.println("Encendido"); 23 | } 24 | else { 25 | Serial.println("Apagado"); 26 | } 27 | delay(1000); 28 | } 29 | ``` 30 | 31 | 32 | -------------------------------------------------------------------------------- /010_arduino-iniciacion/01 - Entradas y salidas/01 - salidas-digitales-en-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/salidas-digitales-en-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Código 8 | ```cpp 9 | const int pin = 2; 10 | 11 | void setup() { 12 | Serial.begin(9600); //iniciar puerto serie 13 | pinMode(pin, OUTPUT); //definir pin como salida 14 | } 15 | 16 | void loop(){ 17 | digitalWrite(pin, HIGH); // poner el Pin en HIGH 18 | delay(1000); // esperar un segundo 19 | digitalWrite(pin, LOW); // poner el Pin en LOW 20 | delay(1000); // esperar un segundo 21 | } 22 | ``` 23 | 24 | ```cpp 25 | const int pin = 2; 26 | int option; 27 | 28 | void setup(){ 29 | Serial.begin(9600); 30 | pinMode(pin, OUTPUT); 31 | } 32 | 33 | void loop(){ 34 | //si existe información pendiente 35 | if (Serial.available()>0){ 36 | //leeemos la opcion 37 | char option = Serial.read(); 38 | if (option == '0' ) //si el valor es 0 39 | { 40 | digitalWrite(pin, LOW); //apagamos el pin 41 | } 42 | else if (option == '1' ) 43 | { 44 | digitalWrite(pin, HIGH); //encendemos el pin 45 | } 46 | delay(200); 47 | } 48 | } 49 | ``` 50 | 51 | 52 | -------------------------------------------------------------------------------- /010_arduino-iniciacion/01 - Entradas y salidas/02 - entradas-analogicas-en-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/entradas-analogicas-en-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Código en Arduino 8 | ```csharp 9 | const int sensorPin = A0; // seleccionar la entrada para el sensor 10 | int sensorValue; // variable que almacena el valor raw (0 a 1023) 11 | 12 | void setup() 13 | { 14 | Serial.begin(9600); 15 | } 16 | 17 | void loop() 18 | { 19 | sensorValue = analogRead(sensorPin); // realizar la lectura 20 | 21 | //mandar mensaje a puerto serie en función del valor leido 22 | if (sensorValue > 512) 23 | { 24 | Serial.println("Mayor que 2,5V"); 25 | } 26 | else 27 | { 28 | Serial.println("Menor que 2,5V"); 29 | } 30 | delay(1000); 31 | } 32 | ``` 33 | 34 | ```csharp 35 | const int sensorPin = A0; // seleccionar la entrada para el sensor 36 | int sensorValue; // variable que almacena el valor raw (0 a 1023) 37 | float value; // variable que almacena el voltaje (0.0 a 5.0) 38 | 39 | void setup() 40 | { 41 | Serial.begin(9600); 42 | } 43 | 44 | void loop() 45 | { 46 | sensorValue = analogRead(sensorPin); // realizar la lectura 47 | value = fmap(sensorValue, 0, 1023, 0.0, 5.0); // cambiar escala a 0.0 - 5.0 48 | 49 | Serial.println(value); // mostrar el valor por serial 50 | delay(1000); 51 | } 52 | 53 | // cambio de escala entre floats 54 | float fmap(float x, float in_min, float in_max, float out_min, float out_max) 55 | { 56 | return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; 57 | } 58 | ``` 59 | 60 | 61 | -------------------------------------------------------------------------------- /010_arduino-iniciacion/01 - Entradas y salidas/03 - salidas-analogicas-pwm-en-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/salidas-analogicas-pwm-en-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplo de código 8 | ```cpp 9 | const int analogOutPin = 5; // Analog output pin 10 | 11 | byte outputValue = 0; // valor del PWM 12 | 13 | void setup() { 14 | } 15 | 16 | void loop() { 17 | analogWrite(analogOutPin, outputValue); 18 | delay(10); 19 | outputValue++; 20 | } 21 | ``` 22 | 23 | ```cpp 24 | const int analogOutPin = 11; // Analog output pin that the LED is attached to 25 | byte outputValue = 0; 26 | 27 | void setup() 28 | { 29 | bitSet(DDRB, 5); // LED pin (13) 30 | bitSet(PCICR, PCIE0); // enable pin change interrupts on bank 0 31 | bitSet(PCMSK0, PCINT3); // enable PCINT3 (PB3) pin change interrupt 32 | } 33 | 34 | void loop() 35 | { 36 | analogWrite(analogOutPin, outputValue); 37 | delay(10); 38 | outputValue++; 39 | } 40 | 41 | ISR(PCINT0_vect) 42 | { 43 | if(bitRead(PINB, 3)) 44 | { 45 | bitSet(PORTB, 5); // LED on 46 | } 47 | else 48 | { 49 | bitClear(PORTB, 5); // LED off 50 | } 51 | } 52 | ``` 53 | 54 | ```cpp 55 | const int analogOutPin = 11; 56 | byte outputValue = 0; 57 | 58 | void setup() 59 | { 60 | Serial.begin(9600); // Iniciar puerto serie 61 | pinMode(ledPIN , OUTPUT); 62 | 63 | bitSet(DDRB, 5); // LED pin (13) 64 | bitSet(PCICR, PCIE0); // enable pin change interrupts on bank 0 65 | bitSet(PCMSK0, PCINT3); // enable PCINT3 (PB3) pin change interrupt 66 | } 67 | 68 | void loop() 69 | { 70 | if (Serial.available()>0) // Si hay datos disponibles 71 | { 72 | outputValue = Serial.read(); // Leemos la opción 73 | if(outputValue >= '0' && outputValue <= '9') 74 | { 75 | outputValue -= '0'; // Restamos '0' para convertir a un número 76 | outputValue *= 25; // Multiplicamos x25 para pasar a una escala 0 a 250 77 | analogWrite(ledPIN , outputValue); 78 | } 79 | } 80 | } 81 | 82 | ISR(PCINT0_vect) 83 | { 84 | if(bitRead(PINB, 3)) 85 | { 86 | bitSet(PORTB, 5); // LED on 87 | } 88 | else 89 | { 90 | bitClear(PORTB, 5); // LED off 91 | } 92 | } 93 | ``` 94 | 95 | 96 | -------------------------------------------------------------------------------- /010_arduino-iniciacion/01 - Entradas y salidas/05 - que-son-y-como-usar-interrupciones-en-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/que-son-y-como-usar-interrupciones-en-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Crear interrupciones en Arduino 8 | ```csharp 9 | attachInterrupt(interrupt, ISR, mode); 10 | ``` 11 | 12 | ```csharp 13 | attachInterrupt(digitalPinToInterrupt(pin), ISR, mode); 14 | ``` 15 | 16 | 17 | ## Haciendo parpadear un LED a través de interrupciones 18 | ```cpp 19 | const int emuPin = 10; 20 | 21 | const int LEDPin = 13; 22 | const int intPin = 2; 23 | volatile int state = LOW; // definimos como volatil 24 | 25 | void setup() { 26 | pinMode(emuPin, OUTPUT); 27 | pinMode(LEDPin, OUTPUT); 28 | pinMode(intPin, INPUT_PULLUP); 29 | attachInterrupt(digitalPinToInterrupt(intPin), blink, CHANGE); 30 | } 31 | 32 | void loop() { 33 | //esta parte es para emular la salida 34 | digitalWrite(emuPin, HIGH); 35 | delay(150); 36 | digitalWrite(emuPin, LOW); 37 | delay(150); 38 | } 39 | 40 | void blink() { 41 | state = !state; // cambiamos el state para que parpadee 42 | digitalWrite(LEDPin, state); 43 | } 44 | ``` 45 | 46 | 47 | ## Contando disparos de una interrupción 48 | ```csharp 49 | const int emuPin = 10; 50 | 51 | const int intPin = 2; 52 | volatile int ISRCounter = 0; 53 | int counter = 0; 54 | 55 | void setup() 56 | { 57 | pinMode(emuPin, OUTPUT); 58 | 59 | pinMode(intPin, INPUT_PULLUP); 60 | Serial.begin(9600); 61 | attachInterrupt(digitalPinToInterrupt(intPin), interruptCount, FALLING); 62 | } 63 | 64 | void loop() 65 | { 66 | //esta parte es para emular la salida 67 | digitalWrite(emuPin, HIGH); 68 | delay(1000); 69 | digitalWrite(emuPin, LOW); 70 | delay(1000); 71 | 72 | if (counter != ISRCounter) 73 | { 74 | counter = ISRCounter; 75 | Serial.println(counter); 76 | } 77 | } 78 | 79 | void interruptCount() 80 | { 81 | ISRCounter++; 82 | } 83 | ``` 84 | 85 | 86 | -------------------------------------------------------------------------------- /010_arduino-iniciacion/01 - Entradas y salidas/06 - debounce-interrupciones-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/debounce-interrupciones-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## PROBANDO EL REBOTE 8 | ```cpp 9 | const int intPin = 2; 10 | volatile int ISRCounter = 0; 11 | int counter = 0; 12 | 13 | void setup() 14 | { 15 | pinMode(intPin, INPUT_PULLUP); 16 | Serial.begin(9600); 17 | attachInterrupt(digitalPinToInterrupt(intPin), debounceCount, FALLING); 18 | } 19 | 20 | void loop() 21 | { 22 | if (counter != ISRCounter) 23 | { 24 | counter = ISRCounter; 25 | Serial.println(counter); 26 | } 27 | } 28 | 29 | void debounceCount() 30 | { 31 | ISRCounter++; 32 | } 33 | ``` 34 | 35 | 36 | ## Debounce por software 37 | ```cpp 38 | const int timeThreshold = 150; 39 | const int intPin = 2; 40 | volatile int ISRCounter = 0; 41 | int counter = 0; 42 | long startTime = 0; 43 | 44 | void setup() 45 | { 46 | pinMode(intPin, INPUT_PULLUP); 47 | Serial.begin(9600); 48 | attachInterrupt(digitalPinToInterrupt(intPin), debounceCount, FALLING); 49 | } 50 | 51 | void loop() 52 | { 53 | if (counter != ISRCounter) 54 | { 55 | counter = ISRCounter; 56 | Serial.println(counter); 57 | } 58 | } 59 | 60 | void debounceCount() 61 | { 62 | if (millis() - startTime > timeThreshold) 63 | { 64 | ISRCounter++; 65 | startTime = millis(); 66 | } 67 | } 68 | ``` 69 | 70 | 71 | -------------------------------------------------------------------------------- /010_arduino-iniciacion/02 - Electrónica básica/00 - encender-un-led-con-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/encender-un-led-con-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | const int ledPIN = 9; 10 | 11 | void setup() { 12 | Serial.begin(9600); //iniciar puerto serie 13 | pinMode(ledPIN , OUTPUT); //definir pin como salida 14 | } 15 | 16 | void loop(){ 17 | digitalWrite(ledPIN , HIGH); // poner el Pin en HIGH 18 | delay(1000); // esperar un segundo 19 | digitalWrite(ledPIN , LOW); // poner el Pin en LOW 20 | delay(1000); // esperar un segundo 21 | } 22 | ``` 23 | 24 | ```csharp 25 | const int ledPIN = 9; 26 | 27 | int option; 28 | 29 | void setup(){ 30 | Serial.begin(9600); 31 | pinMode(ledPIN , OUTPUT); 32 | } 33 | 34 | void loop(){ 35 | //si existe información pendiente 36 | if (Serial.available()>0){ 37 | //leeemos la opcion 38 | char option = Serial.read(); 39 | //si la opcion esta entre '1' y '9' 40 | if (option >= '1' && option <= '9') 41 | { 42 | //restamos el valor '0' para obtener el numero enviado 43 | option -= '0'; 44 | for(int i=0;i0) // Si hay datos disponibles 69 | { 70 | outputValue = Serial.read(); // Leemos la opción 71 | if(outputValue >= '0' && outputValue <= '9') 72 | { 73 | outputValue -= '0'; // Restamos '0' para convertir a un número 74 | outputValue *= 25; // Multiplicamos x25 para pasar a una escala 0 a 250 75 | analogWrite(ledPIN , outputValue); 76 | } 77 | } 78 | } 79 | ``` 80 | 81 | 82 | -------------------------------------------------------------------------------- /010_arduino-iniciacion/02 - Electrónica básica/01 - leer-un-pulsador-con-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/leer-un-pulsador-con-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Montaje correcto, resistencias de Pull-Down o Pull-Up 8 | ```cpp 9 | const int inputPin = 2; 10 | 11 | int value = 0; 12 | 13 | void setup() { 14 | Serial.begin(9600); 15 | pinMode(inputPin, INPUT); 16 | } 17 | 18 | void loop(){ 19 | value = digitalRead(inputPin); //lectura digital de pin 20 | 21 | //mandar mensaje a puerto serie en función del valor leido 22 | if (value == HIGH) { 23 | Serial.println("Encendido"); 24 | } 25 | else { 26 | Serial.println("Apagado"); 27 | } 28 | delay(1000); 29 | } 30 | ``` 31 | 32 | 33 | -------------------------------------------------------------------------------- /010_arduino-iniciacion/02 - Electrónica básica/02 - lectura-de-una-resistencia-variable-con-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/lectura-de-una-resistencia-variable-con-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplo de código 8 | ```cpp 9 | const int sensorPin = A0; 10 | const int Rc = 1500; // valor de la resistencia de calibración 11 | 12 | int V; // almacena el valor medido 13 | long Rsensor; // almacena la resistencia calculada 14 | 15 | void setup() { 16 | } 17 | 18 | void loop() { 19 | V = analogRead(sensorPin); //realizar la lectura 20 | Rsensor = 1024L * Rc / V - Rc; //calcular el valor de la resistencia 21 | 22 | //...haríamos lo que quisieramos por Rsensor 23 | 24 | delay(1000); 25 | } 26 | ``` 27 | 28 | 29 | -------------------------------------------------------------------------------- /010_arduino-iniciacion/02 - Electrónica básica/03 - lectura-de-un-potenciometro-con-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/lectura-de-un-potenciometro-con-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Código 8 | ```cpp 9 | const int analogPin = A0; 10 | int value; //variable que almacena la lectura analógica raw 11 | int position; //posicion del potenciometro en tanto por ciento 12 | 13 | void setup() { 14 | } 15 | 16 | void loop() { 17 | value = analogRead(analogPin); // realizar la lectura analógica raw 18 | position = map(value, 0, 1023, 0, 100); // convertir a porcentaje 19 | 20 | //...hacer lo que se quiera, con el valor de posición medido 21 | 22 | delay(1000); 23 | } 24 | ``` 25 | 26 | 27 | -------------------------------------------------------------------------------- /010_arduino-iniciacion/05 - Comunicación/00 - arduino-puerto-serie.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-puerto-serie/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Recibir información desde el Arduino 8 | ```csharp 9 | int cont=0; 10 | 11 | void setup(){ 12 | //iniciamos el puerto serie 13 | Serial.begin(9600); 14 | } 15 | 16 | void loop(){ 17 | //Imprimimos el valor del contador 18 | Serial.print("Contador: "); 19 | Serial.println(cont); 20 | 21 | //incrementamos el contador y esperamos un segundo 22 | cont++; 23 | delay(1000); 24 | } 25 | ``` 26 | 27 | 28 | ## Enviar información al Arduino 29 | ```csharp 30 | int option; 31 | int led = 13; 32 | 33 | void setup(){ 34 | Serial.begin(9600); 35 | pinMode(led, OUTPUT); 36 | } 37 | 38 | void loop(){ 39 | //si existe datos disponibles los leemos 40 | if (Serial.available()>0){ 41 | //leemos la opcion enviada 42 | option=Serial.read(); 43 | if(option=='a') { 44 | digitalWrite(led, LOW); 45 | Serial.println("OFF"); 46 | } 47 | if(option=='b') { 48 | digitalWrite(led, HIGH); 49 | Serial.println("ON"); 50 | } 51 | } 52 | } 53 | ``` 54 | 55 | 56 | ## Enviar valores numéricos 57 | ```csharp 58 | int option; 59 | int led = 13; 60 | 61 | void setup(){ 62 | Serial.begin(9600); 63 | pinMode(led, OUTPUT); 64 | } 65 | 66 | void loop(){ 67 | //si existe información pendiente 68 | if (Serial.available()>0){ 69 | //leeemos la opcion 70 | char option = Serial.read(); 71 | //si la opcion esta entre '1' y '9' 72 | if (option >= '1' && option <= '9') 73 | { 74 | //restamos el valor '0' para obtener el numeroenviado 75 | option -= '0'; 76 | for(int i=0;i Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-serial-plotter/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Arduino Serial Plotter 8 | ```cpp 9 | void setup() { 10 | Serial.begin(9600); 11 | } 12 | 13 | void loop() { 14 | 15 | float value; 16 | value = random(100,300)/100.0; 17 | 18 | Serial.println(value); 19 | 20 | delay(100); 21 | } 22 | ``` 23 | 24 | 25 | -------------------------------------------------------------------------------- /010_arduino-iniciacion/05 - Comunicación/02 - arduino-i2c.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-i2c/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## El bus I2C en Arduino 8 | ```cpp 9 | Wire.begin() // Inicializa el hardware del bus 10 | Wire.beginTransmission(address); //Comienza la transmisión 11 | Wire.endTransmission(); // Finaliza la transmisión 12 | Wire.requestFrom(address,nBytes); //solicita un numero de bytes al esclavo en la dirección address 13 | Wire.available(); // Detecta si hay datos pendientes por ser leídos 14 | Wire.write(); // Envía un byte 15 | Wire.read(); // Recibe un byte 16 | 17 | Wire.onReceive(handler); // Registra una función de callback al recibir un dato 18 | Wire.onRequest(handler); // Registra una función de callback al solicitar un dato 19 | ``` 20 | 21 | 22 | ## Escáner de I2C 23 | ```cpp 24 | #include "Wire.h" 25 | 26 | extern "C" { 27 | #include "utility/twi.h" 28 | } 29 | 30 | void scanI2CBus(byte from_addr, byte to_addr, void(*callback)(byte address, byte result) ) 31 | { 32 | byte rc; 33 | byte data = 0; 34 | for( byte addr = from_addr; addr <= to_addr; addr++ ) { 35 | rc = twi_writeTo(addr, &data, 0, 1, 0); 36 | callback( addr, rc ); 37 | } 38 | } 39 | 40 | void scanFunc( byte addr, byte result ) { 41 | Serial.print("addr: "); 42 | Serial.print(addr,DEC); 43 | Serial.print( (result==0) ? " Encontrado!":" "); 44 | Serial.print( (addr%4) ? "\t":"\n"); 45 | } 46 | 47 | const byte start_address = 8; 48 | const byte end_address = 119; 49 | 50 | void setup() 51 | { 52 | Wire.begin(); 53 | 54 | Serial.begin(9600); 55 | Serial.print("Escaneando bus I2C..."); 56 | scanI2CBus( start_address, end_address, scanFunc ); 57 | Serial.println("\nTerminado"); 58 | } 59 | 60 | void loop() 61 | { 62 | delay(1000); 63 | } 64 | ``` 65 | 66 | 67 | -------------------------------------------------------------------------------- /010_arduino-iniciacion/05 - Comunicación/03 - arduino-spi.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-spi/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Software 8 | ```cpp 9 | SPI.begin(); // Inicia el bus SPI 10 | SPI.transfer(c); // Envía un byte 11 | SPI.attachInterrupt(); // Activar la interrupción para recibir datos 12 | ``` 13 | 14 | ```cpp 15 | setBitOrder (LSBFIRST); // least significant bit first 16 | setBitOrder (MSBFIRST); // more significant bit first 17 | ``` 18 | 19 | ```cpp 20 | setDataMode (SPI_MODE0); // clock normalmente LOW, muestreo en flanco subida 21 | setDataMode (SPI_MODE1); // clock normalmente LOW, muestreo en flanco bajada 22 | setDataMode (SPI_MODE2); // clock normalmente HIGH, muestreo en flanco subida 23 | setDataMode (SPI_MODE3); // clock normalmente HIGH, muestreo en flanco bajada 24 | ``` 25 | 26 | ```cpp 27 | setClockDivider(SPI_CLOCK_DIV2); //8 MHz (considerando un modelo de 16 Mhz) 28 | setClockDivider(SPI_CLOCK_DIV4); //4 MHz 29 | setClockDivider(SPI_CLOCK_DIV8); //2 MHz 30 | setClockDivider(SPI_CLOCK_DIV16); //1 MHz 31 | setClockDivider(SPI_CLOCK_DIV32); //500 KHz 32 | setClockDivider(SPI_CLOCK_DIV64); //250 KHz 33 | setClockDivider(SPI_CLOCK_DIV128); //125 KHz 34 | ``` 35 | 36 | ```cpp 37 | SPI.beginTransaction (SPISettings (2000000, MSBFIRST, SPI_MODE0)); // 2 MHz clock, MSB first, mode 0 38 | ``` 39 | 40 | 41 | -------------------------------------------------------------------------------- /010_arduino-iniciacion/06 - Comunicar con un PC/01 - controlar-arduino-con-python-y-la-libreria-pyserial.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/controlar-arduino-con-python-y-la-libreria-pyserial/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Instalar Python y PySerial 8 | ```python 9 | python -m pip install PySerial 10 | ``` 11 | 12 | 13 | ## Recibir información desde Arduino 14 | ```python 15 | void setup() { 16 | Serial.begin(9600); 17 | } 18 | 19 | void loop() { 20 | Serial.println("Hola mundo"); 21 | delay(1000); 22 | } 23 | ``` 24 | 25 | ```python 26 | import serial, time 27 | arduino = serial.Serial('COM4', 9600) 28 | time.sleep(2) 29 | rawString = arduino.readline() 30 | print(rawString) 31 | arduino.close() 32 | ``` 33 | 34 | 35 | ## Enviar información a Arduino 36 | ```cpp 37 | const int pinLED = 13; 38 | 39 | void setup() 40 | { 41 | Serial.begin(9600); 42 | pinMode(pinLED, OUTPUT); 43 | } 44 | 45 | void loop() 46 | { 47 | if (Serial.available()>0) 48 | { 49 | char option = Serial.read(); 50 | if (option >= '1' && option <= '9') 51 | { 52 | option -= '0'; 53 | for (int i = 0;i Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/usar-un-optointerruptor-con-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```csharp 9 | const int sensorPin = 9; 10 | 11 | void setup() { 12 | Serial.begin(9600); //iniciar puerto serie 13 | pinMode(sensorPin , INPUT); //definir pin como entrada 14 | } 15 | 16 | void loop(){ 17 | int value = 0; 18 | value = digitalRead(sensorPin ); //lectura digital de pin 19 | 20 | if (value == LOW) { 21 | Serial.println("Optointerruptor activado"); 22 | } 23 | delay(1000); 24 | } 25 | ``` 26 | 27 | 28 | -------------------------------------------------------------------------------- /020_arduino-intermedio/00 - Entradas y salidas/03 - como-usar-extensor-i2c-tca9548a-y-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/como-usar-extensor-i2c-tca9548a-y-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Escaner I2C 8 | ```csharp 9 | #include "Wire.h" 10 | 11 | void scanI2CBus(byte from_addr, byte to_addr, void(*callback)(byte address, byte result) ) 12 | { 13 | byte rc; 14 | byte data = 0; 15 | for( byte addr = from_addr; addr <= to_addr; addr++ ) { 16 | rc = twi_writeTo(addr, &data, 0, 1, 0); 17 | callback( addr, rc ); 18 | } 19 | } 20 | 21 | void scanFunc( byte addr, byte result ) { 22 | Serial.print("addr: "); 23 | Serial.print(addr,DEC); 24 | Serial.print( (result==0) ? " Encontrado!":" "); 25 | Serial.print( (addr%4) ? "\t":"\n"); 26 | } 27 | 28 | const byte start_address = 8; 29 | const byte end_address = 119; 30 | 31 | void setup() 32 | { 33 | Wire.begin(); 34 | 35 | Serial.begin(9600); 36 | Serial.print("Escaneando bus I2C..."); 37 | scanI2CBus( start_address, end_address, scanFunc ); 38 | Serial.println("\nTerminado"); 39 | } 40 | 41 | void loop() 42 | { 43 | delay(1000); 44 | } 45 | ``` 46 | 47 | 48 | ## Escaner I2C para TCA9548A 49 | ```csharp 50 | /** 51 | * TCA9548 I2CScanner.ino -- I2C bus scanner for Arduino 52 | * 53 | * Based on https://playground.arduino.cc/Main/I2cScanner/ 54 | * 55 | */ 56 | 57 | #include "Wire.h" 58 | 59 | 60 | #define TCAADDR 0x70 61 | 62 | void tcaselect(uint8_t i) { 63 | if (i > 7) return; 64 | 65 | Wire.beginTransmission(TCAADDR); 66 | Wire.write(1 << i); 67 | Wire.endTransmission(); 68 | } 69 | 70 | void setup() 71 | { 72 | while (!Serial); 73 | delay(1000); 74 | 75 | Wire.begin(); 76 | 77 | Serial.begin(115200); 78 | Serial.println("\nTCA escaner listo"); 79 | 80 | for (uint8_t t=0; t<8; t++) { 81 | tcaselect(t); 82 | Serial.print(" Escaneando salida "); Serial.println(t); 83 | 84 | for (uint8_t addr = 0; addr<=127; addr++) { 85 | if (addr == TCAADDR) continue; 86 | 87 | Wire.beginTransmission(addr); 88 | if (!Wire.endTransmission()) { 89 | Serial.print(" - Encontrado I2C 0x"); Serial.println(addr,HEX); 90 | } 91 | } 92 | } 93 | Serial.println("Finalizado"); 94 | } 95 | 96 | void loop() 97 | { 98 | } 99 | ``` 100 | 101 | 102 | -------------------------------------------------------------------------------- /020_arduino-intermedio/00 - Entradas y salidas/04 - arduino-mosfet-irf520n.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-mosfet-irf520n/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | const int pin = 9; 10 | 11 | void setup() { 12 | pinMode(pin, OUTPUT); //definir pin como salida 13 | } 14 | 15 | void loop(){ 16 | digitalWrite(pin, HIGH); // poner el Pin en HIGH 17 | delay(5000); // esperar un segundo 18 | digitalWrite(pin, LOW); // poner el Pin en LOW 19 | delay(5000); // esperar un segundo 20 | } 21 | ``` 22 | 23 | 24 | -------------------------------------------------------------------------------- /020_arduino-intermedio/00 - Entradas y salidas/05 - arduino-salida-rele.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-salida-rele/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | const int pin = 9; 10 | 11 | void setup() { 12 | Serial.begin(9600); //iniciar puerto serie 13 | pinMode(pin, OUTPUT); //definir pin como salida 14 | } 15 | 16 | void loop(){ 17 | digitalWrite(pin, HIGH); // poner el Pin en HIGH 18 | delay(10000); // esperar un segundo 19 | digitalWrite(pin, LOW); // poner el Pin en LOW 20 | delay(10000); // esperar un segundo 21 | } 22 | ``` 23 | 24 | 25 | -------------------------------------------------------------------------------- /020_arduino-intermedio/00 - Entradas y salidas/06 - arduino-rele-estado-solido-ssr.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-rele-estado-solido-ssr/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | const int pin = 9; 10 | 11 | void setup() 12 | { 13 | Serial.begin(9600); //iniciar puerto serie 14 | pinMode(pin, OUTPUT); //definir pin como salida 15 | } 16 | 17 | void loop() 18 | { 19 | digitalWrite(pin, HIGH); // poner el Pin en HIGH 20 | delay(10000); // esperar diez segundos 21 | digitalWrite(pin, LOW); // poner el Pin en LOW 22 | delay(10000); // esperar diez segundos 23 | } 24 | ``` 25 | 26 | 27 | -------------------------------------------------------------------------------- /020_arduino-intermedio/00 - Entradas y salidas/07 - mas-salidas-y-entradas-en-arduino-con-multiplexor-cd74hc4067.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/mas-salidas-y-entradas-en-arduino-con-multiplexor-cd74hc4067/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## CD74HC4067 como salida 8 | ```cpp 9 | const int muxSIG = A0; 10 | const int muxS0 = 8; 11 | const int muxS1 = 9; 12 | const int muxS2 = 10; 13 | const int muxS3 = 11; 14 | 15 | int SetMuxChannel(byte channel) 16 | { 17 | digitalWrite(muxS0, bitRead(channel, 0)); 18 | digitalWrite(muxS1, bitRead(channel, 1)); 19 | digitalWrite(muxS2, bitRead(channel, 2)); 20 | digitalWrite(muxS3, bitRead(channel, 3)); 21 | } 22 | 23 | void setup() 24 | { 25 | pinMode(muxSIG, OUTPUT); 26 | pinMode(muxS0, OUTPUT); 27 | pinMode(muxS1, OUTPUT); 28 | pinMode(muxS2, OUTPUT); 29 | pinMode(muxS3, OUTPUT); 30 | } 31 | 32 | void loop() 33 | { 34 | for (byte i = 0; i < 16; i++) 35 | { 36 | SetMuxChannel(i); 37 | digitalWrite(muxSIG, HIGH); 38 | delay(200); 39 | digitalWrite(muxSIG, LOW); 40 | delay(200); 41 | } 42 | } 43 | ``` 44 | 45 | 46 | ## CD74HC4067 como entrada 47 | ```cpp 48 | const int muxSIG = A0; 49 | const int muxS0 = 8; 50 | const int muxS1 = 9; 51 | const int muxS2 = 10; 52 | const int muxS3 = 11; 53 | 54 | int SetMuxChannel(byte channel) 55 | { 56 | digitalWrite(muxS0, bitRead(channel, 0)); 57 | digitalWrite(muxS1, bitRead(channel, 1)); 58 | digitalWrite(muxS2, bitRead(channel, 2)); 59 | digitalWrite(muxS3, bitRead(channel, 3)); 60 | } 61 | 62 | void setup() 63 | { 64 | Serial.begin(9600); 65 | pinMode(muxS0, OUTPUT); 66 | pinMode(muxS1, OUTPUT); 67 | pinMode(muxS2, OUTPUT); 68 | pinMode(muxS3, OUTPUT); 69 | } 70 | 71 | void loop() 72 | { 73 | for (byte i = 0; i < 16; i++) 74 | { 75 | SetMuxChannel(i); 76 | byte muxValue = analogRead(muxSIG); 77 | 78 | Serial.print(muxValue); 79 | Serial.print("\t"); 80 | } 81 | Serial.println(); 82 | delay(1000); 83 | } 84 | ``` 85 | 86 | 87 | -------------------------------------------------------------------------------- /020_arduino-intermedio/00 - Entradas y salidas/08 - mas-pines-digitales-con-arduino-y-el-expansor-es-i2c-pcf8574.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/mas-pines-digitales-con-arduino-y-el-expansor-es-i2c-pcf8574/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Sin librería 8 | ```cpp 9 | #include 10 | 11 | const int pcfAddress = 0x38; 12 | 13 | void setup() 14 | { 15 | Wire.begin(); 16 | Serial.begin(9600); 17 | } 18 | 19 | void loop() 20 | { 21 | for (short channel = 0; channel < 8; channel++) 22 | { 23 | // Escribir dato en canal 'channel' 24 | Wire.beginTransmission(pcfAddress); 25 | Wire.write(~(1 << channel)); 26 | Wire.endTransmission(); 27 | 28 | // Leer dato de canal 29 | delay(500); 30 | } 31 | } 32 | ``` 33 | 34 | ```cpp 35 | #include 36 | 37 | const int pcfAddress = 0x38; 38 | 39 | void setup() 40 | { 41 | Wire.begin(); 42 | Serial.begin(9600); 43 | } 44 | 45 | void loop() 46 | { 47 | short channel = 1; 48 | byte value = 0; 49 | 50 | // Leer dato de canal 'channel' 51 | Wire.requestFrom(pcfAddress, 1 << channel); 52 | if (Wire.available()) 53 | { 54 | value = Wire.read(); 55 | } 56 | Wire.endTransmission(); 57 | 58 | // Mostrar el valor por puerto serie 59 | Serial.println(value); 60 | } 61 | ``` 62 | 63 | 64 | ## Con librería 65 | ```cpp 66 | #include 67 | #include "PCF8574.h" 68 | 69 | PCF8574 expander; 70 | 71 | void setup() 72 | { 73 | Serial.begin(9600); 74 | 75 | expander.begin(0x20); 76 | 77 | /* Setup some PCF8574 pins for demo */ 78 | expander.pinMode(0, OUTPUT); 79 | expander.pinMode(1, OUTPUT); 80 | expander.pinMode(2, OUTPUT); 81 | expander.pinMode(3, INPUT_PULLUP); 82 | 83 | /* Blink hardware LED for debug */ 84 | digitalWrite(13, HIGH); 85 | 86 | /* Toggle PCF8574 output 0 for demo */ 87 | expander.toggle(); 88 | 89 | /* Blink hardware LED for debug */ 90 | digitalWrite(13, LOW); 91 | } 92 | 93 | void loop() 94 | { 95 | } 96 | ``` 97 | 98 | 99 | -------------------------------------------------------------------------------- /020_arduino-intermedio/00 - Entradas y salidas/09 - como-controlar-hasta-16-gpio-por-i2c-con-extensor-pcf8575-y-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/como-controlar-hasta-16-gpio-por-i2c-con-extensor-pcf8575-y-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```csharp 9 | #include "PCF8575.h" 10 | 11 | // Iniciar el PCF8575 en la dirección 0x20 12 | PCF8575 pcf8575(0x20); 13 | 14 | void setup() 15 | { 16 | Serial.begin(115200); 17 | 18 | // Establecer el pin P0 como salida 19 | pcf8575.pinMode(P0, OUTPUT); 20 | 21 | pcf8575.begin(); 22 | } 23 | 24 | void loop() 25 | { 26 | pcf8575.digitalWrite(P0, HIGH); 27 | delay(1000); 28 | pcf8575.digitalWrite(P0, LOW); 29 | delay(1000); 30 | } 31 | ``` 32 | 33 | 34 | -------------------------------------------------------------------------------- /020_arduino-intermedio/00 - Entradas y salidas/10 - entrada-analogica-adc-de-16-bits-con-arduino-y-ads1115.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/entrada-analogica-adc-de-16-bits-con-arduino-y-ads1115/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Modo single end 8 | ```cpp 9 | #include 10 | #include 11 | 12 | Adafruit_ADS1115 ads; 13 | const float multiplier = 0.1875F; 14 | 15 | void setup(void) 16 | { 17 | Serial.begin(9600); 18 | 19 | // Descomentar el que interese 20 | // ads.setGain(GAIN_TWOTHIRDS); +/- 6.144V 1 bit = 0.1875mV (default) 21 | // ads.setGain(GAIN_ONE); +/- 4.096V 1 bit = 0.125mV 22 | // ads.setGain(GAIN_TWO); +/- 2.048V 1 bit = 0.0625mV 23 | // ads.setGain(GAIN_FOUR); +/- 1.024V 1 bit = 0.03125mV 24 | // ads.setGain(GAIN_EIGHT); +/- 0.512V 1 bit = 0.015625mV 25 | // ads.setGain(GAIN_SIXTEEN); +/- 0.256V 1 bit = 0.0078125mV 26 | ads.begin(); 27 | } 28 | 29 | void loop(void) 30 | { 31 | int16_t adc0, adc1, adc2, adc3; 32 | 33 | 34 | adc0 = ads.readADC_SingleEnded(0); 35 | adc1 = ads.readADC_SingleEnded(1); 36 | adc2 = ads.readADC_SingleEnded(2); 37 | adc3 = ads.readADC_SingleEnded(3); 38 | Serial.print("AIN0: "); Serial.println(adc0 * multiplier); 39 | Serial.print("AIN1: "); Serial.println(adc1 * multiplier); 40 | Serial.print("AIN2: "); Serial.println(adc2 * multiplier); 41 | Serial.print("AIN3: "); Serial.println(adc3 * multiplier); 42 | Serial.println(" "); 43 | 44 | delay(1000); 45 | } 46 | ``` 47 | 48 | 49 | ## Modo diferencial 50 | ```cpp 51 | #include 52 | #include 53 | 54 | Adafruit_ADS1115 ads; 55 | const float multiplier = 0.1875F; 56 | 57 | void setup(void) 58 | { 59 | Serial.begin(9600); 60 | 61 | ads.begin(); 62 | } 63 | 64 | void loop(void) 65 | { 66 | int16_t results = ads.readADC_Differential_0_1(); 67 | 68 | Serial.print("Diferencial: "); 69 | Serial.print(results); 70 | Serial.print(" "); 71 | Serial.print(results * multiplier); 72 | Serial.println("mV"); 73 | 74 | delay(1000); 75 | } 76 | ``` 77 | 78 | 79 | ## Modo comparador 80 | ```cpp 81 | #include 82 | #include 83 | 84 | Adafruit_ADS1115 ads; 85 | 86 | void setup(void) 87 | { 88 | Serial.begin(9600); 89 | 90 | ads.begin(); 91 | 92 | // Activar comparador para 2.5V en canal 0 93 | // (Donde 13333 = 2500 / 0.1875F) 94 | ads.startComparator_SingleEnded(0, 13333); 95 | } 96 | 97 | void loop(void) 98 | { 99 | int16_t adc0; 100 | 101 | // Actualizar comparadores 102 | adc0 = ads.getLastConversionResults(); 103 | Serial.print("AIN0: "); Serial.println(adc0); 104 | 105 | delay(100); 106 | } 107 | ``` 108 | 109 | 110 | -------------------------------------------------------------------------------- /020_arduino-intermedio/00 - Entradas y salidas/11 - salida-analogica-real-con-arduino-y-dac-de-12bits-mcp4725.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/salida-analogica-real-con-arduino-y-dac-de-12bits-mcp4725/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | #include 10 | #include 11 | 12 | Adafruit_MCP4725 dac; 13 | 14 | void setup(void) 15 | { 16 | dac.begin(0x60); 17 | } 18 | 19 | void loop(void) { 20 | uint32_t counter; 21 | for (counter = 0; counter < 4095; counter++) 22 | { 23 | dac.setVoltage(counter, false); 24 | } 25 | for (counter = 4095; counter > 0; counter--) 26 | { 27 | dac.setVoltage(counter, false); 28 | } 29 | } 30 | ``` 31 | 32 | 33 | -------------------------------------------------------------------------------- /020_arduino-intermedio/00 - Entradas y salidas/12 - resistencia-variable-con-arduino-y-digipot-mcp41xxx.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/resistencia-variable-con-arduino-y-digipot-mcp41xxx/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | //SCK > D13 10 | //SI > D11 11 | //CS > D10 12 | 13 | #include 14 | const byte address = 0x11; 15 | const int CS = 10; 16 | 17 | int digitalPotWrite(int value) 18 | { 19 | digitalWrite(CS, LOW); 20 | SPI.transfer(address); 21 | SPI.transfer(value); 22 | digitalWrite(CS, HIGH); 23 | } 24 | 25 | void setup() 26 | { 27 | pinMode(CS, OUTPUT); 28 | SPI.begin(); 29 | 30 | // Resistencia maxima 31 | digitalPotWrite(0); 32 | delay(5000); 33 | 34 | // Resistencia intermedia 35 | digitalPotWrite(126); 36 | delay(5000); 37 | 38 | // Resistencia inferior 39 | digitalPotWrite(255); 40 | delay(5000); 41 | } 42 | 43 | void loop() 44 | { 45 | for (int i = 0; i <= 255; i++) 46 | { 47 | digitalPotWrite(i); 48 | delay(100); 49 | } 50 | delay(2000); 51 | for (int i = 255; i >= 0; i--) 52 | { 53 | digitalPotWrite(i); 54 | delay(100); 55 | } 56 | delay(2000); 57 | } 58 | ``` 59 | 60 | 61 | -------------------------------------------------------------------------------- /020_arduino-intermedio/01 - Motores/00 - controlar-un-servo-con-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/controlar-un-servo-con-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```csharp 9 | #include 10 | 11 | Servo myservo; // crea el objeto servo 12 | 13 | int pos = 0; // posicion del servo 14 | 15 | void setup() { 16 | myservo.attach(9); // vincula el servo al pin digital 9 17 | } 18 | 19 | void loop() { 20 | //varia la posicion de 0 a 180, con esperas de 15ms 21 | for (pos = 0; pos <= 180; pos += 1) 22 | { 23 | myservo.write(pos); 24 | delay(15); 25 | } 26 | 27 | //varia la posicion de 180 a 0, con esperas de 15ms 28 | for (pos = 180; pos >= 0; pos -= 1) 29 | { 30 | myservo.write(pos); 31 | delay(15); 32 | } 33 | } 34 | ``` 35 | 36 | 37 | -------------------------------------------------------------------------------- /020_arduino-intermedio/01 - Motores/01 - controlar-un-servo-de-rotacion-continua-con-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/controlar-un-servo-de-rotacion-continua-con-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```csharp 9 | #include 10 | 11 | Servo myservo; // crea el objeto servo 12 | 13 | int vel = 0; // velocidad del servo 14 | 15 | void setup() { 16 | myservo.attach(9); // vincula el servo al pin digital 9 17 | } 18 | 19 | void loop() { 20 | //servo parado (equivalente a angulo 90º) 21 | vel = 90; 22 | myservo.write(vel); 23 | delay(1500); 24 | 25 | //servo 100% CW (equivalente a angulo 180º) 26 | vel = 180; 27 | myservo.write(vel); 28 | delay(1500); 29 | 30 | //servo 100% CCW (equivalente a angulo 0º) 31 | vel = 0; 32 | myservo.write(vel); 33 | delay(1500); 34 | } 35 | ``` 36 | 37 | 38 | -------------------------------------------------------------------------------- /020_arduino-intermedio/01 - Motores/03 - hasta-32-de-servos-en-arduino-con-el-controlador-usc-32.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/hasta-32-de-servos-en-arduino-con-el-controlador-usc-32/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```bash 9 | [channel] P[pw] ... #[channel] P[pw] T[time] \n\r 10 | ``` 11 | 12 | ```bash 13 | #11 P2000 #30 P2500 T1500 \n\r 14 | ``` 15 | 16 | ```cpp 17 | uint8_t ServoMinMs = 500; // ancho de pulso en ms para pocicion 0° 18 | uint8_t ServoMaxMs = 2500; // ancho de pulso en ms para la pocicion 180° 19 | 20 | void setup() 21 | { 22 | Serial.begin(9600); 23 | } 24 | 25 | void loop() 26 | { 27 | for (uint8_t servo = 0; servo < 32; servo++) 28 | { 29 | for (uint16_t servoPos = ServoMinMs; servoPos < ServoMaxMs; servoPos++) 30 | { 31 | moveServo(servo, servoPos, 500); 32 | } 33 | } 34 | delay(750 35 | for (uint8_t servo = 0; servo < 32; servo++) 36 | { 37 | for (uint16_t servoPos = ServoMaxMs; servoPos > ServoMinMs; servoPos--) 38 | { 39 | moveServo(servo, servoPos, 500); 40 | } 41 | } 42 | delay(750); 43 | } 44 | 45 | void moveServo(uint8_t servo, uint16_t position, uint16_t time) 46 | { 47 | Serial.print("#"); 48 | Serial.print(servo); 49 | Serial.print("P"); 50 | Serial.print(position); 51 | Serial.print("T"); 52 | Serial.println(time); 53 | } 54 | ``` 55 | 56 | 57 | -------------------------------------------------------------------------------- /020_arduino-intermedio/01 - Motores/04 - arduino-motor-corriente-continua-l298n.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-motor-corriente-continua-l298n/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```csharp 9 | const int pinENA = 6; 10 | const int pinIN1 = 7; 11 | const int pinIN2 = 8; 12 | 13 | const int speed = 200; //velocidad de giro 80% (200/255) 14 | 15 | void setup() 16 | { 17 | pinMode(pinIN1, OUTPUT); 18 | pinMode(pinIN2, OUTPUT); 19 | pinMode(pinENA, OUTPUT); 20 | } 21 | 22 | void loop() 23 | { 24 | digitalWrite(pinIN1, HIGH); 25 | digitalWrite(pinIN2, LOW); 26 | analogWrite(pinENA, speed); 27 | delay(1000); 28 | } 29 | ``` 30 | 31 | ```csharp 32 | const int pinENA = 6; 33 | const int pinIN1 = 7; 34 | const int pinIN2 = 8; 35 | const int pinIN3 = 9; 36 | const int pinIN4 = 10; 37 | const int pinENB = 11; 38 | 39 | const int waitTime = 2000; //espera entre fases 40 | const int speed = 200; //velocidad de giro 41 | 42 | const int pinMotorA[3] = { pinENA, pinIN1, pinIN2 }; 43 | const int pinMotorB[3] = { pinENB, pinIN3, pinIN4 }; 44 | 45 | void setup() 46 | { 47 | pinMode(pinIN1, OUTPUT); 48 | pinMode(pinIN2, OUTPUT); 49 | pinMode(pinENA, OUTPUT); 50 | pinMode(pinIN3, OUTPUT); 51 | pinMode(pinIN4, OUTPUT); 52 | pinMode(pinENB, OUTPUT); 53 | } 54 | 55 | void loop() 56 | { 57 | moveForward(pinMotorA, 180); 58 | moveForward(pinMotorB, 180); 59 | delay(waitTime); 60 | 61 | moveBackward(pinMotorA, 180); 62 | moveBackward(pinMotorB, 180); 63 | delay(waitTime); 64 | 65 | fullStop(pinMotorA); 66 | fullStop(pinMotorB); 67 | delay(waitTime); 68 | } 69 | 70 | void moveForward(const int pinMotor[3], int speed) 71 | { 72 | digitalWrite(pinMotor[1], HIGH); 73 | digitalWrite(pinMotor[2], LOW); 74 | 75 | analogWrite(pinMotor[0], speed); 76 | } 77 | 78 | void moveBackward(const int pinMotor[3], int speed) 79 | { 80 | digitalWrite(pinMotor[1], LOW); 81 | digitalWrite(pinMotor[2], HIGH); 82 | 83 | analogWrite(pinMotor[0], speed); 84 | } 85 | 86 | void fullStop(const int pinMotor[3]) 87 | { 88 | digitalWrite(pinMotor[1], LOW); 89 | digitalWrite(pinMotor[2], LOW); 90 | 91 | analogWrite(pinMotor[0], 0); 92 | } 93 | ``` 94 | 95 | 96 | -------------------------------------------------------------------------------- /020_arduino-intermedio/01 - Motores/05 - controla-motores-de-gran-potencia-con-arduino-y-bts7960.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/controla-motores-de-gran-potencia-con-arduino-y-bts7960/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | #include "BTS7960.h" 10 | 11 | const uint8_t EN = 8; 12 | const uint8_t L_PWM = 9; 13 | const uint8_t R_PWM = 10; 14 | 15 | BTS7960 motorController(EN, L_PWM, R_PWM); 16 | 17 | void setup() 18 | { 19 | } 20 | 21 | void loop() 22 | { 23 | motorController.Enable(); 24 | 25 | for(int speed = 0 ; speed < 255; speed+=10) 26 | { 27 | motorController.TurnLeft(speed); 28 | delay(100); 29 | } 30 | 31 | motorController.Stop(); 32 | 33 | for(int speed = 255 ; speed > 0; speed-=10) 34 | { 35 | motorController.TurnLeft(speed); 36 | delay(100); 37 | } 38 | motorController.Stop(); 39 | motorController.Disable(); 40 | delay(5000); 41 | } 42 | ``` 43 | 44 | 45 | -------------------------------------------------------------------------------- /020_arduino-intermedio/01 - Motores/06 - arduino-motor-dc-tb6612fng.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-motor-dc-tb6612fng/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```csharp 9 | const int pinPWMA = 6; 10 | const int pinAIN2 = 7; 11 | const int pinAIN1 = 8; 12 | const int pinBIN1 = 9; 13 | const int pinBIN2 = 10; 14 | const int pinPWMB = 11; 15 | const int pinSTBY = 12; 16 | 17 | const int waitTime = 2000; //espera entre fases 18 | const int speed = 200; //velocidad de giro 19 | 20 | const int pinMotorA[3] = { pinPWMA, pinAIN2, pinAIN1 }; 21 | const int pinMotorB[3] = { pinPWMB, pinBIN1, pinBIN2 }; 22 | 23 | enum moveDirection { 24 | forward, 25 | backward 26 | }; 27 | 28 | enum turnDirection { 29 | clockwise, 30 | counterClockwise 31 | }; 32 | 33 | void setup() 34 | { 35 | pinMode(pinAIN2, OUTPUT); 36 | pinMode(pinAIN1, OUTPUT); 37 | pinMode(pinPWMA, OUTPUT); 38 | pinMode(pinBIN1, OUTPUT); 39 | pinMode(pinBIN2, OUTPUT); 40 | pinMode(pinPWMB, OUTPUT); 41 | } 42 | 43 | void loop() 44 | { 45 | enableMotors(); 46 | move(forward, 180); 47 | delay(waitTime); 48 | 49 | move(backward, 180); 50 | delay(waitTime); 51 | 52 | turn(clockwise, 180); 53 | delay(waitTime); 54 | 55 | turn(counterClockwise, 180); 56 | delay(waitTime); 57 | 58 | fullStop(); 59 | delay(waitTime); 60 | } 61 | 62 | //Funciones que controlan el vehiculo 63 | void move(int direction, int speed) 64 | { 65 | if (direction == forward) 66 | { 67 | moveMotorForward(pinMotorA, speed); 68 | moveMotorForward(pinMotorB, speed); 69 | } 70 | else 71 | { 72 | moveMotorBackward(pinMotorA, speed); 73 | moveMotorBackward(pinMotorB, speed); 74 | } 75 | } 76 | 77 | void turn(int direction, int speed) 78 | { 79 | if (direction == forward) 80 | { 81 | moveMotorForward(pinMotorA, speed); 82 | moveMotorBackward(pinMotorB, speed); 83 | } 84 | else 85 | { 86 | moveMotorBackward(pinMotorA, speed); 87 | moveMotorForward(pinMotorB, speed); 88 | } 89 | } 90 | 91 | void fullStop() 92 | { 93 | disableMotors(); 94 | stopMotor(pinMotorA); 95 | stopMotor(pinMotorB); 96 | } 97 | 98 | //Funciones que controlan los motores 99 | void moveMotorForward(const int pinMotor[3], int speed) 100 | { 101 | digitalWrite(pinMotor[1], HIGH); 102 | digitalWrite(pinMotor[2], LOW); 103 | 104 | analogWrite(pinMotor[0], speed); 105 | } 106 | 107 | void moveMotorBackward(const int pinMotor[3], int speed) 108 | { 109 | digitalWrite(pinMotor[1], LOW); 110 | digitalWrite(pinMotor[2], HIGH); 111 | 112 | analogWrite(pinMotor[0], speed); 113 | } 114 | 115 | void stopMotor(const int pinMotor[3]) 116 | { 117 | digitalWrite(pinMotor[1], LOW); 118 | digitalWrite(pinMotor[2], LOW); 119 | 120 | analogWrite(pinMotor[0], 0); 121 | } 122 | 123 | void enableMotors() 124 | { 125 | digitalWrite(pinSTBY, HIGH); 126 | } 127 | 128 | void disableMotors() 129 | { 130 | digitalWrite(pinSTBY, LOW); 131 | } 132 | ``` 133 | 134 | 135 | -------------------------------------------------------------------------------- /020_arduino-intermedio/01 - Motores/07 - motores-paso-paso-arduino-driver-a4988-drv8825.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/motores-paso-paso-arduino-driver-a4988-drv8825/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplo de código 8 | ```csharp 9 | const int dirPin = 8; 10 | const int stepPin = 9; 11 | 12 | const int steps = 200; 13 | int stepDelay; 14 | 15 | void setup() { 16 | // Marcar los pines como salida 17 | pinMode(dirPin, OUTPUT); 18 | pinMode(stepPin, OUTPUT); 19 | } 20 | 21 | void loop() { 22 | //Activar una direccion y fijar la velocidad con stepDelay 23 | digitalWrite(dirPin, HIGH); 24 | stepDelay = 250; 25 | // Giramos 200 pulsos para hacer una vuelta completa 26 | for (int x = 0; x < steps * 1; x++) { 27 | digitalWrite(stepPin, HIGH); 28 | delayMicroseconds(stepDelay); 29 | digitalWrite(stepPin, LOW); 30 | delayMicroseconds(stepDelay); 31 | } 32 | delay(1000); 33 | 34 | //Cambiamos la direccion y aumentamos la velocidad 35 | digitalWrite(dirPin, LOW); 36 | stepDelay = 150; 37 | // Giramos 400 pulsos para hacer dos vueltas completas 38 | for (int x = 0; x < steps * 2; x++) { 39 | digitalWrite(stepPin, HIGH); 40 | delayMicroseconds(stepDelay); 41 | digitalWrite(stepPin, LOW); 42 | delayMicroseconds(stepDelay); 43 | } 44 | delay(1000); 45 | } 46 | ``` 47 | 48 | 49 | -------------------------------------------------------------------------------- /020_arduino-intermedio/01 - Motores/08 - motor-paso-paso-28byj-48-arduino-driver-uln2003.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/motor-paso-paso-28byj-48-arduino-driver-uln2003/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## EJEMPLOS DE CODIGO 8 | ```csharp 9 | //definicion de pins 10 | const int motorPin1 = 8; // 28BYJ48 In1 11 | const int motorPin2 = 9; // 28BYJ48 In2 12 | const int motorPin3 = 10; // 28BYJ48 In3 13 | const int motorPin4 = 11; // 28BYJ48 In4 14 | 15 | //definicion variables 16 | int motorSpeed = 1200; //variable para fijar la velocidad 17 | int stepCounter = 0; // contador para los pasos 18 | int stepsPerRev = 4076; // pasos para una vuelta completa 19 | 20 | //tablas con la secuencia de encendido (descomentar la que necesiteis) 21 | //secuencia 1-fase 22 | //const int numSteps = 4; 23 | //const int stepsLookup[4] = { B1000, B0100, B0010, B0001 }; 24 | 25 | //secuencia 2-fases 26 | //const int numSteps = 4; 27 | //const int stepsLookup[4] = { B1100, B0110, B0011, B1001 }; 28 | 29 | //secuencia media fase 30 | const int numSteps = 8; 31 | const int stepsLookup[8] = { B1000, B1100, B0100, B0110, B0010, B0011, B0001, B1001 }; 32 | 33 | void setup() 34 | { 35 | //declarar pines como salida 36 | pinMode(motorPin1, OUTPUT); 37 | pinMode(motorPin2, OUTPUT); 38 | pinMode(motorPin3, OUTPUT); 39 | pinMode(motorPin4, OUTPUT); 40 | } 41 | 42 | void loop() 43 | { 44 | for (int i = 0; i < stepsPerRev * 2; i++) 45 | { 46 | clockwise(); 47 | delayMicroseconds(motorSpeed); 48 | } 49 | for (int i = 0; i < stepsPerRev * 2; i++) 50 | { 51 | anticlockwise(); 52 | delayMicroseconds(motorSpeed); 53 | } 54 | delay(1000); 55 | } 56 | 57 | void clockwise() 58 | { 59 | stepCounter++; 60 | if (stepCounter >= numSteps) stepCounter = 0; 61 | setOutput(stepCounter); 62 | } 63 | 64 | void anticlockwise() 65 | { 66 | stepCounter--; 67 | if (stepCounter < 0) stepCounter = numSteps - 1; 68 | setOutput(stepCounter); 69 | } 70 | 71 | void setOutput(int step) 72 | { 73 | digitalWrite(motorPin1, bitRead(stepsLookup[step], 0)); 74 | digitalWrite(motorPin2, bitRead(stepsLookup[step], 1)); 75 | digitalWrite(motorPin3, bitRead(stepsLookup[step], 2)); 76 | digitalWrite(motorPin4, bitRead(stepsLookup[step], 3)); 77 | } 78 | ``` 79 | 80 | 81 | -------------------------------------------------------------------------------- /020_arduino-intermedio/02 - Actuadores/01 - arduino-actuador-electromagnetico.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-actuador-electromagnetico/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | const int pin = 9; 10 | 11 | void setup() 12 | { 13 | pinMode(pin, OUTPUT); //definir pin como salida 14 | } 15 | 16 | void loop() 17 | { 18 | digitalWrite(pin, HIGH); // poner el Pin en HIGH 19 | delay(10000); // esperar 10 segundos 20 | digitalWrite(pin, LOW); // poner el Pin en LOW 21 | delay(10000); // esperar 10 segundos 22 | } 23 | ``` 24 | 25 | 26 | -------------------------------------------------------------------------------- /020_arduino-intermedio/02 - Actuadores/02 - diodo-laser-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/diodo-laser-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplo de código de montaje 8 | ```cpp 9 | const int pin = 9; 10 | 11 | void setup() { 12 | pinMode(pin, OUTPUT); //definir pin como salida 13 | } 14 | 15 | void loop(){ 16 | digitalWrite(pin, HIGH); // poner el Pin en HIGH 17 | delay(5000); // esperar 5 segundos 18 | digitalWrite(pin, LOW); // poner el Pin en LOW 19 | delay(20000); // esperar 20 segundos 20 | } 21 | ``` 22 | 23 | 24 | -------------------------------------------------------------------------------- /020_arduino-intermedio/02 - Actuadores/03 - electroiman-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/electroiman-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplo de código 8 | ```cpp 9 | const int pin = 9; 10 | 11 | void setup() { 12 | pinMode(pin, OUTPUT); //definir pin como salida 13 | } 14 | 15 | void loop(){ 16 | digitalWrite(pin, HIGH); // poner el Pin en HIGH 17 | delay(10000); // esperar un segundo 18 | digitalWrite(pin, LOW); // poner el Pin en LOW 19 | delay(10000); // esperar un segundo 20 | } 21 | ``` 22 | 23 | 24 | -------------------------------------------------------------------------------- /020_arduino-intermedio/02 - Actuadores/04 - arduino-peltier.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-peltier/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplo de códigode montaje 8 | ```cpp 9 | const int pin = 9; 10 | 11 | void setup() { 12 | pinMode(pin, OUTPUT); //definir pin como salida 13 | } 14 | 15 | void loop(){ 16 | digitalWrite(pin, HIGH); // poner el Pin en HIGH 17 | delay(5000); // esperar 5 segundos 18 | digitalWrite(pin, LOW); // poner el Pin en LOW 19 | delay(10000); // esperar 10 segundos 20 | } 21 | ``` 22 | 23 | ```cpp 24 | const int pin = 9; 25 | 26 | const float thresholdLOW = 20.0; 27 | const float thresholdHIGH= 30.0; 28 | 29 | bool state = 0; //placa Peltier desacivada o desactivada 30 | 31 | float GetTemperature() 32 | { 33 | return 20.0; //sustituir en función del sensor empleado 34 | } 35 | 36 | void setup() { 37 | pinMode(pin, OUTPUT); //definir pin como salida 38 | } 39 | 40 | void loop(){ 41 | float currentTemperature = GetTemperature(); 42 | 43 | if(state == 0 && currentTemperature > thresholdHIGH) 44 | { 45 | state = 1; 46 | digitalWrite(pin, HIGH); // encender la placa Peltier 47 | } 48 | if(state == 1 && currentTemperature < thresholdLOW) 49 | { 50 | state == 0; 51 | digitalWrite(pin, LOW); // apagar la placa Peltier 52 | } 53 | 54 | delay(5000); // esperar 5 segundos entre medicioens 55 | } 56 | ``` 57 | 58 | 59 | -------------------------------------------------------------------------------- /020_arduino-intermedio/02 - Actuadores/05 - controlar-un-ventilador-con-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/controlar-un-ventilador-con-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplo de código 8 | ```cpp 9 | const int pin = 9; 10 | 11 | void setup() { 12 | pinMode(pin, OUTPUT); //definir pin como salida 13 | } 14 | 15 | void loop(){ 16 | digitalWrite(pin, HIGH); // poner el Pin en HIGH 17 | delay(10000); // esperar 10 segundos 18 | digitalWrite(pin, LOW); // poner el Pin en LOW 19 | delay(10000); // esperar 10 segundos 20 | 21 | } 22 | ``` 23 | 24 | ```cpp 25 | const int pin = 9; 26 | 27 | const float thresholdLOW = 20.0; 28 | const float thresholdHIGH= 30.0; 29 | 30 | bool state = false; /// ventilador activo o inactivo 31 | 32 | float GetTemperature() 33 | { 34 | return 20.0; //sustituir en función del sensor empleado 35 | } 36 | 37 | void setup() { 38 | pinMode(pin, OUTPUT); //definir pin como salida 39 | } 40 | 41 | void loop(){ 42 | float currentTemperature = GetTemperature(); 43 | 44 | if(state == false && currentTemperature > thresholdHIGH) 45 | { 46 | state = true; 47 | digitalWrite(pin, HIGH); // encender ventilador 48 | } 49 | if(state == true && currentTemperature < thresholdLOW) 50 | { 51 | state = false; 52 | digitalWrite(pin, LOW); // apagar ventilador 53 | } 54 | 55 | delay(5000); // esperar 5 segundos entre mediciones 56 | } 57 | ``` 58 | 59 | 60 | -------------------------------------------------------------------------------- /020_arduino-intermedio/03 - Optico/00 - medir-nivel-luz-con-arduino-y-fotoresistencia-ldr.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/medir-nivel-luz-con-arduino-y-fotoresistencia-ldr/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | const int LEDPin = 13; 10 | const int LDRPin = 2; 11 | 12 | void setup() 13 | { 14 | pinMode(LEDPin, OUTPUT); 15 | pinMode(LDRPin, INPUT); 16 | } 17 | 18 | void loop() 19 | { 20 | int value = digitalRead(LDRPin); 21 | if (value == HIGH) 22 | { 23 | digitalWrite(LEDPin, HIGH); 24 | delay(50); 25 | digitalWrite(LEDPin, LOW); 26 | delay(50); 27 | } 28 | } 29 | ``` 30 | 31 | ```cpp 32 | const int LEDPin = 13; 33 | const int LDRPin = A0; 34 | const int threshold = 100; 35 | 36 | void setup() { 37 | pinMode(LEDPin, OUTPUT); 38 | pinMode(LDRPin, INPUT); 39 | } 40 | 41 | void loop() { 42 | int input = analogRead(LDRPin); 43 | if (input > threshold) { 44 | digitalWrite(LEDPin, HIGH); 45 | } 46 | else { 47 | digitalWrite(LEDPin, LOW); 48 | } 49 | } 50 | ``` 51 | 52 | ```cpp 53 | const long A = 1000; //Resistencia en oscuridad en KΩ 54 | const int B = 15; //Resistencia a la luz (10 Lux) en KΩ 55 | const int Rc = 10; //Resistencia calibracion en KΩ 56 | const int LDRPin = A0; //Pin del LDR 57 | 58 | int V; 59 | int ilum; 60 | 61 | void setup() 62 | { 63 | Serial.begin(115200); 64 | } 65 | 66 | void loop() 67 | { 68 | V = analogRead(LDRPin); 69 | 70 | //ilum = ((long)(1024-V)*A*10)/((long)B*Rc*V); //usar si LDR entre GND y A0 71 | ilum = ((long)V*A*10)/((long)B*Rc*(1024-V)); //usar si LDR entre A0 y Vcc (como en el esquema anterior) 72 | 73 | Serial.println(ilum); 74 | delay(1000); 75 | } 76 | ``` 77 | 78 | 79 | -------------------------------------------------------------------------------- /020_arduino-intermedio/03 - Optico/01 - medir-cantidad-de-luxes-con-arduino-y-el-luxometro-bh1750.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/medir-cantidad-de-luxes-con-arduino-y-el-luxometro-bh1750/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Mostrar nivel de lux 8 | ```cpp 9 | #include 10 | #include 11 | 12 | BH1750 luxometro; 13 | 14 | const byte luxMode = BH1750_CONTINUOUS_HIGH_RES_MODE; 15 | // BH1750_CONTINUOUS_HIGH_RES_MODE 16 | // BH1750_CONTINUOUS_HIGH_RES_MODE_2 17 | // BH1750_CONTINUOUS_LOW_RES_MODE 18 | // BH1750_ONE_TIME_HIGH_RES_MODE 19 | // BH1750_ONE_TIME_HIGH_RES_MODE_2 20 | // BH1750_ONE_TIME_LOW_RES_MODE 21 | 22 | void setup() { 23 | Serial.begin(9600); 24 | Serial.println(F("Inicializando sensor...")); 25 | luxometro.begin(luxMode); // Inicializar BH1750 26 | } 27 | 28 | void loop() { 29 | uint16_t lux = luxometro.readLightLevel(); // Lectura del BH1750 30 | Serial.print(F("Iluminancia: ")); 31 | Serial.print(lux); 32 | Serial.println(" lx"); 33 | delay(500); 34 | } 35 | ``` 36 | 37 | 38 | ## Encender un dispositivo con el luxómetro 39 | ```cpp 40 | #include 41 | #include 42 | 43 | BH1750 luxometro;; 44 | const byte luxMode = BH1750_CONTINUOUS_HIGH_RES_MODE; 45 | 46 | const uint16_t lowThreshold = 20; 47 | const uint16_t highThreshold = 50; 48 | 49 | const int pinOut = LED_BUILTIN; 50 | 51 | void setup() { 52 | Serial.begin(9600); 53 | Serial.println(F("Inicializando sensor...")); 54 | luxometro.begin(luxMode); // Iniciar BH1750 55 | } 56 | 57 | void setup() { 58 | Serial.begin(9600); 59 | Serial.println(F("Inicializando sensor...")); 60 | luxometro.begin(BH1750_CONTINUOUS_HIGH_RES_MODE); // Iniciar sens el sensor 61 | pinMode(pinOut, OUTPUT); 62 | digitalWrite(pinOut, LOW); 63 | } 64 | 65 | void loop() { 66 | uint16_t lux = luxometro.readLightLevel(); // Lectura iluminancia 67 | 68 | if (lux < lowThreshold) 69 | { 70 | digitalWrite(pinOut, HIGH); 71 | } 72 | else if (lux > highThreshold) 73 | { 74 | digitalWrite(pinOut, LOW); 75 | } 76 | delay(500); 77 | } 78 | ``` 79 | 80 | 81 | -------------------------------------------------------------------------------- /020_arduino-intermedio/03 - Optico/02 - arduino-detector-lineas-tcrt5000l.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-detector-lineas-tcrt5000l/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```csharp 9 | const int sensorPin = 9; 10 | 11 | void setup() { 12 | Serial.begin(9600); //iniciar puerto serie 13 | pinMode(sensorPin, INPUT); //definir pin como entrada 14 | } 15 | 16 | void loop(){ 17 | int value = 0; 18 | value = digitalRead(sensorPin ); //lectura digital de pin 19 | 20 | if (value == LOW) { 21 | Serial.println("TCRT5000L activado"); //zona oscura 22 | } 23 | delay(1000); 24 | } 25 | ``` 26 | 27 | 28 | -------------------------------------------------------------------------------- /020_arduino-intermedio/03 - Optico/03 - detector-llama-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/detector-llama-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```csharp 9 | const int sensorPin = 9; 10 | 11 | void setup() 12 | { 13 | Serial.begin(9600); 14 | pinMode(sensorPin, INPUT); 15 | } 16 | 17 | void loop() 18 | { 19 | int humedad = digitalRead(sensorPin); 20 | 21 | //mandar mensaje a puerto serie en función del valor leido 22 | if (humedad == HIGH) 23 | { 24 | Serial.println("Detección"); 25 | //aquí se ejecutarían las acciones 26 | } 27 | delay(1000); 28 | } 29 | ``` 30 | 31 | ```csharp 32 | const int sensorPin = A0; 33 | 34 | void setup() { 35 | Serial.begin(9600); 36 | } 37 | 38 | void loop() 39 | { 40 | int measure = analogRead(sensorPin); 41 | Serial.println(measure); 42 | 43 | if(measure < 500) 44 | { 45 | Serial.println("Detección"); 46 | //hacer las acciones necesarias 47 | } 48 | delay(1000); 49 | } 50 | ``` 51 | 52 | 53 | -------------------------------------------------------------------------------- /020_arduino-intermedio/03 - Optico/04 - medir-color-arduino-colorimetro-tcs3200.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/medir-color-arduino-colorimetro-tcs3200/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | //VCC——5V 10 | //GND——GND 11 | //S0——D3 12 | //S1——D4 13 | //S2——D5 14 | //S3——D6 15 | //OUT——D2 16 | 17 | const int s0 = 8; 18 | const int s1 = 9; 19 | const int s2 = 12; 20 | const int s3 = 11; 21 | const int out = 10; 22 | 23 | byte countRed = 0; 24 | byte countGreen = 0; 25 | byte countBlue = 0; 26 | 27 | void setup() { 28 | Serial.begin(9600); 29 | pinMode(s0, OUTPUT); 30 | pinMode(s1, OUTPUT); 31 | pinMode(s2, OUTPUT); 32 | pinMode(s3, OUTPUT); 33 | pinMode(out, INPUT); 34 | digitalWrite(s0, HIGH); 35 | digitalWrite(s1, HIGH); 36 | } 37 | 38 | void loop() { 39 | getColor(); 40 | Serial.print("Red: "); 41 | Serial.print(countRed, DEC); 42 | Serial.print("Green: "); 43 | Serial.print(countGreen, DEC); 44 | Serial.print("Blue: "); 45 | Serial.print(countBlue, DEC); 46 | 47 | if (countRed < countBlue && countGreen > 100 && countRed < 80) 48 | { 49 | Serial.println(" - Red"); 50 | } 51 | else if (countBlue < countRed && countBlue < countGreen) 52 | { 53 | Serial.println(" - Blue"); 54 | } 55 | else if (countGreen < countRed && countGreen < countBlue) 56 | { 57 | Serial.println(" - Green"); 58 | } 59 | else { 60 | Serial.println("-"); 61 | } 62 | delay(300); 63 | } 64 | 65 | void getColor() 66 | { 67 | digitalWrite(s2, LOW); 68 | digitalWrite(s3, LOW); 69 | countRed = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH); 70 | digitalWrite(s3, HIGH); 71 | countBlue = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH); 72 | digitalWrite(s2, HIGH); 73 | countGreen = pulseIn(out, digitalRead(out) == HIGH ? LOW : HIGH); 74 | } 75 | ``` 76 | 77 | 78 | -------------------------------------------------------------------------------- /020_arduino-intermedio/04 - Distancia/00 - medir-distancia-con-arduino-y-sensor-de-ultrasonidos-hc-sr04.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/medir-distancia-con-arduino-y-sensor-de-ultrasonidos-hc-sr04/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Sin librerías 8 | ```cpp 9 | const int EchoPin = 5; 10 | const int TriggerPin = 6; 11 | 12 | void setup() { 13 | Serial.begin(9600); 14 | pinMode(TriggerPin, OUTPUT); 15 | pinMode(EchoPin, INPUT); 16 | } 17 | 18 | void loop() { 19 | int cm = ping(TriggerPin, EchoPin); 20 | Serial.print("Distancia: "); 21 | Serial.println(cm); 22 | delay(1000); 23 | } 24 | 25 | int ping(int TriggerPin, int EchoPin) { 26 | long duration, distanceCm; 27 | 28 | digitalWrite(TriggerPin, LOW); //para generar un pulso limpio ponemos a LOW 4us 29 | delayMicroseconds(4); 30 | digitalWrite(TriggerPin, HIGH); //generamos Trigger (disparo) de 10us 31 | delayMicroseconds(10); 32 | digitalWrite(TriggerPin, LOW); 33 | 34 | duration = pulseIn(EchoPin, HIGH); //medimos el tiempo entre pulsos, en microsegundos 35 | 36 | distanceCm = duration * 10 / 292/ 2; //convertimos a distancia, en cm 37 | return distanceCm; 38 | } 39 | ``` 40 | 41 | 42 | ## Con librería NewPing 43 | ```cpp 44 | #include 45 | 46 | const int UltrasonicPin = 5; 47 | const int MaxDistance = 200; 48 | 49 | NewPing sonar(UltrasonicPin, UltrasonicPin, MaxDistance); 50 | 51 | void setup() { 52 | Serial.begin(9600); 53 | } 54 | 55 | void loop() { 56 | delay(50); // esperar 50ms entre pings (29ms como minimo) 57 | Serial.print(sonar.ping_cm()); // obtener el valor en cm (0 = fuera de rango) 58 | Serial.println("cm"); 59 | } 60 | ``` 61 | 62 | 63 | -------------------------------------------------------------------------------- /020_arduino-intermedio/04 - Distancia/01 - detectar-obstaculos-con-sensor-infrarrojo-y-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/detectar-obstaculos-con-sensor-infrarrojo-y-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```csharp 9 | const int sensorPin = 9; 10 | 11 | void setup() { 12 | Serial.begin(9600); //iniciar puerto serie 13 | pinMode(sensorPin , INPUT); //definir pin como entrada 14 | } 15 | 16 | void loop(){ 17 | int value = 0; 18 | value = digitalRead(sensorPin ); //lectura digital de pin 19 | 20 | if (value == HIGH) { 21 | Serial.println("Detectado obstaculo"); 22 | } 23 | delay(1000); 24 | } 25 | ``` 26 | 27 | 28 | -------------------------------------------------------------------------------- /020_arduino-intermedio/04 - Distancia/02 - arduino-sharp-gp2y0a02yk0f.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-sharp-gp2y0a02yk0f/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```csharp 9 | const int sensorPin = A0; 10 | const long referenceMv = 5000; 11 | 12 | void setup() { 13 | Serial.begin(9600); 14 | pinMode(ledPin, OUTPUT); 15 | } 16 | 17 | void loop() { 18 | //lectura de la tensión 19 | int val = analogRead(sensorPin); 20 | int mV = (val * referenceMv) / 1023; 21 | int cm = getDistance(mV); 22 | 23 | 24 | //mostrar valores por pantalla 25 | Serial.print(mV); 26 | Serial.print(","); 27 | Serial.println(cm); 28 | 29 | delay(1000); 30 | } 31 | 32 | //interpolación de la distancia a intervalos de 250mV 33 | const int TABLE_ENTRIES = 12; 34 | const int INTERVAL = 250; 35 | static int distance[TABLE_ENTRIES] = {150,140,130,100,60,50,40,35,30,25,20,15}; 36 | 37 | int getDistance(int mV) { 38 | if (mV > INTERVAL * TABLE_ENTRIES - 1) return distance[TABLE_ENTRIES - 1]; 39 | else { 40 | int index = mV / INTERVAL; 41 | float frac = (mV % 250) / (float)INTERVAL; 42 | return distance[index] - ((distance[index] - distance[index + 1]) * frac); 43 | } 44 | } 45 | ``` 46 | 47 | 48 | -------------------------------------------------------------------------------- /020_arduino-intermedio/04 - Distancia/03 - medir-distancia-con-arduino-y-el-sensor-gp2y0e03.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/medir-distancia-con-arduino-y-el-sensor-gp2y0e03/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | const int sensorPin = A0; 10 | void setup() 11 | { 12 | Serial.begin(9600); 13 | pinMode(sensorPin, INPUT); 14 | } 15 | 16 | void loop() 17 | { 18 | auto raw = analogRead(sensorPin); 19 | Serial.println(raw); 20 | 21 | delay(100); 22 | } 23 | ``` 24 | 25 | ```cpp 26 | #include 27 | 28 | // 7 highest bits 29 | 30 | #define ADDRESS (0x80 >> 1) 31 | 32 | 33 | #define SHIFT_ADDR 0x35 34 | 35 | #define DISTANCE_ADDR 0x5E 36 | 37 | #define RIGHT_EDGE_ADDR 0xF8 // C 38 | 39 | #define LEFT_EDGE_ADDR 0xF9 // A 40 | 41 | #define PEAK_EDGE_ADDR 0xFA // B 42 | 43 | uint8_t distance_raw[2] = { 0 }; 44 | uint8_t shift = 0; 45 | uint8_t distance_cm = 0; 46 | char buf[100]; 47 | 48 | void setup() 49 | { 50 | Wire.begin(); 51 | Serial.begin(9600); 52 | 53 | delay(2000); 54 | 55 | Serial.println("Initializing"); 56 | 57 | Wire.beginTransmission(ADDRESS); 58 | Wire.write(byte(SHIFT_ADDR)); 59 | Wire.endTransmission(); 60 | 61 | Wire.requestFrom(ADDRESS, 1); 62 | if (1 <= Wire.available()) 63 | { 64 | shift = Wire.read(); 65 | } 66 | 67 | Serial.print("Read shift bit: "); 68 | Serial.println(shift, HEX); 69 | } 70 | 71 | void loop() 72 | { 73 | // Read basic measurement 74 | Wire.beginTransmission(ADDRESS); 75 | Wire.write(byte(DISTANCE_ADDR)); 76 | Wire.endTransmission(); 77 | 78 | Wire.requestFrom(ADDRESS, 2); 79 | 80 | if (2 <= Wire.available()) 81 | { 82 | distance_raw[0] = Wire.read(); 83 | distance_raw[1] = Wire.read(); 84 | 85 | // Print distance in cm 86 | distance_cm = (distance_raw[0] * 16 + distance_raw[1]) / 16 / (int)pow(2, shift); 87 | sprintf(buf, "Distance %u cm", distance_cm); 88 | Serial.println(buf); 89 | } 90 | else 91 | { 92 | Serial.println("Read error"); 93 | } 94 | delay(1000); 95 | } 96 | ``` 97 | 98 | 99 | -------------------------------------------------------------------------------- /020_arduino-intermedio/04 - Distancia/04 - arduino-sensor-distancia-vl53l0x.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-sensor-distancia-vl53l0x/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | #include "Adafruit_VL53L0X.h" 10 | 11 | Adafruit_VL53L0X lox = Adafruit_VL53L0X(); 12 | 13 | void setup() { 14 | Serial.begin(9600); 15 | 16 | // Iniciar sensor 17 | Serial.println("VL53L0X test"); 18 | if (!lox.begin()) { 19 | Serial.println(F("Error al iniciar VL53L0X")); 20 | while(1); 21 | } 22 | } 23 | 24 | void loop() { 25 | VL53L0X_RangingMeasurementData_t measure; 26 | 27 | Serial.print("Leyendo sensor... "); 28 | lox.rangingTest(&measure, false); // si se pasa true como parametro, muestra por puerto serie datos de debug 29 | 30 | if (measure.RangeStatus != 4) 31 | { 32 | Serial.print("Distancia (mm): "); 33 | Serial.println(measure.RangeMilliMeter); 34 | } 35 | else 36 | { 37 | Serial.println(" Fuera de rango "); 38 | } 39 | 40 | delay(100); 41 | } 42 | ``` 43 | 44 | 45 | -------------------------------------------------------------------------------- /020_arduino-intermedio/05 - Inercial/00 - medir-inclinacion-con-arduino-y-sensor-tilt-sw-520d.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/medir-inclinacion-con-arduino-y-sensor-tilt-sw-520d/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplo de código 8 | ```cpp 9 | const int SensorPin = 2; 10 | const int LEDPin = 13; 11 | 12 | void setup() { 13 | pinMode(SensorPin , INPUT); 14 | digitalWrite(SensorPin , HIGH); //activamos la resistencia interna PULL UP 15 | pinMode(LEDPin, OUTPUT); 16 | } 17 | 18 | void loop() { 19 | if (digitalRead(SensorPin)) { 20 | digitalWrite(LEDPin, HIGH); 21 | } else { 22 | digitalWrite(LEDPin, LOW); 23 | } 24 | } 25 | ``` 26 | 27 | 28 | -------------------------------------------------------------------------------- /020_arduino-intermedio/05 - Inercial/01 - arduino-acelerometro-adxl345.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-acelerometro-adxl345/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | // Gnd - GND 10 | // 3.3v - VCC 11 | // 3.3v - CS 12 | // Analog 4 - SDA 13 | // Analog 5 - SLC 14 | 15 | #include 16 | 17 | //Direccion del dispositivo 18 | const int DEVICE_ADDRESS = (0x53); 19 | 20 | byte _buff[6]; 21 | 22 | //Direcciones de los registros del ADXL345 23 | char POWER_CTL = 0x2D; 24 | char DATA_FORMAT = 0x31; 25 | char DATAX0 = 0x32; //X-Axis Data 0 26 | char DATAX1 = 0x33; //X-Axis Data 1 27 | char DATAY0 = 0x34; //Y-Axis Data 0 28 | char DATAY1 = 0x35; //Y-Axis Data 1 29 | char DATAZ0 = 0x36; //Z-Axis Data 0 30 | char DATAZ1 = 0x37; //Z-Axis Data 1 31 | 32 | void setup() 33 | { 34 | Serial.begin(57000); 35 | Serial.print("Iniciado"); 36 | 37 | Wire.begin(); 38 | writeTo(DEVICE_ADDRESS, DATA_FORMAT, 0x01); //Poner ADXL345 en +- 4G 39 | writeTo(DEVICE_ADDRESS, POWER_CTL, 0x08); //Poner el ADXL345 40 | } 41 | 42 | void loop() 43 | { 44 | readAccel(); //Leer aceleracion x, y, z 45 | delay(500); 46 | } 47 | 48 | void readAccel() { 49 | //Leer los datos 50 | uint8_t numBytesToRead = 6; 51 | readFrom(DEVICE_ADDRESS, DATAX0, numBytesToRead, _buff); 52 | 53 | //Leer los valores del registro y convertir a int (Cada eje tiene 10 bits, en 2 Bytes LSB) 54 | int x = (((int)_buff[1]) << 8) | _buff[0]; 55 | int y = (((int)_buff[3]) << 8) | _buff[2]; 56 | int z = (((int)_buff[5]) << 8) | _buff[4]; 57 | Serial.print("x: "); 58 | Serial.print( x ); 59 | Serial.print(" y: "); 60 | Serial.print( y ); 61 | Serial.print(" z: "); 62 | Serial.println( z ); 63 | } 64 | 65 | //Funcion auxiliar de escritura 66 | void writeTo(int device, byte address, byte val) { 67 | Wire.beginTransmission(device); 68 | Wire.write(address); 69 | Wire.write(val); 70 | Wire.endTransmission(); 71 | } 72 | 73 | //Funcion auxiliar de lectura 74 | void readFrom(int device, byte address, int num, byte _buff[]) { 75 | Wire.beginTransmission(device); 76 | Wire.write(address); 77 | Wire.endTransmission(); 78 | 79 | Wire.beginTransmission(device); 80 | Wire.requestFrom(device, num); 81 | 82 | int i = 0; 83 | while(Wire.available()) 84 | { 85 | _buff[i] = Wire.read(); 86 | i++; 87 | } 88 | Wire.endTransmission(); 89 | } 90 | ``` 91 | 92 | ```cpp 93 | #include 94 | #include 95 | #include 96 | 97 | ADXL345 adxl = ADXL345(); 98 | 99 | void setup() 100 | { 101 | Serial.begin(9600); 102 | Serial.println("Iniciar"); 103 | Serial.println(); 104 | 105 | adxl.powerOn(); 106 | adxl.setRangeSetting(16); //Definir el rango, valores 2, 4, 8 o 16 107 | } 108 | 109 | void loop() 110 | { 111 | //leer los valores e imprimirlos 112 | int x, y, z; 113 | adxl.readAccel(&x, &y, &z); 114 | Serial.print(x); 115 | Serial.print(", "); 116 | Serial.print(y); 117 | Serial.print(", "); 118 | Serial.println(z); 119 | } 120 | ``` 121 | 122 | 123 | -------------------------------------------------------------------------------- /020_arduino-intermedio/05 - Inercial/02 - arduino-acelerometro-mma7455.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-acelerometro-mma7455/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | #include 10 | #include 11 | 12 | MMA_7455 accel = MMA_7455(i2c_protocol); 13 | float xg, yg, zg; 14 | 15 | void setup() 16 | { 17 | Serial.begin(9600); 18 | accel.begin(); 19 | accel.setSensitivity(2); //Definir el rango, valores 2, 4 o 8 20 | accel.setMode(measure); 21 | accel.setAxisOffset(0, 0, 0); 22 | } 23 | 24 | void loop() 25 | { 26 | //leer los valores e imprimirlos 27 | xg = accel.readAxis10g('x'); 28 | yg = accel.readAxis10g('y'); 29 | zg = accel.readAxis10g('z'); 30 | 31 | Serial.print("\tXg: "); Serial.print(xg, DEC); 32 | Serial.print("\tYg: "); Serial.print(yg, DEC); 33 | Serial.print("\tZg: "); Serial.print(zg, DEC); 34 | Serial.println(); 35 | delay(500); 36 | } 37 | ``` 38 | 39 | 40 | -------------------------------------------------------------------------------- /020_arduino-intermedio/05 - Inercial/04 - brujula-magnetica-con-arduino-compass-digital-hmc5883.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/brujula-magnetica-con-arduino-compass-digital-hmc5883/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | //GND - GND 10 | //VCC - VCC 11 | //SDA - Pin A4 12 | //SCL - Pin A5 13 | 14 | #include "Wire.h" 15 | #include "I2Cdev.h" 16 | #include "HMC5883L.h" 17 | 18 | HMC5883L compass; 19 | 20 | int16_t mx, my, mz; 21 | 22 | void setup() 23 | { 24 | 25 | Serial.begin(9600); 26 | Wire.begin(); 27 | compass.initialize(); 28 | } 29 | 30 | void loop() 31 | { 32 | //Obtener componentes del campo magnético 33 | compass.getHeading(&mx, &my, &mz); 34 | 35 | Serial.print("mx:"); 36 | Serial.print(mx); 37 | Serial.print("tmy:"); 38 | Serial.print(my); 39 | Serial.print("tmz:"); 40 | Serial.println(mz); 41 | delay(100); 42 | } 43 | ``` 44 | 45 | 46 | ## Obtener la orientación respecto al norte 47 | ```cpp 48 | //GND - GND 49 | //VCC - VCC 50 | //SDA - Pin A4 51 | //SCL - Pin A5 52 | 53 | #include "Wire.h" 54 | #include "I2Cdev.h" 55 | #include "HMC5883L.h" 56 | 57 | HMC5883L compass; 58 | 59 | int16_t mx, my, mz; 60 | 61 | //declinacion en grados en tu posición 62 | const float declinacion = 0.12; 63 | 64 | void setup() 65 | { 66 | Serial.begin(9600); 67 | Wire.begin(); 68 | compass .initialize(); 69 | } 70 | 71 | void loop() { 72 | //Obtener componentes del campo magnético 73 | compass .getHeading(&mx, &my, &mz); 74 | 75 | //Calcular ángulo el ángulo del eje X respecto al norte 76 | float angulo = atan2(my, mx); 77 | angulo = angulo * RAD_TO_DEG; 78 | angulo = angulo - declinacion; 79 | 80 | if(angulo < 0) angulo = angulo + 360; 81 | 82 | Serial.print("N:"); 83 | Serial.println(angulo,0); 84 | } 85 | ``` 86 | 87 | 88 | -------------------------------------------------------------------------------- /020_arduino-intermedio/05 - Inercial/06 - usar-arduino-y-el-imu-9-ejes-l3gd20-lsm303d.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/usar-arduino-y-el-imu-9-ejes-l3gd20-lsm303d/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | Adafruit_9DOF dof = Adafruit_9DOF(); 16 | Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(30301); 17 | Adafruit_LSM303_Mag_Unified mag = Adafruit_LSM303_Mag_Unified(30302); 18 | 19 | void initSensors() 20 | { 21 | if(!accel.begin()) 22 | { 23 | Serial.println(F("Ooops, no LSM303 detected ... Check your wiring!")); 24 | while(1); 25 | } 26 | if(!mag.begin()) 27 | { 28 | Serial.println("Ooops, no LSM303 detected ... Check your wiring!"); 29 | while(1); 30 | } 31 | } 32 | 33 | void setup(void) 34 | { 35 | Serial.begin(115200); 36 | Serial.println(F("Adafruit 9 DOF Pitch/Roll/Heading Example")); 37 | Serial.println(""); 38 | 39 | initSensors(); // iniciar sensor 40 | } 41 | 42 | void loop(void) 43 | { 44 | sensors_event_t accel_event; 45 | sensors_event_t mag_event; 46 | sensors_vec_t orientation; 47 | 48 | // leer el estado de los sensores 49 | accel.getEvent(&accel_event); 50 | mag.getEvent(&mag_event); 51 | 52 | // usar el algoritmo de fusion de la libreria para combinar las mediciones 53 | if (dof.fusionGetOrientation(&accel_event, &mag_event, &orientation)) 54 | { 55 | /* 'orientation' should have valid .roll and .pitch fields */ 56 | Serial.print(F("Orientation: ")); 57 | Serial.print(orientation.roll); 58 | Serial.print(F(" ")); 59 | Serial.print(orientation.pitch); 60 | Serial.print(F(" ")); 61 | Serial.print(orientation.heading); 62 | Serial.println(F("")); 63 | } 64 | 65 | delay(100); 66 | } 67 | ``` 68 | 69 | 70 | -------------------------------------------------------------------------------- /020_arduino-intermedio/06 - Movimiento/00 - medir-vibracion-con-arduino-y-sensor-sw-18020p.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/medir-vibracion-con-arduino-y-sensor-sw-18020p/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplo de código 8 | ```cpp 9 | const int sensorPin = 2; 10 | const int ledPin = 13; 11 | 12 | int tiltSensorPreviousValue = 0; 13 | int tiltSensorCurrentValue = 0; 14 | long lastTimeMoved = 0; 15 | int shakeTime = 50; 16 | 17 | void setup() { 18 | pinMode(sensorPin, INPUT); 19 | digitalWrite(sensorPin, HIGH); //activamos la resistencia interna PULL UP 20 | pinMode(ledPin, OUTPUT); 21 | } 22 | 23 | void loop() { 24 | tiltSensorCurrentValue = digitalRead(sensorPin); 25 | if (tiltSensorPreviousValue != tiltSensorCurrentValue) { 26 | lastTimeMoved = millis(); 27 | tiltSensorPreviousValue = tiltSensorCurrentValue; 28 | } 29 | if (millis() - lastTimeMoved < shakeTime) { 30 | digitalWrite(ledPin, HIGH); 31 | } 32 | else { 33 | digitalWrite(ledPin, LOW); 34 | } 35 | } 36 | ``` 37 | 38 | 39 | -------------------------------------------------------------------------------- /020_arduino-intermedio/06 - Movimiento/01 - detector-de-movimiento-con-arduino-y-sensor-pir.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/detector-de-movimiento-con-arduino-y-sensor-pir/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplo de código 8 | ```cpp 9 | const int LEDPin= 13; 10 | const int PIRPin= 2; 11 | 12 | void setup() 13 | { 14 | pinMode(LEDPin, OUTPUT); 15 | pinMode(PIRPin, INPUT); 16 | } 17 | 18 | void loop() 19 | { 20 | int value= digitalRead(PIRPin); 21 | 22 | if (value == HIGH) 23 | { 24 | digitalWrite(LEDPin, HIGH); 25 | delay(50); 26 | digitalWrite(LEDPin, LOW); 27 | delay(50); 28 | } 29 | else 30 | { 31 | digitalWrite(LEDPin, LOW); 32 | } 33 | } 34 | ``` 35 | 36 | ```cpp 37 | const int LEDPin = 13; // pin para el LED 38 | const int PIRPin = 2; // pin de entrada (for PIR sensor) 39 | 40 | int pirState = LOW; // de inicio no hay movimiento 41 | int val = 0; // estado del pin 42 | 43 | void setup() 44 | { 45 | pinMode(LEDPin, OUTPUT); 46 | pinMode(PIRPin, INPUT); 47 | Serial.begin(9600); 48 | } 49 | 50 | void loop() 51 | { 52 | val = digitalRead(PIRPin); 53 | if (val == HIGH) //si está activado 54 | { 55 | digitalWrite(LEDPin, HIGH); //LED ON 56 | if (pirState == LOW) //si previamente estaba apagado 57 | { 58 | Serial.println("Sensor activado"); 59 | pirState = HIGH; 60 | } 61 | } 62 | else //si esta desactivado 63 | { 64 | digitalWrite(LEDPin, LOW); // LED OFF 65 | if (pirState == HIGH) //si previamente estaba encendido 66 | { 67 | Serial.println("Sensor parado"); 68 | pirState = LOW; 69 | } 70 | } 71 | } 72 | ``` 73 | 74 | 75 | -------------------------------------------------------------------------------- /020_arduino-intermedio/06 - Movimiento/02 - arduino-detector-movimiento-rcwl-0516.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-detector-movimiento-rcwl-0516/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | const int LEDPin = 13; 10 | const int RadarPin = 2; 11 | 12 | void setup() 13 | { 14 | pinMode(LEDPin, OUTPUT); 15 | pinMode(RadarPin, INPUT); 16 | } 17 | 18 | void loop() 19 | { 20 | int value= digitalRead(RadarPin); 21 | 22 | if (value == HIGH) 23 | { 24 | digitalWrite(LEDPin, HIGH); 25 | delay(50); 26 | digitalWrite(LEDPin, LOW); 27 | delay(50); 28 | } 29 | else 30 | { 31 | digitalWrite(LEDPin, LOW); 32 | } 33 | } 34 | ``` 35 | 36 | 37 | -------------------------------------------------------------------------------- /020_arduino-intermedio/07 - Tactil _ Gestos/00 - interruptor-touchless-con-arduino-y-sensor-capacitivo.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/interruptor-touchless-con-arduino-y-sensor-capacitivo/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | const int sensorPin = 9; 10 | 11 | void setup() 12 | { 13 | Serial.begin(9600); 14 | pinMode(sensorPin, INPUT); 15 | } 16 | 17 | void loop() 18 | { 19 | int estado = digitalRead(sensorPin); 20 | 21 | //mandar mensaje a puerto serie en función del valor leido 22 | if (estado == HIGH) 23 | { 24 | Serial.println("Contacto detectado"); 25 | //aquí se ejecutarían las acciones 26 | } 27 | delay(1000); 28 | } 29 | ``` 30 | 31 | 32 | -------------------------------------------------------------------------------- /020_arduino-intermedio/07 - Tactil _ Gestos/01 - arduino-mpr121.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-mpr121/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | #include 10 | #include "Adafruit_MPR121.h" 11 | 12 | Adafruit_MPR121 mpr121 = Adafruit_MPR121(); 13 | uint8_t mpr121Address = 0x5A; 14 | 15 | uint16_t lasttouched = 0; 16 | uint16_t currtouched = 0; 17 | 18 | void setup() { 19 | Serial.begin(9600); 20 | 21 | // Iniciar el sensor 22 | if (!mpr121.begin(mpr121Address)) { 23 | Serial.println("MPR121 no encontrado"); 24 | while (1); 25 | } 26 | Serial.println("MPR121 iniciado"); 27 | } 28 | 29 | // Devuelve true si el pad se ha tocado 30 | bool isPressed(uint8_t channel) 31 | { 32 | return bitRead(currtouched, channel) && !bitRead(lasttouched, channel) 33 | } 34 | 35 | // Devuelve true si el pad se ha dejado de tocar 36 | bool isReleased(uint8_t channel) 37 | { 38 | return !bitRead(currtouched, channel) && bitRead(lasttouched, channel) 39 | } 40 | 41 | void loop() 42 | { 43 | // Obtener los datos del sensor 44 | mpr121.updateTouchData(); 45 | currtouched = mpr121.touched(); 46 | 47 | // Comprobamos los cambios en todos los canales 48 | for (uint8_t sensorChannel = 0; sensorChannel < 12; i++) 49 | { 50 | if (isPressed(sensorChannel) ) 51 | { 52 | Serial.print(sensorChannel ); 53 | Serial.println(" tocado"); 54 | } 55 | 56 | if (isReleased(sensorChannel)) 57 | { 58 | Serial.print(sensorChannel); 59 | Serial.println(" soltado"); 60 | } 61 | } 62 | 63 | lasttouched = currtouched; 64 | } 65 | ``` 66 | 67 | 68 | -------------------------------------------------------------------------------- /020_arduino-intermedio/07 - Tactil _ Gestos/02 - detectar-gestos-con-arduino-y-sensor-apds-9960.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/detectar-gestos-con-arduino-y-sensor-apds-9960/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Mostrar por puerto de serie 8 | ```cpp 9 | #include "Adafruit_APDS9960.h" 10 | Adafruit_APDS9960 apds; 11 | 12 | void setup() { 13 | Serial.begin(115200); 14 | 15 | if(!apds.begin()) Serial.println("failed to initialize device! Please check your wiring."); 16 | apds.enableProximity(true); 17 | apds.enableGesture(true); 18 | } 19 | 20 | void loop() { 21 | uint8_t gesture = apds.readGesture(); 22 | if(gesture == APDS9960_DOWN) Serial.println("DOWN"); 23 | if(gesture == APDS9960_UP) Serial.println("UP"); 24 | if(gesture == APDS9960_LEFT) Serial.println("LEFT"); 25 | if(gesture == APDS9960_RIGHT) Serial.println("RIGHT"); 26 | } 27 | ``` 28 | 29 | 30 | ## Mostrar por Led integrado 31 | ```cpp 32 | #include "Adafruit_APDS9960.h" 33 | Adafruit_APDS9960 apds; 34 | 35 | void setup() 36 | { 37 | Serial.begin(115200); 38 | 39 | pinMode(LED_BUILTIN, OUTPUT); 40 | 41 | if(!apds.begin()) Serial.println("failed to initialize device! Please check your wiring."); 42 | apds.enableProximity(true); 43 | apds.enableGesture(true); 44 | } 45 | 46 | void loop() 47 | { 48 | uint8_t gesture = apds.readGesture(); 49 | if(gesture == APDS9960_DOWN) blink(1); 50 | if(gesture == APDS9960_UP) blink(2); 51 | if(gesture == APDS9960_LEFT) blink(3); 52 | if(gesture == APDS9960_RIGHT) blink(4); 53 | } 54 | 55 | void blink(int count) 56 | { 57 | for(int i = 0; i < count; i++) 58 | { 59 | digitalWrite(LED_BUILTIN, HIGH); 60 | delay(100); 61 | digitalWrite(LED_BUILTIN, LOW); 62 | delay(100); 63 | } 64 | } 65 | ``` 66 | 67 | 68 | -------------------------------------------------------------------------------- /020_arduino-intermedio/08 - Ambiental/00 - medir-temperatura-con-arduino-y-termistor-mf52.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/medir-temperatura-con-arduino-y-termistor-mf52/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | #include 10 | 11 | const int Rc = 10000; //valor de la resistencia 12 | const int Vcc = 5; 13 | const int SensorPIN = A0; 14 | 15 | float A = 1.11492089e-3; 16 | float B = 2.372075385e-4; 17 | float C = 6.954079529e-8; 18 | 19 | float K = 2.5; //factor de disipacion en mW/C 20 | 21 | void setup() 22 | { 23 | Serial.begin(9600); 24 | } 25 | 26 | void loop() 27 | { 28 | float raw = analogRead(SensorPIN); 29 | float V = raw / 1024 * Vcc; 30 | 31 | float R = (Rc * V ) / (Vcc - V); 32 | 33 | 34 | float logR = log(R); 35 | float R_th = 1.0 / (A + B * logR + C * logR * logR * logR ); 36 | 37 | float kelvin = R_th - V*V/(K * R)*1000; 38 | float celsius = kelvin - 273.15; 39 | 40 | Serial.print("T = "); 41 | Serial.print(celsius); 42 | Serial.print("C\n"); 43 | delay(2500); 44 | } 45 | ``` 46 | 47 | 48 | -------------------------------------------------------------------------------- /020_arduino-intermedio/08 - Ambiental/01 - medir-temperatura-con-arduino-y-sensor-lm35.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/medir-temperatura-con-arduino-y-sensor-lm35/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplo de código 8 | ```cpp 9 | const int sensorPin= A0; 10 | 11 | void setup() 12 | { 13 | Serial.begin(9600); 14 | } 15 | 16 | void loop() 17 | { 18 | int value = analogRead(sensorPin); 19 | float millivolts = (value / 1023.0) * 5000; 20 | float celsius = millivolts / 10; 21 | Serial.print(celsius); 22 | Serial.println(" C"); 23 | delay(1000); 24 | } 25 | ``` 26 | 27 | 28 | -------------------------------------------------------------------------------- /020_arduino-intermedio/08 - Ambiental/02 - arduino-dht11-dht22.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-dht11-dht22/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```csharp 9 | #include "DHT.h" 10 | 11 | // Uncomment whatever type you're using! 12 | //#define DHTTYPE DHT11 // DHT 11 13 | 14 | #define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 15 | //#define DHTTYPE DHT21 // DHT 21 (AM2301) 16 | 17 | // Connect pin 1 (on the left) of the sensor to +5V 18 | // NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1 19 | // to 3.3V instead of 5V! 20 | // Connect pin 2 of the sensor to whatever your DHTPIN is 21 | // Connect pin 4 (on the right) of the sensor to GROUND 22 | // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor 23 | 24 | const int DHTPin = 5; // what digital pin we're connected to 25 | 26 | DHT dht(DHTPin, DHTTYPE); 27 | 28 | void setup() { 29 | Serial.begin(9600); 30 | Serial.println("DHTxx test!"); 31 | 32 | dht.begin(); 33 | } 34 | 35 | void loop() { 36 | // Wait a few seconds between measurements. 37 | delay(2000); 38 | 39 | // Reading temperature or humidity takes about 250 milliseconds! 40 | float h = dht.readHumidity(); 41 | float t = dht.readTemperature(); 42 | 43 | if (isnan(h) || isnan(t)) { 44 | Serial.println("Failed to read from DHT sensor!"); 45 | return; 46 | } 47 | 48 | Serial.print("Humidity: "); 49 | Serial.print(h); 50 | Serial.print(" %\t"); 51 | Serial.print("Temperature: "); 52 | Serial.print(t); 53 | Serial.print(" *C "); 54 | } 55 | ``` 56 | 57 | 58 | -------------------------------------------------------------------------------- /020_arduino-intermedio/08 - Ambiental/03 - usar-el-sensor-de-temperatura-interno-de-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/usar-el-sensor-de-temperatura-interno-de-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## usar-el-sensor-de-temperatura-interno-de-arduino 8 | ```cpp 9 | void setup() 10 | { 11 | Serial.begin(9600); 12 | 13 | Serial.println(F("Internal Temperature Sensor")); 14 | } 15 | 16 | void loop() 17 | { 18 | Serial.println(GetTemp(),1); 19 | delay(1000); 20 | } 21 | 22 | double GetTemp(void) 23 | { 24 | unsigned int wADC; 25 | double t; 26 | 27 | ADMUX = (_BV(REFS1) | _BV(REFS0) | _BV(MUX3)); 28 | ADCSRA |= _BV(ADEN); 29 | delay(20); 30 | ADCSRA |= _BV(ADSC); 31 | while (bit_is_set(ADCSRA,ADSC)); 32 | wADC = ADCW; 33 | 34 | // Esto es la función a calibrar. 35 | t = (wADC - 324.31 ) / 1.22; 36 | return (t); 37 | } 38 | ``` 39 | 40 | 41 | -------------------------------------------------------------------------------- /020_arduino-intermedio/08 - Ambiental/05 - medir-temperatura-y-presion-barometrica-con-arduino-y-bmp280.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/medir-temperatura-y-presion-barometrica-con-arduino-y-bmp280/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Obtener los valores de temperatura, humedad y presión 8 | ```cpp 9 | Adafruit_BMP280 bmp; 10 | 11 | void setup() { 12 | Serial.begin(9600); 13 | Serial.println(F("BMP280 test")); 14 | 15 | if (!bmp.begin()) { 16 | Serial.println(F("Could not find a valid BMP280 sensor, check wiring!")); 17 | while (1); 18 | } 19 | 20 | bmp.setSampling(Adafruit_BMP280::MODE_NORMAL, /* Modo de operación */ 21 | Adafruit_BMP280::SAMPLING_X2, /* Temp. oversampling */ 22 | Adafruit_BMP280::SAMPLING_X16, /* Presion oversampling */ 23 | Adafruit_BMP280::FILTER_X16, /* Filtrado. */ 24 | Adafruit_BMP280::STANDBY_MS_500); /* Tiempo Standby. */ 25 | } 26 | 27 | void loop() 28 | { 29 | Serial.print(F("Temperatura = ")); 30 | Serial.print(bmp.readTemperature()); 31 | Serial.println(" *C"); 32 | 33 | Serial.print(F("Presión = ")); 34 | Serial.print(bmp.readPressure()); 35 | Serial.println(" Pa"); 36 | 37 | Serial.print(F("Altitud = ")); 38 | Serial.print(bmp.readAltitude(1013.25)); 39 | Serial.println(" m"); 40 | 41 | Serial.println(); 42 | delay(2000); 43 | } 44 | ``` 45 | 46 | 47 | -------------------------------------------------------------------------------- /020_arduino-intermedio/08 - Ambiental/06 - arduino-y-el-termometro-infrarrojo-a-distancia-mlx90614.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-y-el-termometro-infrarrojo-a-distancia-mlx90614/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | #include 10 | #include 11 | 12 | Adafruit_MLX90614 mlx = Adafruit_MLX90614(); 13 | 14 | void setup() { 15 | Serial.begin(9600); 16 | 17 | mlx.begin(); 18 | } 19 | 20 | void loop() { 21 | Serial.print("Ambiente = "); 22 | Serial.print(mlx.readAmbientTempC()); 23 | Serial.print("ºC\tObjeto = "); 24 | Serial.print(mlx.readObjectTempC()); 25 | Serial.println("ºC"); 26 | delay(500); 27 | } 28 | ``` 29 | 30 | 31 | -------------------------------------------------------------------------------- /020_arduino-intermedio/08 - Ambiental/07 - arduino-detector-gas-mq.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-detector-gas-mq/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Lectura digital 8 | ```cpp 9 | const int MQ_PIN = 2; 10 | const int MQ_DELAY = 2000; 11 | 12 | void setup() 13 | { 14 | Serial.begin(9600); 15 | } 16 | 17 | void loop() 18 | { 19 | bool state= digitalRead(MQ_PIN); 20 | 21 | if (!state) 22 | { 23 | Serial.println("Deteccion"); 24 | } 25 | else 26 | { 27 | Serial.println("No detectado"); 28 | } 29 | delay(MQ_DELAY); 30 | } 31 | ``` 32 | 33 | 34 | ## Lectura analógica 35 | ```cpp 36 | const int MQ_PIN = A0; 37 | const int MQ_DELAY = 2000; 38 | 39 | void setup() 40 | { 41 | Serial.begin(9600); 42 | } 43 | 44 | void loop() 45 | { 46 | int raw_adc = analogRead(MQ_PIN); 47 | float value_adc = raw_adc * (5.0 / 1023.0); 48 | 49 | Serial.print("Raw:"); 50 | Serial.print(raw_adc); 51 | Serial.print(" Tension:"); 52 | Serial.println(value_adc); 53 | 54 | delay(MQ_DELAY); 55 | } 56 | ``` 57 | 58 | 59 | ## Leer la concentración 60 | ```cpp 61 | const int MQ_PIN = A0; // Pin del sensor 62 | const int RL_VALUE = 5; // Resistencia RL del modulo en Kilo ohms 63 | const int R0 = 10; // Resistencia R0 del sensor en Kilo ohms 64 | 65 | // Datos para lectura multiple 66 | const int READ_SAMPLE_INTERVAL = 100; // Tiempo entre muestras 67 | const int READ_SAMPLE_TIMES = 5; // Numero muestras 68 | 69 | // Ajustar estos valores para vuestro sensor según el Datasheet 70 | // (opcionalmente, según la calibración que hayáis realizado) 71 | const float X0 = 200; 72 | const float Y0 = 1.7; 73 | const float X1 = 10000; 74 | const float Y1 = 0.28; 75 | 76 | // Puntos de la curva de concentración {X, Y} 77 | const float punto0[] = { log10(X0), log10(Y0) }; 78 | const float punto1[] = { log10(X1), log10(Y1) }; 79 | 80 | // Calcular pendiente y coordenada abscisas 81 | const float scope = (punto1[1] - punto0[1]) / (punto1[0] - punto0[0]); 82 | const float coord = punto0[1] - punto0[0] * scope; 83 | 84 | void setup() 85 | { 86 | Serial.begin(9600); 87 | } 88 | 89 | void loop() 90 | { 91 | float rs_med = readMQ(MQ_PIN); // Obtener la Rs promedio 92 | float concentration = getConcentration(rs_med/R0); // Obtener la concentración 93 | 94 | // Mostrar el valor de la concentración por serial 95 | Serial.println("Concentración: "); 96 | Serial.println(concentration); 97 | } 98 | 99 | // Obtener la resistencia promedio en N muestras 100 | float readMQ(int mq_pin) 101 | { 102 | float rs = 0; 103 | for (int i = 0;i Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/sensor-ambiental-arduino-bme280/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Obtener los valores de temperatura, humedad y presión 8 | ```cpp 9 | #include 10 | #include 11 | #include 12 | 13 | Adafruit_BME280 bme; // use I2C interface 14 | Adafruit_Sensor *bme_temp = bme.getTemperatureSensor(); 15 | Adafruit_Sensor *bme_pressure = bme.getPressureSensor(); 16 | Adafruit_Sensor *bme_humidity = bme.getHumiditySensor(); 17 | 18 | void setup() { 19 | Serial.begin(9600); 20 | Serial.println(F("BME280 Sensor event test")); 21 | 22 | if (!bme.begin()) { 23 | Serial.println(F("No se ha encontrado el sensor BME280")); 24 | while (1) delay(10); 25 | } 26 | 27 | bme_temp->printSensorDetails(); 28 | bme_pressure->printSensorDetails(); 29 | bme_humidity->printSensorDetails(); 30 | } 31 | 32 | void loop() { 33 | sensors_event_t temp_event, pressure_event, humidity_event; 34 | bme_temp->getEvent(&temp_event); 35 | bme_pressure->getEvent(&pressure_event); 36 | bme_humidity->getEvent(&humidity_event); 37 | 38 | Serial.print(F("Temperatura = ")); 39 | Serial.print(temp_event.temperature); 40 | Serial.println(" *C"); 41 | 42 | Serial.print(F("Humedad = ")); 43 | Serial.print(humidity_event.relative_humidity); 44 | Serial.println(" %"); 45 | 46 | Serial.print(F("Presion = ")); 47 | Serial.print(pressure_event.pressure); 48 | Serial.println(" hPa"); 49 | 50 | Serial.println(); 51 | delay(1000); 52 | } 53 | ``` 54 | 55 | 56 | -------------------------------------------------------------------------------- /020_arduino-intermedio/08 - Ambiental/10 - medir-calidad-del-aire-y-co2-con-ccs811-y-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/medir-calidad-del-aire-y-co2-con-ccs811-y-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | #include "Adafruit_CCS811.h" 10 | 11 | Adafruit_CCS811 ccs; 12 | 13 | void setup() { 14 | Serial.begin(9600); 15 | 16 | Serial.println("CCS811 test"); 17 | 18 | if(!ccs.begin()){ 19 | Serial.println("Failed to start sensor! Please check your wiring."); 20 | while(1); 21 | } 22 | 23 | // Wait for the sensor to be ready 24 | while(!ccs.available()); 25 | } 26 | 27 | void loop() { 28 | if(ccs.available()){ 29 | if(!ccs.readData()){ 30 | Serial.println(ccs.calculateTemperature();); 31 | Serial.print("ºC, CO2: "); 32 | Serial.print(ccs.geteCO2()); 33 | Serial.print("ppm, TVOC: "); 34 | Serial.println(ccs.getTVOC()); 35 | } 36 | else{ 37 | Serial.println("ERROR!"); 38 | while(1); 39 | } 40 | } 41 | delay(500); 42 | } 43 | ``` 44 | 45 | 46 | -------------------------------------------------------------------------------- /020_arduino-intermedio/09 - Agua _ Liquidos/00 - arduino-lluvia.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-lluvia/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```csharp 9 | const int sensorPin = 9; 10 | 11 | void setup() { 12 | Serial.begin(9600); //iniciar puerto serie 13 | pinMode(pin, INPUT); //definir pin como entrada 14 | } 15 | 16 | void loop(){ 17 | int value = 0; 18 | value = digitalRead(sensorPin ); //lectura digital de pin 19 | 20 | if (value == LOW) { 21 | Serial.println("Detectada lluvia"); 22 | } 23 | delay(1000); 24 | } 25 | ``` 26 | 27 | 28 | -------------------------------------------------------------------------------- /020_arduino-intermedio/09 - Agua _ Liquidos/01 - arduino-humedad-suelo-fc-28.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-humedad-suelo-fc-28/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```csharp 9 | const int sensorPin = A0; 10 | 11 | void setup() { 12 | Serial.begin(9600); 13 | } 14 | 15 | void loop() 16 | { 17 | int humedad = analogRead(sensorPin); 18 | Serial.print(humedad); 19 | 20 | if(humedad < 500) 21 | { 22 | Serial.println("Encendido"); 23 | //hacer las acciones necesarias 24 | } 25 | delay(1000); 26 | } 27 | ``` 28 | 29 | ```csharp 30 | const int sensorPin = 10; 31 | 32 | void setup() 33 | { 34 | Serial.begin(9600); 35 | pinMode(sensorPin, INPUT); 36 | } 37 | 38 | void loop() 39 | { 40 | int humedad = digitalRead(sensorPin); 41 | 42 | //mandar mensaje a puerto serie en función del valor leido 43 | if (humedad == HIGH) 44 | { 45 | Serial.println("Encendido"); 46 | //aquí se ejecutarían las acciones 47 | } 48 | delay(1000); 49 | } 50 | ``` 51 | 52 | 53 | -------------------------------------------------------------------------------- /020_arduino-intermedio/09 - Agua _ Liquidos/02 - sensor-de-humedad-del-suelo-capacitivo-y-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/sensor-de-humedad-del-suelo-capacitivo-y-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Lectura simple 8 | ```cpp 9 | const int sensorPin = A0; 10 | 11 | void setup() 12 | { 13 | Serial.begin(9600); 14 | } 15 | void loop() 16 | { 17 | int humedad = analogRead(sensorPin); 18 | Serial.print(humedad); 19 | delay(1000); 20 | } 21 | ``` 22 | 23 | 24 | ## Porcentaje de humedad 25 | ```cpp 26 | const int sensorPin = A0; 27 | const int humedadAire = 550; 28 | const int humedadAgua = 250; 29 | 30 | void setup() 31 | { 32 | Serial.begin(9600); 33 | } 34 | 35 | void loop() 36 | { 37 | int humedad = analogRead(sensorPin); 38 | Serial.println(humedad); 39 | 40 | porcentajeHumedad = map(humedad, humedadAire, humedadAgua, 0, 100); 41 | if(porcentajeHumedad > 100) porcentajeHumedad = 100; 42 | 43 | Serial.print(porcentajeHumedad); 44 | Serial.println("%"); 45 | } 46 | ``` 47 | 48 | 49 | -------------------------------------------------------------------------------- /020_arduino-intermedio/09 - Agua _ Liquidos/03 - temperatura-liquidos-arduino-ds18b20.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/temperatura-liquidos-arduino-ds18b20/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```csharp 9 | #include 10 | #include 11 | 12 | const int oneWirePin = 5; 13 | 14 | OneWire oneWireBus(oneWirePin); 15 | DallasTemperature sensor(&oneWireBus); 16 | 17 | void setup() { 18 | Serial.begin(9600); 19 | sensor.begin(); 20 | } 21 | 22 | void loop() { 23 | Serial.println("Leyendo temperaturas: "); 24 | sensor.requestTemperatures(); 25 | 26 | Serial.print("Temperatura en sensor 0: "); 27 | Serial.print(sensor.getTempCByIndex(0)); 28 | Serial.println(" ºC"); 29 | 30 | delay(1000); 31 | } 32 | ``` 33 | 34 | ```csharp 35 | #include 36 | 37 | const int oneWirePin = 5; 38 | OneWire oneWireBus(oneWirePin); 39 | 40 | void setup(void) { 41 | Serial.begin(9600); 42 | discoverOneWireDevices(); 43 | } 44 | 45 | void discoverOneWireDevices(void) { 46 | byte i; 47 | byte present = 0; 48 | byte data[12]; 49 | byte addr[8]; 50 | 51 | Serial.println("Buscando dispositivos 1-Wire"); 52 | while(oneWireBus.search(addr)) { 53 | Serial.println("Encontrado dispositivo 1-Wire en direccion"); 54 | for( i = 0; i < 8; i++) { 55 | Serial.print("0x"); 56 | if (addr[i] < 16) { 57 | Serial.print('0'); 58 | } 59 | Serial.print(addr[i], HEX); 60 | if (i < 7) { 61 | Serial.print(", "); 62 | } 63 | } 64 | if ( OneWire::crc8( addr, 7) != addr[7]) { 65 | Serial.print("Error en dispositivo, CRC invalido!\n"); 66 | return; 67 | } 68 | } 69 | Serial.println("Búsqueda finalizada"); 70 | oneWireBus.reset_search(); 71 | return; 72 | } 73 | 74 | void loop(void) { 75 | // nada que hacer aqui 76 | } 77 | ``` 78 | 79 | ```csharp 80 | #include 81 | #include 82 | 83 | const int oneWirePin = 5; 84 | 85 | OneWire oneWireBus(oneWirePin); 86 | DallasTemperature sensors(&oneWireBus); 87 | 88 | DeviceAddress insideThermometer = { 0x28, 0x94, 0xE2, 0xDF, 0x02, 0x00, 0x00, 0xFE }; 89 | DeviceAddress outsideThermometer = { 0x28, 0x6B, 0xDF, 0xDF, 0x02, 0x00, 0x00, 0xC0 }; 90 | 91 | void setup(void) 92 | { 93 | Serial.begin(9600); 94 | sensors.begin(); 95 | sensors.setResolution(insideThermometer, 10); 96 | sensors.setResolution(outsideThermometer, 10); 97 | } 98 | 99 | void printTemperature(DeviceAddress deviceAddress) 100 | { 101 | float tempC = sensors.getTempC(deviceAddress); 102 | if (tempC == -127.00) { 103 | Serial.print("Error getting temperature"); 104 | } else { 105 | Serial.print(tempC); 106 | Serial.println(" ºC"); 107 | } 108 | } 109 | 110 | void loop(void) 111 | { 112 | 113 | Serial.println("Leyendo temperaturas"); 114 | sensors.requestTemperatures(); 115 | 116 | Serial.print("Temperatura interior: "); 117 | printTemperature(insideThermometer); 118 | Serial.print("Temperatura exterior: "); 119 | printTemperature(outsideThermometer); 120 | Serial.println("-------"); 121 | 122 | delay(2000); 123 | } 124 | ``` 125 | 126 | 127 | -------------------------------------------------------------------------------- /020_arduino-intermedio/09 - Agua _ Liquidos/04 - caudal-consumo-de-agua-con-arduino-y-caudalimetro.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/caudal-consumo-de-agua-con-arduino-y-caudalimetro/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Calcular el caudal 8 | ```cpp 9 | const int sensorPin = 2; 10 | const int measureInterval = 2500; 11 | volatile int pulseConter; 12 | 13 | // YF-S201 14 | const float factorK = 7.5; 15 | 16 | // FS300A 17 | //const float factorK = 5.5; 18 | 19 | // FS400A 20 | //const float factorK = 3.5; 21 | 22 | void ISRCountPulse() 23 | { 24 | pulseConter++; 25 | } 26 | 27 | float GetFrequency() 28 | { 29 | pulseConter = 0; 30 | 31 | interrupts(); 32 | delay(measureInterval); 33 | noInterrupts(); 34 | 35 | return (float)pulseConter * 1000 / measureInterval; 36 | } 37 | 38 | void setup() 39 | { 40 | Serial.begin(9600); 41 | attachInterrupt(digitalPinToInterrupt(sensorPin), ISRCountPulse, RISING); 42 | } 43 | 44 | void loop() 45 | { 46 | // obtener frecuencia en Hz 47 | float frequency = GetFrequency(); 48 | 49 | // calcular caudal L/min 50 | float flow_Lmin = frequency / factorK; 51 | 52 | Serial.print("Frecuencia: "); 53 | Serial.print(frequency, 0); 54 | Serial.print(" (Hz)\tCaudal: "); 55 | Serial.print(flow_Lmin, 3); 56 | Serial.println(" (L/min)"); 57 | } 58 | ``` 59 | 60 | 61 | ## Calcular el consumo 62 | ```cpp 63 | const int sensorPin = 2; 64 | const int measureInterval = 2500; 65 | volatile int pulseConter; 66 | 67 | // YF-S201 68 | const float factorK = 7.5; 69 | 70 | // FS300A 71 | //const float factorK = 5.5; 72 | 73 | // FS400A 74 | //const float factorK = 3.5; 75 | 76 | float volume = 0; 77 | long t0 = 0; 78 | 79 | void ISRCountPulse() 80 | { 81 | pulseConter++; 82 | } 83 | 84 | float GetFrequency() 85 | { 86 | pulseConter = 0; 87 | 88 | interrupts(); 89 | delay(measureInterval); 90 | noInterrupts(); 91 | 92 | return (float)pulseConter * 1000 / measureInterval; 93 | } 94 | 95 | void SumVolume(float dV) 96 | { 97 | volume += dV / 60 * (millis() - t0) / 1000.0; 98 | t0 = millis(); 99 | } 100 | 101 | void setup() 102 | { 103 | Serial.begin(9600); 104 | attachInterrupt(digitalPinToInterrupt(sensorPin), ISRCountPulse, RISING); 105 | t0 = millis(); 106 | } 107 | 108 | void loop() 109 | { 110 | // obtener frecuencia en Hz 111 | float frequency = GetFrequency(); 112 | 113 | // calcular caudal L/min 114 | float flow_Lmin = frequency / factorK; 115 | SumVolume(flow_Lmin); 116 | 117 | Serial.print(" Caudal: "); 118 | Serial.print(flow_Lmin, 3); 119 | Serial.print(" (L/min)\tConsumo:"); 120 | Serial.print(volume, 1); 121 | Serial.println(" (L)"); 122 | } 123 | ``` 124 | 125 | 126 | -------------------------------------------------------------------------------- /020_arduino-intermedio/09 - Agua _ Liquidos/05 - bomba-de-agua-con-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/bomba-de-agua-con-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | const int pin = 9; 10 | 11 | void setup() 12 | { 13 | pinMode(pin, OUTPUT); //definir pin como salida 14 | } 15 | 16 | void loop() 17 | { 18 | digitalWrite(pin, HIGH); // poner el Pin en HIGH 19 | delay(10000); // esperar 10 segundos 20 | digitalWrite(pin, LOW); // poner el Pin en LOW 21 | delay(10000); // esperar 10 segundos 22 | } 23 | ``` 24 | 25 | 26 | -------------------------------------------------------------------------------- /020_arduino-intermedio/10 - Intensidad _ Tension/00 - medir-tension-intensidad-y-potencia-con-arduino-y-ina219.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/medir-tension-intensidad-y-potencia-con-arduino-y-ina219/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | #include 10 | #include 11 | 12 | Adafruit_INA219 ina219; 13 | 14 | void setup(void) 15 | { 16 | Serial.begin(115200); 17 | uint32_t currentFrequency; 18 | 19 | // Iniciar el INA219 20 | ina219.begin(); //por defecto, inicia a 32V y 2A 21 | 22 | // Opcionalmente, cambiar la sensibilidad del sensor 23 | //ina219.setCalibration_32V_1A(); 24 | //ina219.setCalibration_16V_400mA(); 25 | 26 | Serial.println("INA219 iniciado..."); 27 | } 28 | 29 | void loop(void) 30 | { 31 | float shuntvoltage = 0; 32 | float busvoltage = 0; 33 | float current_mA = 0; 34 | float loadvoltage = 0; 35 | float power_mW = 0; 36 | 37 | // Obtener mediciones 38 | shuntvoltage = ina219.getShuntVoltage_mV(); 39 | busvoltage = ina219.getBusVoltage_V(); 40 | current_mA = ina219.getCurrent_mA(); 41 | power_mW = ina219.getPower_mW(); 42 | loadvoltage = busvoltage + (shuntvoltage / 1000); 43 | 44 | // Mostrar mediciones 45 | Serial.print("Bus Voltaje: "); Serial.print(busvoltage); Serial.println(" V"); 46 | Serial.print("Shunt Voltaje: "); Serial.print(shuntvoltage); Serial.println(" mV"); 47 | Serial.print("Load Voltaje: "); Serial.print(loadvoltage); Serial.println(" V"); 48 | Serial.print("Corriente: "); Serial.print(current_mA); Serial.println(" mA"); 49 | Serial.print("Potencia: "); Serial.print(power_mW); Serial.println(" mW"); 50 | Serial.println(""); 51 | 52 | delay(2000); 53 | } 54 | ``` 55 | 56 | 57 | -------------------------------------------------------------------------------- /020_arduino-intermedio/10 - Intensidad _ Tension/01 - arduino-intensidad-consumo-electrico-acs712.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-intensidad-consumo-electrico-acs712/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | // Sensibilidad del sensor en V/A 10 | float SENSIBILITY = 0.185; // Modelo 5A 11 | //float SENSIBILITY = 0.100; // Modelo 20A 12 | //float SENSIBILITY = 0.066; // Modelo 30A 13 | 14 | int SAMPLESNUMBER = 100; 15 | 16 | void setup() 17 | { 18 | Serial.begin(9600); 19 | } 20 | 21 | void printMeasure(String prefix, float value, String postfix) 22 | { 23 | Serial.print(prefix); 24 | Serial.print(value, 3); 25 | Serial.println(postfix); 26 | } 27 | 28 | void loop() 29 | { 30 | float current = getCorriente(SAMPLESNUMBER); 31 | float currentRMS = 0.707 * current; 32 | float power = 230.0 * currentRMS; 33 | 34 | printMeasure("Intensidad: ", current, "A ,"); 35 | printMeasure("Irms: ", currentRMS, "A ,"); 36 | printMeasure("Potencia: ", power, "W"); 37 | delay(1000); 38 | } 39 | 40 | float getCorriente(int samplesNumber) 41 | { 42 | float voltage; 43 | float corrienteSum = 0; 44 | for (int i = 0; i < samplesNumber; i++) 45 | { 46 | voltage = analogRead(A0) * 5.0 / 1023.0; 47 | corrienteSum += (voltage - 2.5) / SENSIBILITY; 48 | } 49 | return(corrienteSum / samplesNumber); 50 | } 51 | ``` 52 | 53 | 54 | -------------------------------------------------------------------------------- /020_arduino-intermedio/10 - Intensidad _ Tension/03 - medir-voltajes-de-hasta-25v-con-arduino-y-fz0430.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/medir-voltajes-de-hasta-25v-con-arduino-y-fz0430/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```csharp 9 | const int sensorPin = A0; // seleccionar la entrada para el sensor 10 | int sensorValue; // variable que almacena el valor raw (0 a 1023) 11 | float value; // variable que almacena el voltaje (0.0 a 25.0) 12 | 13 | void setup() { 14 | Serial.begin(9600); 15 | } 16 | 17 | void loop() { 18 | sensorValue = analogRead(sensorPin); // realizar la lectura 19 | value = fmap(sensorValue, 0, 1023, 0.0, 25.0); // cambiar escala a 0.0 - 25.0 20 | 21 | Serial.println(value); // mostrar el valor por serial 22 | delay(1000); 23 | } 24 | 25 | // cambio de escala entre floats 26 | float fmap(float x, float in_min, float in_max, float out_min, float out_max) 27 | { 28 | return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; 29 | } 30 | ``` 31 | 32 | 33 | -------------------------------------------------------------------------------- /020_arduino-intermedio/10 - Intensidad _ Tension/04 - medir-tensiones-de-220v-230v-con-arduino-y-transformador.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/medir-tensiones-de-220v-230v-con-arduino-y-transformador/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Montaje FZ0430 y ADS1115 8 | ```cpp 9 | #include 10 | #include 11 | 12 | Adafruit_ADS1115 ads; 13 | 14 | // const float multiplier = 0.1875F; // Transformador de 15V 15 | const float multiplier = 0.1255F; // Transformador de 12V 16 | 17 | void setup() 18 | { 19 | Serial.begin(115200); 20 | 21 | // ads.setGain(GAIN_TWOTHIRDS); // Transformador de 15V 22 | ads.setGain(GAIN_ONE); // Transformador de 12V 23 | ads.begin(); 24 | } 25 | 26 | void loop() 27 | { 28 | while(1) 29 | { 30 | Serial.print(ads.readADC_Differential_0_1() * multiplier); 31 | } 32 | } 33 | ``` 34 | 35 | 36 | ## Montaje con resistencias y punto medio 37 | ```cpp 38 | const int sensorPin = A0; 39 | int sensorValue; 40 | float value; 41 | 42 | void setup() 43 | { 44 | Serial.begin(9600); 45 | } 46 | 47 | void loop( 48 | { 49 | sensorValue = analogRead(sensorPin); 50 | value = fmap(sensorValue, 0, 1023, -426.2080, +426.2080); 51 | 52 | delay(1); 53 | } 54 | 55 | // cambio de escala entre floats 56 | float fmap(float x, float in_min, float in_max, float out_min, float out_max) 57 | { 58 | return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; 59 | } 60 | ``` 61 | 62 | 63 | -------------------------------------------------------------------------------- /020_arduino-intermedio/10 - Intensidad _ Tension/05 - arduino-cruce-por-cero-h11aa1.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-cruce-por-cero-h11aa1/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Lectura del estado por pool 8 | ```cpp 9 | const int inputPin = 2; 10 | 11 | int value = 0; 12 | 13 | void setup() { 14 | Serial.begin(9600); 15 | pinMode(inputPin, INPUT_PULLUP); 16 | } 17 | 18 | void loop(){ 19 | value = digitalRead(inputPin); //lectura digital de pin 20 | 21 | //mandar mensaje a puerto serie en función del valor leido 22 | if (value == HIGH) { 23 | Serial.println("Encendido"); 24 | } 25 | else { 26 | Serial.println("Apagado"); 27 | } 28 | delay(1000); 29 | } 30 | ``` 31 | 32 | 33 | ## Medir la frecuencia con interrupción 34 | ```cpp 35 | // period of pulse accumulation and serial output, milliseconds 36 | const int inputPin = 2; 37 | const int MainPeriod = 100; 38 | long previousMillis = 0; // will store last time of the cycle end 39 | 40 | volatile unsigned long previousMicros=0; 41 | volatile unsigned long duration=0; // accumulates pulse width 42 | volatile unsigned int pulsecount=0; 43 | 44 | // interrupt handler 45 | void freqCounterCallback() 46 | { 47 | unsigned long currentMicros = micros(); 48 | duration += currentMicros - previousMicros; 49 | previousMicros = currentMicros; 50 | pulsecount++; 51 | } 52 | 53 | void reportFrequency() 54 | { 55 | float freq = 1e6 / float(duration) * (float)pulsecount; 56 | Serial.print("Frec:"); 57 | Serial.print(freq); 58 | Serial.println(" Hz"); 59 | 60 | // clear counters 61 | duration = 0; 62 | pulsecount = 0; 63 | } 64 | 65 | void setup() 66 | { 67 | Serial.begin(19200); 68 | pinMode(inputPin, INPUT_PULLUP); 69 | attachInterrupt(digitalPinToInterrupt(inputPin), freqCounterCallback, RISING); 70 | } 71 | 72 | void loop() 73 | { 74 | unsigned long currentMillis = millis(); 75 | if (currentMillis - previousMillis >= MainPeriod) 76 | { 77 | previousMillis = currentMillis; 78 | reportFrequency(); 79 | } 80 | } 81 | ``` 82 | 83 | 84 | -------------------------------------------------------------------------------- /020_arduino-intermedio/11 - Display/00 - matriz-led-arduino-max7219.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/matriz-led-arduino-max7219/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```csharp 9 | #include 10 | #include 11 | #include 12 | 13 | //Vcc - Vcc 14 | //Gnd - Gnd 15 | //Din - Mosi (Pin 11) 16 | //Cs - SS (Pin 10) 17 | //Clk - Sck (Pin 13) 18 | 19 | const int pinCS = 10; 20 | const int numberOfHorizontalDisplays = 9; 21 | const int numberOfVerticalDisplays = 1; 22 | 23 | Max72xxPanel matrix = Max72xxPanel(pinCS, numberOfHorizontalDisplays, numberOfVerticalDisplays); 24 | 25 | String tape = "www.luisllamas.es"; //text 26 | 27 | const int wait = 100; // In milliseconds 28 | 29 | const int spacer = 1; 30 | const int width = 5 + spacer; // The font width is 5 pixels 31 | 32 | void setup() { 33 | matrix.setIntensity(7); // Use a value between 0 and 15 for brightness 34 | 35 | // Adjust to your own needs 36 | matrix.setPosition(0, 0, 0); // The first display is at <0, 0> 37 | matrix.setPosition(1, 1, 0); // The second display is at <1, 0> 38 | matrix.setPosition(2, 2, 0); // The third display is at <2, 0> 39 | matrix.setPosition(3, 3, 0); // And the last display is at <3, 0> 40 | matrix.setPosition(4, 4, 0); // And the last display is at <3, 0> 41 | matrix.setPosition(5, 5, 0); // And the last display is at <3, 0> 42 | matrix.setPosition(6, 6, 0); // And the last display is at <3, 0> 43 | matrix.setPosition(7, 7, 0); // And the last display is at <3, 0> 44 | matrix.setPosition(8, 8, 0); // And the last display is at <3, 0> 45 | matrix.setPosition(9, 9, 0); // And the last display is at <3, 0> 46 | 47 | matrix.setRotation(0, 1); // Display is position upside down 48 | matrix.setRotation(1, 1); // Display is position upside down 49 | matrix.setRotation(2, 1); // Display is position upside down 50 | matrix.setRotation(3, 1); // Display is position upside down 51 | matrix.setRotation(4, 1); // Display is position upside down 52 | matrix.setRotation(5, 1); // Display is position upside down 53 | matrix.setRotation(6, 1); // Display is position upside down 54 | matrix.setRotation(7, 1); // Display is position upside down 55 | matrix.setRotation(8, 1); // Display is position upside down 56 | matrix.setRotation(9, 1); // Display is position upside down 57 | } 58 | 59 | void loop() { 60 | for (int i = 0; i < width * tape.length() + matrix.width() - 1 - spacer; i++) { 61 | 62 | matrix.fillScreen(LOW); 63 | 64 | int letter = i / width; 65 | int x = (matrix.width() - 1) - i % width; 66 | int y = (matrix.height() - 8) / 2; // center the text vertically 67 | 68 | while (x + width - spacer >= 0 && letter >= 0) { 69 | if (letter < tape.length()) { 70 | matrix.drawChar(x, y, tape[letter], HIGH, LOW, 1); 71 | } 72 | 73 | letter--; 74 | x -= width; 75 | } 76 | matrix.write(); // Send bitmap to display 77 | 78 | delay(wait); 79 | } 80 | } 81 | ``` 82 | 83 | 84 | -------------------------------------------------------------------------------- /020_arduino-intermedio/11 - Display/01 - arduino-lcd-hitachi-hd44780.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-lcd-hitachi-hd44780/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | /* Conexión 10 | PIN2 - LCD4 (RS) 11 | PIN3 - LCD5 (R/W) 12 | PIN4 - LCD6 (E) 13 | 14 | PIN8 - LCD11 (D4) 15 | PIN9 - LCD12 (D5) 16 | PIN10 - LCD13 (D6) 17 | PIN11 - LCD14 (D7) 18 | */ 19 | 20 | #include 21 | 22 | LiquidCrystal lcd(2, 3, 4, 8, 9, 10, 11); //(RS,RW, E, D4,D5, D6, D7) 23 | 24 | void setup() 25 | { 26 | lcd.begin(16, 2); // Inicia un LCD 16x02 (columnas,fila) 27 | lcd.setCursor(0, 0); // Pone el cursor en las coordenadas (0,0) 28 | lcd.print("Linea 1"); // Escribe el LCD 29 | lcd.setCursor(0, 1); // Ponemos el cursor en la segunda Fila 30 | lcd.print("Linea 2"); // Escribe el LCD 31 | } 32 | 33 | void loop() 34 | { 35 | //Apagar cursor 36 | lcd.noCursor(); 37 | delay(500); 38 | 39 | //Apagar encender cursor 40 | lcd.cursor(); 41 | delay(500); 42 | } 43 | ``` 44 | 45 | ```cpp 46 | /* Conexión 47 | PIN2 - LCD4 (RS) 48 | PIN3 - LCD5 (R/W) 49 | PIN4 - LCD6 (E) 50 | 51 | PIN8 - LCD11 (D4) 52 | PIN9 - LCD12 (D5) 53 | PIN10 - LCD13 (D6) 54 | PIN11 - LCD14 (D7) 55 | */ 56 | #include 57 | 58 | LiquidCrystal lcd(2, 3, 4, 8, 9, 10, 11); //(RS,RW, E, D4,D5, D6, D7) 59 | 60 | void setup() { 61 | lcd.begin(16, 2); 62 | 63 | lcd.print("¡Hola mundo!"); 64 | delay(1000); 65 | } 66 | 67 | void loop() { 68 | 69 | //mover 13 posiciones (longitud del texto) a la izquierda 70 | //para sacar el texto de la pantalla por la izquierda 71 | for (int positionCounter = 0; positionCounter < 13; positionCounter++) { 72 | lcd.scrollDisplayLeft(); 73 | delay(150); 74 | } 75 | 76 | //mover 29 posiciones (longitud del texto + ancho del display) a la derecha 77 | //para sacar el texto de la pantalla por la derecha 78 | for (int positionCounter = 0; positionCounter < 29; positionCounter++) { 79 | lcd.scrollDisplayRight(); 80 | delay(150); 81 | } 82 | 83 | //mover 16 posiciones (29-13) a la izquierda 84 | //para devolver el texto a la posición inicial 85 | for (int positionCounter = 0; positionCounter < 16; positionCounter++) { 86 | lcd.scrollDisplayLeft(); 87 | delay(150); 88 | } 89 | 90 | delay(1000); 91 | } 92 | ``` 93 | 94 | 95 | -------------------------------------------------------------------------------- /020_arduino-intermedio/11 - Display/02 - arduino-lcd-i2c.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-lcd-i2c/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | #include 10 | #include 11 | 12 | LiquidCrystal_I2C lcd(0x27, 16, 2); // Inicia el LCD en la dirección 0x27, con 16 caracteres y 2 líneas 13 | 14 | void setup() 15 | { 16 | lcd.begin(); 17 | lcd.backlight(); 18 | lcd.setCursor(0, 0); 19 | lcd.print("Linea 1"); 20 | lcd.setCursor(0, 1); 21 | lcd.print("Linea 2"); 22 | delay(2500); 23 | lcd.clear(); 24 | } 25 | 26 | void loop() 27 | { 28 | } 29 | ``` 30 | 31 | 32 | -------------------------------------------------------------------------------- /020_arduino-intermedio/12 - Comunicacion/00 - conectar-arduino-por-bluetooth-con-los-modulos-hc-05-o-hc-06.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/conectar-arduino-por-bluetooth-con-los-modulos-hc-05-o-hc-06/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | const int led = 13; 10 | 11 | int option; 12 | 13 | void setup(){ 14 | Serial.begin(9600); 15 | pinMode(led, OUTPUT); 16 | } 17 | 18 | void loop(){ 19 | //si existe información pendiente 20 | if (Serial.available()>0){ 21 | //leeemos la opcion 22 | char option = Serial.read(); 23 | //si la opcion esta entre '1' y '9' 24 | if (option >= '1' && option <= '9') 25 | { 26 | //restamos el valor '0' para obtener el numero enviado 27 | option -= '0'; 28 | for(int i=0;i Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/comunicacion-inalambrica-a-2-4ghz-con-arduino-y-nrf24l01/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Enviar un string 8 | ```cpp 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | const int pinCE = 9; 15 | const int pinCSN = 10; 16 | RF24 radio(pinCE, pinCSN); 17 | 18 | // Single radio pipe address for the 2 nodes to communicate. 19 | const uint64_t pipe = 0xE8E8F0F0E1LL; 20 | 21 | char data[16]="Hola mundo" ; 22 | 23 | void setup(void) 24 | { 25 | radio.begin(); 26 | radio.openWritingPipe(pipe); 27 | } 28 | 29 | void loop(void) 30 | { 31 | radio.write(data, sizeof data); 32 | delay(1000); 33 | } 34 | ``` 35 | 36 | ```cpp 37 | #include 38 | #include 39 | #include 40 | #include 41 | 42 | const int pinCE = 9; 43 | const int pinCSN = 10; 44 | RF24 radio(pinCE, pinCSN); 45 | 46 | // Single radio pipe address for the 2 nodes to communicate. 47 | const uint64_t pipe = 0xE8E8F0F0E1LL; 48 | 49 | char data[16]; 50 | 51 | void setup(void) 52 | { 53 | Serial.begin(9600); 54 | radio.begin(); 55 | radio.openReadingPipe(1,pipe); 56 | radio.startListening(); 57 | } 58 | 59 | void loop(void) 60 | { 61 | if (radio.available()) 62 | { 63 | radio.read(data, sizeof data); 64 | Serial.println(data); 65 | } 66 | } 67 | ``` 68 | 69 | 70 | ## Enviar variables integer o float 71 | ```cpp 72 | #include 73 | #include 74 | #include 75 | 76 | const int pinCE = 9; 77 | const int pinCSN = 10; 78 | RF24 radio(pinCE, pinCSN); 79 | 80 | // Single radio pipe address for the 2 nodes to communicate. 81 | const uint64_t pipe = 0xE8E8F0F0E1LL; 82 | 83 | float data[2]; 84 | 85 | void setup() 86 | { 87 | radio.begin(); 88 | radio.openWritingPipe(pipe); 89 | } 90 | 91 | void loop() 92 | { 93 | data[0]= 3.14; 94 | data[1] = millis()/1000.0; 95 | 96 | radio.write(data, sizeof data); 97 | delay(1000); 98 | } 99 | ``` 100 | 101 | ```cpp 102 | #include 103 | #include 104 | #include 105 | 106 | const int pinCE = 9; 107 | const int pinCSN = 10; 108 | RF24 radio(pinCE, pinCSN); 109 | 110 | // Single radio pipe address for the 2 nodes to communicate. 111 | const uint64_t pipe = 0xE8E8F0F0E1LL; 112 | 113 | float data[3]; 114 | 115 | void setup() 116 | { 117 | radio.begin(); 118 | Serial.begin(9600); 119 | radio.openReadingPipe(1, pipe); 120 | radio.startListening(); 121 | } 122 | 123 | void loop() 124 | { 125 | if (radio.available()) 126 | { 127 | radio.read(data, sizeof data); 128 | Serial.print("Dato0= " ); 129 | Serial.print(data[0]); 130 | Serial.print("Dato1= " ); 131 | Serial.print(data[1]); 132 | Serial.println(""); 133 | } 134 | delay(1000); 135 | } 136 | ``` 137 | 138 | 139 | -------------------------------------------------------------------------------- /020_arduino-intermedio/12 - Comunicacion/05 - arduino-rs485-max485.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-rs485-max485/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Comunicación simplex 8 | ```cpp 9 | void setup() 10 | { 11 | Serial.begin(9600); 12 | } 13 | 14 | void loop() 15 | { 16 | byte data = millis() / 1000; 17 | Serial.write(data); 18 | delay(250); 19 | } 20 | ``` 21 | 22 | ```cpp 23 | void setup() 24 | { 25 | Serial.begin(9600); 26 | } 27 | 28 | void loop() 29 | { 30 | if (Serial.available()) 31 | { 32 | byte data = Serial.read(); 33 | } 34 | } 35 | ``` 36 | 37 | 38 | ## Comunicación half-duplex 39 | ```cpp 40 | const int ledPin = 13; // Led integrado 41 | const int ReDePin = 2; // HIGH = Driver / LOW = Receptor 42 | const char HEADER = 'H'; 43 | 44 | void setup() 45 | { 46 | Serial.begin(9600); 47 | Serial.setTimeout(100); 48 | 49 | pinMode(ledPin, OUTPUT); 50 | pinMode(ReDePin, OUTPUT); 51 | } 52 | 53 | void loop() 54 | { 55 | //RS485 transmisor 56 | digitalWrite(ReDePin, HIGH); 57 | digitalWrite(ledPin, HIGH); 58 | Serial.print(HEADER); 59 | Serial.flush(); 60 | delay(50); 61 | 62 | //RS485 como receptor 63 | digitalWrite(ReDePin, LOW); 64 | digitalWrite(ledPin, LOW); 65 | if(Serial.find(HEADER)) 66 | { 67 | int data = Serial.parseInt(); 68 | 69 | // Aqui hariamos lo que queramos con data 70 | } 71 | } 72 | ``` 73 | 74 | ```cpp 75 | const int ledPin = 13; // Led integrado 76 | const int ReDePin = 2; // HIGH = Driver / LOW = Receptor 77 | const char HEADER = 'H'; 78 | 79 | void setup() 80 | { 81 | Serial.begin(9600); 82 | 83 | pinMode(ReDePin, OUTPUT); 84 | pinMode(ledPin, OUTPUT); 85 | pinMode(ReDePin, OUTPUT); 86 | } 87 | 88 | void loop() 89 | { 90 | //RS485 como receptor 91 | digitalWrite(ReDePin, LOW); 92 | digitalWrite(ledPin, LOW); 93 | 94 | if(Serial.available()) 95 | { 96 | if(Serial.read()==HEADER) 97 | { 98 | //RS485 transmisor 99 | digitalWrite(ReDePin, HIGH); 100 | digitalWrite(ledPin, HIGH); 101 | 102 | int data = millis() / 1000; 103 | Serial.print(HEADER); 104 | Serial.print(data); 105 | Serial.flush(); 106 | } 107 | } 108 | delay(10); 109 | } 110 | ``` 111 | 112 | 113 | -------------------------------------------------------------------------------- /020_arduino-intermedio/13 - Controles/00 - arduino-teclado-matricial.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-teclado-matricial/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Sin librería 8 | ```cpp 9 | const unsigned long period = 50; 10 | unsigned long prevMillis = 0; 11 | 12 | byte iRow = 0, iCol = 0; 13 | const byte countRows = 4; 14 | const byte countColumns = 4; 15 | 16 | const byte rowsPins[countRows] = { 11, 10, 9, 8 }; 17 | const byte columnsPins[countColumns] = { 7, 6, 5, 4 }; 18 | 19 | char keys[countRows][countColumns] = { 20 | { '1','2','3', 'A' }, 21 | { '4','5','6', 'B' }, 22 | { '7','8','9', 'C' }, 23 | { '#','0','*', 'D' } 24 | }; 25 | 26 | // Leer el estado del teclado 27 | bool readKeypad() 28 | { 29 | bool rst = false; 30 | 31 | // Barrido de columnas 32 | for (byte c = 0; c < countColumns; c++) 33 | { 34 | // Poner columna a LOW 35 | pinMode(columnsPins[c],OUTPUT); 36 | digitalWrite(columnsPins[c], LOW); 37 | 38 | // Barrer todas las filas comprobando pulsaciones 39 | for (byte r = 0; r < countRows; r++) 40 | { 41 | if (digitalRead(columnsPins[r]) == LOW) 42 | { 43 | // Pulsacion detectada, guardar fila y columna 44 | iRow = r; 45 | iCol = c; 46 | rst = true; 47 | } 48 | } 49 | // Devolver la columna a alta impedancia 50 | digitalWrite(columnsPins[c], HIGH); 51 | pinMode(columnsPins[c], INPUT); 52 | } 53 | return rst; 54 | } 55 | 56 | // Inicializacion 57 | void setup() 58 | { 59 | Serial.begin(9600); 60 | 61 | // Columnas en alta impedancia 62 | for (byte c = 0; c < countColumns; c++) 63 | { 64 | pinMode(columnsPins[c], INPUT); 65 | digitalWrite(columnsPins[c], HIGH); 66 | } 67 | 68 | // Filas en pullup 69 | for (byte r = 0; r < countRows; r++) 70 | { 71 | pinMode(rowsPins[r], INPUT_PULLUP); 72 | } 73 | } 74 | 75 | void loop() 76 | { 77 | if (millis() - prevMillis > period) // Espera no bloqueante 78 | { 79 | prevMillis = millis(); 80 | if (readKeypad()) // Detección de tecla pulsada 81 | { 82 | Serial.println(keys[iRow][iCol]); // Mostrar tecla 83 | } 84 | } 85 | } 86 | ``` 87 | 88 | 89 | ## Con librería 90 | ```cpp 91 | #include 92 | 93 | const byte rowsCount = 4; 94 | const byte columsCount = 4; 95 | 96 | char keys[rowsCount][columsCount] = { 97 | { '1','2','3', 'A' }, 98 | { '4','5','6', 'B' }, 99 | { '7','8','9', 'C' }, 100 | { '#','0','*', 'D' } 101 | }; 102 | 103 | const byte rowPins[rowsCount] = { 11, 10, 9, 8 }; 104 | const byte columnPins[columsCount] = { 7, 6, 5, 4 }; 105 | 106 | Keypad keypad = Keypad(makeKeymap(keys), rowPins, columnPins, rowsCount, columsCount); 107 | 108 | void setup() { 109 | Serial.begin(9600); 110 | } 111 | 112 | void loop() { 113 | char key = keypad.getKey(); 114 | 115 | if (key) { 116 | Serial.println(key); 117 | } 118 | } 119 | ``` 120 | 121 | 122 | -------------------------------------------------------------------------------- /020_arduino-intermedio/13 - Controles/01 - arduino-joystick.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-joystick/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | /* 10 | GND - GND 11 | Vcc - 5v 12 | VRx - A0 13 | VRy - A1 14 | SW - D9 15 | */ 16 | 17 | const int pinLED = 13; 18 | const int pinJoyX = A0; 19 | const int pinJoyY = A1; 20 | const int pinJoyButton = 9; 21 | 22 | void setup() { 23 | pinMode(pinJoyButton , INPUT_PULLUP); //activar resistencia pull up 24 | Serial.begin(9600); 25 | } 26 | 27 | void loop() { 28 | int Xvalue = 0; 29 | int Yvalue = 0; 30 | bool buttonValue = false; 31 | 32 | //leer valores 33 | Xvalue = analogRead(pinJoyX); 34 | delay(100); //es necesaria una pequeña pausa entre lecturas analógicas 35 | Yvalue = analogRead(pinJoyY); 36 | buttonValue = digitalRead(pinJoyButton); 37 | 38 | //mostrar valores por serial 39 | Serial.print("X:" ); 40 | Serial.print(Xvalue); 41 | Serial.print(" | Y: "); 42 | Serial.print(Yvalue); 43 | Serial.print(" | Pulsador: "); 44 | Serial.println(buttonValue); 45 | delay(1000); 46 | } 47 | ``` 48 | 49 | 50 | -------------------------------------------------------------------------------- /020_arduino-intermedio/13 - Controles/02 - arduino-mando-a-distancia-infrarrojo.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-mando-a-distancia-infrarrojo/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | #include 10 | 11 | const int RECV_PIN = 9; 12 | 13 | IRrecv irrecv(RECV_PIN); 14 | decode_results results; 15 | 16 | void setup() 17 | { 18 | Serial.begin(9600); 19 | irrecv.enableIRIn(); 20 | } 21 | 22 | void loop() 23 | { 24 | if (irrecv.decode(&results)) 25 | { 26 | Serial.println(results.value, HEX); 27 | irrecv.resume(); 28 | } 29 | } 30 | ``` 31 | 32 | ```cpp 33 | #include 34 | 35 | const int KEY_UP = 0xFF629D; 36 | const int KEY_LEFT = 0xFF22DD; 37 | const int KEY_OK = 0xFF02FD; 38 | const int KEY_RIGHT = 0xFFC23D; 39 | const int KEY_DOWN = 0xFFA857; 40 | const int KEY_1 = 0xFF6897; 41 | const int KEY_2 = 0xFF9867; 42 | const int KEY_3 = 0xFFB04F; 43 | const int KEY_4 = 0xFF30CF; 44 | const int KEY_5 = 0xFF18E7; 45 | const int KEY_6 = 0xFF7A85; 46 | const int KEY_7 = 0xFF10EF; 47 | const int KEY_8 = 0xFF38C7; 48 | const int KEY_9 = 0xFF5AA5; 49 | const int KEY_0 = 0xFF4AB5; 50 | const int KEY_ASTERISK = 0xFF42BD; 51 | const int KEY_POUND = 0xFF52AD; 52 | const int KEY_REPEAT = 0xFFFFFFFF; 53 | 54 | const int RECV_PIN = 9; 55 | 56 | IRrecv irrecv(RECV_PIN); 57 | decode_results results; 58 | 59 | void setup() 60 | { 61 | Serial.begin(9600); 62 | irrecv.enableIRIn(); 63 | } 64 | 65 | void loop() 66 | { 67 | if (irrecv.decode(&results)) 68 | { 69 | switch (results.value) 70 | { 71 | case KEY_UP: 72 | Serial.println("KEY_UP"); 73 | break; 74 | case KEY_LEFT: 75 | Serial.println("KEY_LEFT"); 76 | break; 77 | case KEY_OK: 78 | Serial.println("KEY_OK"); 79 | break; 80 | case KEY_RIGHT: 81 | Serial.println("KEY_RIGHT"); 82 | break; 83 | case KEY_DOWN: 84 | Serial.println("KEY_DOWN"); 85 | break; 86 | case KEY_1: 87 | Serial.println("KEY_1"); 88 | break; 89 | case KEY_2: 90 | Serial.println("KEY_2"); 91 | break; 92 | case KEY_3: 93 | Serial.println("KEY_3"); 94 | break; 95 | case KEY_4: 96 | Serial.println("KEY_4"); 97 | break; 98 | case KEY_5: 99 | Serial.println("KEY_5"); 100 | break; 101 | case KEY_6: 102 | Serial.println("KEY_6"); 103 | break; 104 | case KEY_7: 105 | Serial.println("KEY_7"); 106 | break; 107 | case KEY_8: 108 | Serial.println("KEY_8"); 109 | break; 110 | case KEY_9: 111 | Serial.println("KEY_9"); 112 | break; 113 | case KEY_0: 114 | Serial.println("KEY_0"); 115 | break; 116 | case KEY_ASTERISK: 117 | Serial.println("KEY_ASTERISK"); 118 | break; 119 | case KEY_POUND: 120 | Serial.println("KEY_POUND"); 121 | break; 122 | case KEY_REPEAT: 123 | Serial.println("KEY_REPEAT"); 124 | break; 125 | } 126 | irrecv.resume(); 127 | } 128 | } 129 | ``` 130 | 131 | 132 | -------------------------------------------------------------------------------- /020_arduino-intermedio/13 - Controles/03 - arduino-y-mando-a-distancia-de-4-canales-315mhz-ic2262.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-y-mando-a-distancia-de-4-canales-315mhz-ic2262/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | // D0 - 8 10 | // D1 - 9 11 | // D2 - 10 12 | // D3 - 11 13 | 14 | const int pinB = 8; 15 | const int pinD = 9; 16 | const int pinA = 10; 17 | const int pinC = 11; 18 | 19 | void setup() 20 | { 21 | Serial.begin(9600); 22 | } 23 | 24 | void loop() 25 | { 26 | if (digitalRead(pinA) == HIGH) 27 | { 28 | Serial.println("A"); 29 | delay(1500); 30 | } 31 | 32 | if (digitalRead(pinB) == HIGH) 33 | { 34 | Serial.println("B"); 35 | delay(1500); 36 | } 37 | 38 | if (digitalRead(pinC) == HIGH) 39 | { 40 | Serial.println("C"); 41 | delay(1500); 42 | } 43 | 44 | if (digitalRead(pinD) == HIGH) 45 | { 46 | Serial.println("D"); 47 | delay(1500); 48 | } 49 | delay(10); 50 | ``` 51 | 52 | 53 | -------------------------------------------------------------------------------- /020_arduino-intermedio/13 - Controles/04 - conectar-emisora-radio-control-con-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/conectar-emisora-radio-control-con-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | int rcPins[6] = {5,6,7,8,9,10}; 10 | float chValue[6]; 11 | 12 | const int pulseInDelay = 20000; 13 | 14 | void setup() 15 | { 16 | Serial.begin(9600); 17 | } 18 | 19 | float fmap(float x, float in_min, float in_max, float out_min, float out_max) 20 | { 21 | return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; 22 | } 23 | 24 | void readChannel(int channel) 25 | { 26 | int rawValue = pulseIn(rcPins[channel], HIGH, pulseInDelay); 27 | chValue[channel] = fmap( (float)rawValue, 1000.0, 2000.0, 0.0, 1.0); 28 | chValue[channel] = chValue[channel] < 0.0 ? 0.0 : chValue[channel]; 29 | chValue[channel] = chValue[channel] > 1.0 ? 1.0 : chValue[channel]; 30 | } 31 | 32 | void printChannel() 33 | { 34 | for(int iChannel = 0; iChannel < 6; iChannel++) 35 | { 36 | Serial.print("Ch #"); 37 | Serial.print(iChannel); 38 | Serial.print(": "); 39 | Serial.println(chValue[iChannel]); 40 | }; 41 | Serial.println("------------"); 42 | } 43 | 44 | void loop() 45 | { 46 | for(int iChannel = 0; iChannel < 6; iChannel++) 47 | { 48 | readChannel(iChannel); 49 | } 50 | printChannel(); 51 | delay(2500); 52 | } 53 | ``` 54 | 55 | 56 | -------------------------------------------------------------------------------- /020_arduino-intermedio/13 - Controles/05 - arduino-mando-wii-wiichuck.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-mando-wii-wiichuck/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | //GND - GND 10 | //VCC - VCC 11 | //SDA - Pin A4 12 | //SCL - Pin A5 13 | 14 | #include 15 | #include 16 | 17 | Wiichuck wii; 18 | 19 | void setup() { 20 | Serial.begin(9600); 21 | wii.init(); 22 | wii.calibrate(); 23 | } 24 | 25 | void loop() { 26 | if (wii.poll()) { 27 | Serial.print("joy:"); 28 | Serial.print(wii.joyX()); 29 | Serial.print(", "); 30 | Serial.print(wii.joyY()); 31 | Serial.print(" \t"); 32 | 33 | Serial.print("accle:"); 34 | Serial.print(wii.accelX()); 35 | Serial.print(", "); 36 | Serial.print(wii.accelY()); 37 | Serial.print(", "); 38 | Serial.print(wii.accelZ()); 39 | Serial.print(" \t"); 40 | 41 | Serial.print("button:"); 42 | Serial.print(wii.buttonC()); 43 | Serial.print(", "); 44 | Serial.print(wii.buttonZ()); 45 | Serial.println(""); 46 | } 47 | 48 | delay(100); 49 | } 50 | ``` 51 | 52 | 53 | -------------------------------------------------------------------------------- /020_arduino-intermedio/14 - Magnetico/00 - usar-un-interruptor-magnetico-con-arduino-magnetic-reed.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/usar-un-interruptor-magnetico-con-arduino-magnetic-reed/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | const int pinSensor = 2; 10 | const int pinLED = 13; 11 | 12 | void setup() { 13 | //configurar pin como entrada con resistencia pull-up interna 14 | pinMode(pinSensor, INPUT_PULLUP); 15 | pinMode(pinLED, OUTPUT); 16 | } 17 | 18 | void loop() { 19 | int value = digitalRead(pinSensor); 20 | 21 | if (value == LOW) { 22 | digitalWrite(pinLED, HIGH); 23 | } else { 24 | digitalWrite(pinLED, LOW); 25 | } 26 | 27 | delay(1000); 28 | } 29 | ``` 30 | 31 | 32 | -------------------------------------------------------------------------------- /020_arduino-intermedio/14 - Magnetico/01 - medir-campos-magneticos-arduino-hall-49e.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/medir-campos-magneticos-arduino-hall-49e/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplo de código 8 | ```cpp 9 | const int pinHall = A0; 10 | 11 | void setup() { 12 | pinMode(pinHall, INPUT); 13 | Serial.begin(9600); 14 | } 15 | 16 | void loop() { 17 | 18 | //media de 10 medidas para filtrar ruido 19 | long measure = 0; 20 | for(int i = 0; i < 10; i++){ 21 | int value = 22 | measure += analogRead(pinHall); 23 | } 24 | measure /= 10; 25 | 26 | //calculo del voltaje en mV 27 | float outputV = measure * 5000.0 / 1023; 28 | Serial.print("Output Voltaje = "); 29 | Serial.print(outputV); 30 | Serial.print(" mV "); 31 | 32 | //interpolacion a densidad de flujo magnético 33 | float magneticFlux = outputV * 53.33 - 133.3; 34 | Serial.print("Magnetic Flux Density = "); 35 | Serial.print(magneticFlux); 36 | Serial.print(" mT"); 37 | 38 | delay(2000); 39 | } 40 | ``` 41 | 42 | 43 | -------------------------------------------------------------------------------- /020_arduino-intermedio/14 - Magnetico/02 - detectar-campos-magneticos-con-arduino-y-sensor-hall-a3144.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/detectar-campos-magneticos-con-arduino-y-sensor-hall-a3144/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplo de código 8 | ```cpp 9 | const int HALLPin = 5; 10 | const int LEDPin = 13; 11 | 12 | void setup() { 13 | pinMode(LEDPin, OUTPUT); 14 | pinMode(HALLPin, INPUT); 15 | } 16 | 17 | void loop() { 18 | if(digitalRead(HALLPin)==HIGH) 19 | { 20 | digitalWrite(LEDPin, HIGH); 21 | } 22 | else 23 | { 24 | digitalWrite(LEDPin, LOW); 25 | } 26 | } 27 | ``` 28 | 29 | 30 | -------------------------------------------------------------------------------- /020_arduino-intermedio/14 - Magnetico/03 - detector-de-metales-con-arduino-y-sensor-inductivo.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/detector-de-metales-con-arduino-y-sensor-inductivo/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```csharp 9 | const int sensorPin = 9; 10 | 11 | void setup() 12 | { 13 | Serial.begin(9600); 14 | } 15 | 16 | void loop() 17 | { 18 | bool state = digitalRead(sensorPin); 19 | 20 | //mandar mensaje a puerto serie en función del valor leido 21 | if (state == HIGH) 22 | { 23 | Serial.println("Detección"); 24 | //aquí se ejecutarían las acciones 25 | } 26 | delay(1000); 27 | } 28 | ``` 29 | 30 | 31 | -------------------------------------------------------------------------------- /020_arduino-intermedio/15 - Memoria/00 - arduino-eeprom-externa-i2c-at24c256.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-eeprom-externa-i2c-at24c256/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | //Vcc - 5V 10 | //GND - GND 11 | //SDA - A4 12 | //SCL - A5 13 | 14 | #include 15 | const int eepromAddress = 0x50; 16 | 17 | // Funciones de lectura basadas en el trabajo de 18 | // Author: hkhijhe 19 | // Date : 01 / 10 / 2010 20 | void i2c_eeprom_write_byte(int deviceaddress, unsigned int eeaddress, byte data) { 21 | int rdata = data; 22 | Wire.beginTransmission(deviceaddress); 23 | Wire.write((int)(eeaddress >> 8)); // MSB 24 | Wire.write((int)(eeaddress & 0xFF)); // LSB 25 | Wire.write(rdata); 26 | Wire.endTransmission(); 27 | } 28 | 29 | // WARNING: address is a page address, 6-bit end will wrap around 30 | // also, data can be maximum of about 30 bytes, because the Wire library has a buffer of 32 bytes 31 | void i2c_eeprom_write_page(int deviceaddress, unsigned int eeaddresspage, byte* data, byte length) { 32 | Wire.beginTransmission(deviceaddress); 33 | Wire.write((int)(eeaddresspage >> 8)); // MSB 34 | Wire.write((int)(eeaddresspage & 0xFF)); // LSB 35 | byte c; 36 | for (c = 0; c < length; c++) 37 | Wire.write(data[c]); 38 | Wire.endTransmission(); 39 | } 40 | 41 | byte i2c_eeprom_read_byte(int deviceaddress, unsigned int eeaddress) { 42 | byte rdata = 0xFF; 43 | Wire.beginTransmission(deviceaddress); 44 | Wire.write((int)(eeaddress >> 8)); // MSB 45 | Wire.write((int)(eeaddress & 0xFF)); // LSB 46 | Wire.endTransmission(); 47 | Wire.requestFrom(deviceaddress, 1); 48 | if (Wire.available()) rdata = Wire.read(); 49 | return rdata; 50 | } 51 | 52 | // maybe let's not read more than 30 or 32 bytes at a time! 53 | void i2c_eeprom_read_buffer(int deviceaddress, unsigned int eeaddress, byte *buffer, int length) { 54 | Wire.beginTransmission(deviceaddress); 55 | Wire.write((int)(eeaddress >> 8)); // MSB 56 | Wire.write((int)(eeaddress & 0xFF)); // LSB 57 | Wire.endTransmission(); 58 | Wire.requestFrom(deviceaddress, length); 59 | int c = 0; 60 | for (c = 0; c < length; c++) 61 | if (Wire.available()) buffer[c] = Wire.read(); 62 | } 63 | 64 | void setup() 65 | { 66 | Wire.begin(); 67 | Serial.begin(9600); 68 | 69 | // Datos de ejemplo 70 | char somedata[] = "datos grabados en la EEPROM"; 71 | 72 | // Escribir ejemplo en memoria 73 | i2c_eeprom_write_page(eepromAddress, 0, (byte *)somedata, sizeof(somedata)); 74 | delay(10); 75 | 76 | Serial.println(F("Escritura inicial completada")); 77 | } 78 | 79 | void loop() 80 | { 81 | // Leer el primer byte de la memoria 82 | int addr = 0; 83 | byte value = i2c_eeprom_read_byte(eepromAddress, addr); 84 | 85 | // Leer e imprimir el caracter mientras sea distinto de '0' 86 | while (value != 0) 87 | { 88 | Serial.print((char)value); 89 | addr++; 90 | value = i2c_eeprom_read_byte(0x50, addr); 91 | } 92 | Serial.println(" "); 93 | delay(20000); 94 | } 95 | ``` 96 | 97 | 98 | -------------------------------------------------------------------------------- /020_arduino-intermedio/15 - Memoria/01 - tarjeta-micro-sd-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/tarjeta-micro-sd-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplo de código 8 | ```cpp 9 | // Iniciar la SD 10 | SD.begin(cspin); 11 | 12 | // Comprobar si existe un fichero (devuelve true si existe, falso en caso contrario) 13 | SD.exists(filename); 14 | 15 | // Borrar un fichero 16 | SD.remove(filename); 17 | 18 | // Abrir un fichero 19 | // Mode: FILE_READ para sólo lectura 20 | // FILE_WRITE para lectura y escritura 21 | SD.open(filepath, mode); 22 | 23 | // Crear un directorio 24 | SD.mkdir(directory); 25 | 26 | // Eliminar un directorio 27 | SD.rmdir(dirname); 28 | ``` 29 | 30 | ```cpp 31 | // Obtener el tamaño de un fichero 32 | file.size() 33 | 34 | // Comprobar si quedan bytes por leer 35 | file.available() 36 | 37 | // Leer un byte del fichero 38 | file.read() 39 | 40 | // Escribir un byte en el fichero 41 | file.write(data) 42 | 43 | // Escribir una variable en un fichero (en forma similar a Serial.Print) 44 | file.print(data) 45 | 46 | // Obtener el punto de lectura/escritura actual 47 | file.position() 48 | 49 | // Mover el punto de lectura/escritura actual 50 | // Pos: Debe estar entre 0 y file.size() 51 | file.seek(pos) 52 | 53 | // Cerrar el fichero 54 | file.close() 55 | ``` 56 | 57 | 58 | ## Lectura de un fichero 59 | ```cpp 60 | #include 61 | 62 | File dataFile; 63 | 64 | void setup() 65 | { 66 | Serial.begin(9600); 67 | Serial.print(F("Iniciando SD ...")); 68 | if (!SD.begin(9)) 69 | { 70 | Serial.println(F("Error al iniciar")); 71 | return; 72 | } 73 | Serial.println(F("Iniciado correctamente")); 74 | 75 | // Abrir fichero y mostrar el resultado 76 | dataFile = SD.open("datalog.txt"); 77 | if (dataLine) 78 | { 79 | string dataLine; 80 | while (dataFile.available()) 81 | { 82 | dataLine = dataFile.read(); 83 | Serial.write(dataLine); // En un caso real se realizarían las acciones oportunas 84 | } 85 | dataFile.close(); 86 | } 87 | else 88 | { 89 | Serial.println(F("Error al abrir el archivo")); 90 | } 91 | } 92 | 93 | void loop() 94 | { 95 | } 96 | ``` 97 | 98 | 99 | ## Escritura de un fichero (datalogger) 100 | ```cpp 101 | #include 102 | 103 | File logFile; 104 | 105 | void setup() 106 | { 107 | Serial.begin(9600); 108 | Serial.print(F("Iniciando SD ...")); 109 | if (!SD.begin(9)) 110 | { 111 | Serial.println(F("Error al iniciar")); 112 | return; 113 | } 114 | Serial.println(F("Iniciado correctamente")); 115 | } 116 | 117 | // Funcion que simula la lectura de un sensor 118 | int readSensor() 119 | { 120 | return 0; 121 | } 122 | 123 | void loop() 124 | { 125 | // Abrir archivo y escribir valor 126 | logFile = SD.open("datalog.txt", FILE_WRITE); 127 | 128 | if (logFile) { 129 | int value = readSensor; 130 | logFile.print("Time(ms)="); 131 | logFile.print(millis()); 132 | logFile.print(", value="); 133 | logFile.println(value); 134 | 135 | logFile.close(); 136 | 137 | } 138 | else { 139 | Serial.println("Error al abrir el archivo"); 140 | } 141 | delay(500); 142 | } 143 | ``` 144 | 145 | 146 | -------------------------------------------------------------------------------- /020_arduino-intermedio/19 - Sonido/00 - reproducir-sonidos-arduino-buzzer-pasivo-altavoz.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/reproducir-sonidos-arduino-buzzer-pasivo-altavoz/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```csharp 9 | tone(pin, frecuencia); //activa un tono de frecuencia determinada en un pin dado 10 | noTone(pin); //detiene el tono en el pin 11 | ``` 12 | 13 | ```csharp 14 | tone(pin, frequencia, duracion); //activa un tono de frecuencia y duracion determinados en un pin dado 15 | ``` 16 | 17 | ```csharp 18 | const int pinBuzzer = 9; 19 | 20 | void setup() 21 | { 22 | } 23 | 24 | void loop() 25 | { 26 | //generar tono de 440Hz durante 1000 ms 27 | tone(pinBuzzer, 440); 28 | delay(1000); 29 | 30 | //detener tono durante 500ms 31 | noTone(pinBuzzer); 32 | delay(500); 33 | 34 | //generar tono de 523Hz durante 500ms, y detenerlo durante 500ms. 35 | tone(pinBuzzer, 523, 300); 36 | delay(500); 37 | } 38 | ``` 39 | 40 | ```csharp 41 | const int pinBuzzer = 9; 42 | 43 | const int tonos[] = {261, 277, 294, 311, 330, 349, 370, 392, 415, 440, 466, 494}; 44 | const int countTonos = 10; 45 | 46 | void setup() 47 | { 48 | } 49 | 50 | void loop() 51 | { 52 | for (int iTono = 0; iTono < countTonos; iTono++) 53 | { 54 | tone(pinBuzzer, tonos[iTono]); 55 | delay(1000); 56 | } 57 | noTone(pinBuzzer); 58 | } 59 | ``` 60 | 61 | 62 | -------------------------------------------------------------------------------- /020_arduino-intermedio/19 - Sonido/01 - arduino-buzzer-activo.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-buzzer-activo/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplo de código de montaje 8 | ```cpp 9 | const int pin = 9; 10 | 11 | void setup() { 12 | pinMode(pin, OUTPUT); //definir pin como salida 13 | } 14 | 15 | void loop(){ 16 | digitalWrite(pin, HIGH); // poner el Pin en HIGH 17 | delay(5000); // esperar 5 segundos 18 | digitalWrite(pin, LOW); // poner el Pin en LOW 19 | delay(20000); // esperar 20 segundos 20 | } 21 | ``` 22 | 23 | ```cpp 24 | const int pin = 9; 25 | 26 | bool isAlarmOn = 0; //almacena el estado de la alarma 27 | 28 | void setup() { 29 | pinMode(pin, OUTPUT); //definir pin como salida 30 | } 31 | 32 | bool GetSystemState() 33 | { 34 | return true; //cambiar en función del sensor usado 35 | } 36 | 37 | void loop(){ 38 | isAlarmOn = GetSystemState(); 39 | 40 | if(isAlarmOn) 41 | { 42 | digitalWrite(pin, HIGH); // poner el Pin en HIGH 43 | delay(5000); // esperar 5 segundos 44 | } 45 | else 46 | { 47 | digitalWrite(pin, LOW); // poner el Pin en LOW 48 | } 49 | delay(1000); 50 | } 51 | ``` 52 | 53 | 54 | -------------------------------------------------------------------------------- /020_arduino-intermedio/19 - Sonido/02 - detectar-sonido-con-arduino-y-microfono-ky-038.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/detectar-sonido-con-arduino-y-microfono-ky-038/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | const int pinLED = 13; 10 | const int pinMicrophone = 9; 11 | 12 | void setup () 13 | { 14 | pinMode (pinLED, OUTPUT); 15 | pinMode (pinMicrophone, INPUT); 16 | } 17 | 18 | void loop () 19 | { 20 | bool soundDetected = digitalRead(pinMicrophone); 21 | if (soundDetected) 22 | { 23 | digitalWrite (pinLED, HIGH); 24 | delay(1000); 25 | } 26 | else 27 | { 28 | digitalWrite (pinLED, LOW); 29 | delay(10); 30 | } 31 | } 32 | ``` 33 | 34 | ```cpp 35 | const int pinLED = 13; 36 | const int pinMicrophone = 9; 37 | bool state; 38 | 39 | void setup() 40 | { 41 | pinMode(pinLED, OUTPUT); 42 | pinMode(pinMicrophone, INPUT_PULLUP); 43 | } 44 | 45 | void loop() 46 | { 47 | bool soundDetected = digitalRead(pinMicrophone); 48 | if (soundDetected == true) 49 | { 50 | state = ! state; 51 | digitalWrite(pinLED , state); 52 | delay (1000); 53 | } 54 | delay(10); 55 | } 56 | ``` 57 | 58 | 59 | -------------------------------------------------------------------------------- /020_arduino-intermedio/19 - Sonido/03 - medir-sonido-con-arduino-y-microfono-amplificado-max9812.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/medir-sonido-con-arduino-y-microfono-amplificado-max9812/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | const int sensorPIN = A0; 10 | const int sampleWindow = 50; // Ancho ventana en mS (50 mS = 20Hz) 11 | 12 | void setup() 13 | { 14 | Serial.begin(9600); 15 | } 16 | 17 | void loop() 18 | { 19 | unsigned long startMillis= millis(); 20 | 21 | unsigned int signalMax = 0; 22 | unsigned int signalMin = 1024; 23 | 24 | // Recopilar durante la ventana 25 | unsigned int sample; 26 | while (millis() - startMillis < sampleWindow) 27 | { 28 | sample = analogRead(sensorPIN); 29 | if (sample < 1024) 30 | { 31 | if (sample > signalMax) 32 | { 33 | signalMax = sample; // Actualizar máximo 34 | } 35 | else if (sample < signalMin) 36 | { 37 | signalMin = sample; // Actualizar mínimo 38 | } 39 | } 40 | } 41 | unsigned int peakToPeak = signalMax - signalMin; // Amplitud del sonido 42 | double volts = (peakToPeak * 5.0) / 1024; // Convertir a tensión 43 | Serial.println(volts); 44 | } 45 | ``` 46 | 47 | 48 | -------------------------------------------------------------------------------- /020_arduino-intermedio/19 - Sonido/04 - arduino-mp3-dfplayer-mini.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-mp3-dfplayer-mini/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplos de código 8 | ```cpp 9 | #include 10 | #include 11 | 12 | SoftwareSerial DFPlayerSerial(10, 11); // RX, TX 13 | 14 | /* 15 | mp3_play(); //start play 16 | mp3_play(5); //play "mp3/0005.mp3" 17 | mp3_pause(); 18 | mp3_stop(); 19 | mp3_next(); 20 | mp3_prev(); 21 | 22 | mp3_set_volume(uint16_t volume); //0~30 23 | mp3_set_EQ(); //0~5 24 | void mp3_single_loop(boolean state); //set single loop 25 | void mp3_random_play(); 26 | */ 27 | 28 | void setup() 29 | { 30 | Serial.begin(9600); 31 | DFPlayerSerial.begin(9600); 32 | mp3_set_serial(DFPlayerSerial); 33 | mp3_set_volume(15); 34 | } 35 | 36 | void loop() 37 | { 38 | mp3_play(1); 39 | delay(6000); 40 | mp3_next(); 41 | delay(6000); 42 | mp3_prev(); 43 | delay(6000); 44 | mp3_play(4); 45 | delay(6000); 46 | } 47 | ``` 48 | 49 | 50 | -------------------------------------------------------------------------------- /020_arduino-intermedio/20 - Gps/00 - localizacion-gps-con-arduino-y-los-modulos-gps-neo-6.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/localizacion-gps-con-arduino-y-los-modulos-gps-neo-6/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Obtener lectura NMEA 8 | ```cpp 9 | #include 10 | 11 | const int RX = 4; 12 | const int TX = 3; 13 | 14 | SoftwareSerial gps(RX, TX); 15 | 16 | void setup() 17 | { 18 | Serial.begin(115200); 19 | gps.begin(9600); 20 | } 21 | 22 | void loop() 23 | { 24 | if (gps.available()) 25 | { 26 | char data; 27 | data = gps.read(); 28 | Serial.print(data); 29 | } 30 | } 31 | ``` 32 | 33 | ```bash 34 | $GPRMC,hhmmss.ss,A,llll.ll,a,yyyyy.yy,a,x.x,x.x,ddmmyy,x.x,a\*hh 35 | ``` 36 | 37 | ```bash 38 | $GPRMC,225446,A,4916.45,N,12311.12,W,000.5,054.7,191194,020.3,E\*68 39 | ``` 40 | 41 | 42 | ## Obtener coordenadas con TinyGPS 43 | ```cpp 44 | #include 45 | #include 46 | 47 | TinyGPS gps; 48 | SoftwareSerial softSerial(4, 3); 49 | 50 | void setup() 51 | { 52 | Serial.begin(115200); 53 | softSerial.begin(9600); 54 | } 55 | 56 | void loop() 57 | { 58 | bool newData = false; 59 | unsigned long chars; 60 | unsigned short sentences, failed; 61 | 62 | // Intentar recibir secuencia durante un segundo 63 | for (unsigned long start = millis(); millis() - start < 1000;) 64 | { 65 | while (softSerial.available()) 66 | { 67 | char c = softSerial.read(); 68 | if (gps.encode(c)) // Nueva secuencia recibida 69 | newData = true; 70 | } 71 | } 72 | 73 | if (newData) 74 | { 75 | float flat, flon; 76 | unsigned long age; 77 | gps.f_get_position(&flat, &flon, &age); 78 | Serial.print("LAT="); 79 | Serial.print(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flat, 6); 80 | Serial.print(" LON="); 81 | Serial.print(flon == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flon, 6); 82 | Serial.print(" SAT="); 83 | Serial.print(gps.satellites() == TinyGPS::GPS_INVALID_SATELLITES ? 0 : gps.satellites()); 84 | Serial.print(" PREC="); 85 | Serial.print(gps.hdop() == TinyGPS::GPS_INVALID_HDOP ? 0 : gps.hdop()); 86 | } 87 | 88 | gps.stats(&chars, &sentences, &failed); 89 | Serial.print(" CHARS="); 90 | Serial.print(chars); 91 | Serial.print(" SENTENCES="); 92 | Serial.print(sentences); 93 | Serial.print(" CSUM ERR="); 94 | Serial.println(failed); 95 | } 96 | ``` 97 | 98 | 99 | -------------------------------------------------------------------------------- /030_arduino-avanzado/00 - Programación e IDEs/01 - programar-arduino-con-atom-y-platformio-ide.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/programar-arduino-con-atom-y-platformio-ide/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Blink en Arduino 8 | ```cpp 9 | void setup() { 10 | // initialize digital pin 13 as an output. 11 | pinMode(13, OUTPUT); 12 | } 13 | 14 | void loop() { 15 | digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level) 16 | delay(1000); // wait for a second 17 | digitalWrite(13, LOW); // turn the LED off by making the voltage LOW 18 | delay(1000); // wait for a second 19 | } 20 | ``` 21 | 22 | 23 | -------------------------------------------------------------------------------- /030_arduino-avanzado/00 - Programación e IDEs/03 - como-programar-arduino-con-visual-studio-code-y-plaftormio.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/como-programar-arduino-con-visual-studio-code-y-plaftormio/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Crear un nuevo proyecto 8 | ```bash 9 | project_dir 10 | ├── lib 11 | │   └── README 12 | ├── platformio.ini 13 | └── src 14 | └── main.cpp 15 | ``` 16 | 17 | 18 | ## El fichero platform.ini 19 | ```bash 20 | [env:m5stack-atom] 21 | platform = espressif32 22 | board = m5stack-atom 23 | framework = arduino 24 | ``` 25 | 26 | 27 | -------------------------------------------------------------------------------- /030_arduino-avanzado/00 - Programación e IDEs/04 - programar-arduino-con-eclipse.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/programar-arduino-con-eclipse/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Instalar Eclipse 8 | ```bash 9 | sudo apt-get install eclipse 10 | ``` 11 | 12 | 13 | ## Instalar avrdude 14 | ```bash 15 | sudo apt-get install gcc-avr binutils-avr gdb-avr avr-libc avrdude make 16 | ``` 17 | 18 | 19 | ## Probando a programar Arduino con Eclipse 20 | ```cpp 21 | #include 22 | #include 23 | 24 | int main(void) { 25 | 26 | DDRB = (1< Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/cadenas-de-texto-puerto-serie-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Leer un carácter 8 | ```cpp 9 | #define DEBUG(a) Serial.println(a); 10 | 11 | void setup() 12 | { 13 | Serial.begin(9600); 14 | Serial.setTimeout(50); 15 | } 16 | 17 | void loop() 18 | { 19 | if (Serial.available()) 20 | { 21 | char data = Serial.read(); 22 | if ((data >= 'A' && data <= 'Z') || (data >= 'a' && data <= 'z')) 23 | { 24 | DEBUG((char)data); 25 | } 26 | } 27 | } 28 | ``` 29 | 30 | 31 | ## Leer una cadena de texto con clase String 32 | ```cpp 33 | #define DEBUG(a) Serial.println(a); 34 | 35 | void setup() 36 | { 37 | Serial.begin(9600); 38 | } 39 | 40 | void loop() 41 | { 42 | if (Serial.available()) 43 | { 44 | String data = Serial.readStringUntil('\n'); 45 | DEBUG(data); 46 | } 47 | } 48 | ``` 49 | 50 | 51 | ## Leer cadena de texto con char array 52 | ```cpp 53 | #define DEBUG(a, b) for (int index = 0; index < b; index++) Serial.print(a[index]); Serial.println(); 54 | 55 | void setup() 56 | { 57 | Serial.begin(9600); 58 | Serial.setTimeout(50); 59 | } 60 | 61 | void loop() 62 | { 63 | if (Serial.available()) 64 | { 65 | char data[20]; 66 | size_t count = Serial.readBytesUntil('\n', data, 20); 67 | DEBUG(data, count) 68 | } 69 | } 70 | ``` 71 | 72 | 73 | ## Leer cadena con método Naive 74 | ```cpp 75 | #define DEBUG(a) Serial.println(a); 76 | 77 | String data = ""; 78 | 79 | void setup() 80 | { 81 | Serial.begin(9600); 82 | } 83 | 84 | void loop() 85 | { 86 | while (Serial.available()) 87 | { 88 | char character = Serial.read(); 89 | if (character != '\n') 90 | { 91 | data.concat(character); 92 | } 93 | else 94 | { 95 | Serial.println(data); 96 | data = ""; 97 | } 98 | } 99 | } 100 | ``` 101 | 102 | ```cpp 103 | #define DEBUG(a) Serial.println(a); 104 | 105 | char data[20]; 106 | size_t dataIndex = 0; 107 | 108 | void setup() 109 | { 110 | Serial.begin(9600); 111 | } 112 | 113 | void loop() 114 | { 115 | while (Serial.available()) 116 | { 117 | char character = Serial.read(); 118 | if (character != '\n') 119 | { 120 | data[dataIndex] = character; 121 | dataindex ++; 122 | } 123 | else 124 | { 125 | Serial.println(data); 126 | dataIndex = 0; 127 | } 128 | } 129 | } 130 | ``` 131 | 132 | 133 | -------------------------------------------------------------------------------- /030_arduino-avanzado/01 - Puerto serie avanzado/03 - array-puerto-serie-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/array-puerto-serie-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Envío y recepción elementos individuales 8 | ```cpp 9 | const size_t dataLength = 10; 10 | int data[dataLength]; 11 | 12 | void setup() 13 | { 14 | Serial.begin(9600); 15 | 16 | for(int n = 0; n < dataLength; n++) 17 | { 18 | sendBytes(data[n]); 19 | } 20 | } 21 | 22 | void loop() 23 | { 24 | } 25 | 26 | void sendBytes(uint16_t value) 27 | { 28 | Serial.write(highByte(value)); 29 | Serial.write(lowByte(value)); 30 | } 31 | ``` 32 | 33 | ```cpp 34 | const size_t dataLength = 10; 35 | int data[dataLength]; 36 | int dataIndex = 0; 37 | 38 | void setup() 39 | { 40 | Serial.begin(9600); 41 | } 42 | 43 | 44 | void loop() 45 | { 46 | if(Serial.available() >= sizeof(data[0]) 47 | { 48 | byte byte1 = Serial.read(); 49 | byte byte2 = Serial.read(); 50 | data[dataIndex] = byteToInt(byte1, byte2); 51 | 52 | dataIndex++; 53 | if(dataIndex >= dataLength) 54 | { 55 | dataIndex = 0; 56 | } 57 | } 58 | } 59 | 60 | uint16_t byteToInt(byte byte1, byte byte2) 61 | { 62 | return (uint16_t)byte1 << 8 | (uint16_t)byte2; 63 | } 64 | ``` 65 | 66 | 67 | ## Envío y recepción con cast directo 68 | ```cpp 69 | const size_t dataLength = 10; 70 | int data[dataLength]; 71 | 72 | void setup() 73 | { 74 | Serial.begin(9600); 75 | Serial.write((byte*)data, dataLength * sizeof(data[0])); 76 | } 77 | 78 | void loop() 79 | { 80 | } 81 | ``` 82 | 83 | ```cpp 84 | const size_t dataLength = 10; 85 | int data[dataLength]; 86 | 87 | void setup() 88 | { 89 | Serial.begin(9600); 90 | } 91 | 92 | void loop() 93 | { 94 | if(Serial.available() >= dataLength * sizeof(data[0])) 95 | { 96 | Serial.readBytes((byte*)data, dataLength * sizeof(data[0])); 97 | } 98 | } 99 | ``` 100 | 101 | 102 | -------------------------------------------------------------------------------- /030_arduino-avanzado/01 - Puerto serie avanzado/04 - arduino-array-separado-comas.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-array-separado-comas/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Recibir con clase string 8 | ```cpp 9 | #define DEBUG_ARRAY(a) {for (int index = 0; index < sizeof(a) / sizeof(a[0]); index++) {Serial.print(a[index]); Serial.print('\t');} Serial.println();}; 10 | 11 | String str = ""; 12 | const char separator = ','; 13 | const int dataLength = 3; 14 | int data[dataLength]; 15 | 16 | void setup() 17 | { 18 | Serial.begin(9600); 19 | } 20 | 21 | void loop() 22 | { 23 | if (Serial.available()) 24 | { 25 | str = Serial.readStringUntil('\n'); 26 | for (int i = 0; i < dataLength ; i++) 27 | { 28 | int index = str.indexOf(separator); 29 | data[i] = str.substring(0, index).toInt(); 30 | str = str.substring(index + 1); 31 | } 32 | DEBUG_ARRAY(data); 33 | } 34 | } 35 | ``` 36 | 37 | 38 | ## Recibir con char array y método naive 39 | ```cpp 40 | #define DEBUG_ARRAY(a) {for (int index = 0; index < sizeof(a) / sizeof(a[0]); index++) {Serial.print(a[index]); Serial.print('\t');} Serial.println();}; 41 | 42 | String str = ""; 43 | const char separator = ','; 44 | const int dataLength = 3; 45 | int dataArray[dataLength]; 46 | int data = 0; 47 | int dataIndex = 0; 48 | 49 | void setup() 50 | { 51 | Serial.begin(9600); 52 | } 53 | 54 | void loop() 55 | { 56 | while (Serial.available()) 57 | { 58 | char incomingChar = Serial.read(); 59 | if (incomingChar >= '0' && incomingChar <= '9') 60 | { 61 | data = (data * 10) + (incomingChar - '0'); 62 | } 63 | else if (incomingChar == separator) 64 | { 65 | dataArray[dataIndex] = data; 66 | if (++dataIndex >= dataLength) dataIndex = 0; 67 | data = 0; 68 | } 69 | else if (incomingChar == '\n') 70 | { 71 | dataArray[dataIndex] = data; 72 | data = 0; 73 | dataIndex = 0; 74 | DEBUG_ARRAY(dataArray); 75 | } 76 | } 77 | } 78 | ``` 79 | 80 | 81 | -------------------------------------------------------------------------------- /030_arduino-avanzado/01 - Puerto serie avanzado/05 - arduino-bytes-puerto-serie.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-bytes-puerto-serie/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Enviar una serie de bytes 8 | ```cpp 9 | const byte data[] = {0, 50, 100, 150, 200, 250}; 10 | const size_t dataLength = sizeof(data) / sizeof(data[0]); 11 | 12 | void setup() 13 | { 14 | Serial.begin(9600); 15 | Serial.write(data, dataLength); 16 | } 17 | 18 | void loop() 19 | { 20 | } 21 | ``` 22 | 23 | 24 | ## Recibir una serie de bytes 25 | ```cpp 26 | const int NUM_BYTES = 3; 27 | byte data[NUM_BYTES]; 28 | 29 | bool TryGetSerialData(const byte* data, uint8_t dataLength) 30 | { 31 | if (Serial.available() >= dataLength) 32 | { 33 | Serial.readBytes(data, dataLength); 34 | return true; 35 | } 36 | return false; 37 | } 38 | 39 | void OkAction() 40 | { 41 | } 42 | 43 | void setup() 44 | { 45 | Serial.begin(9600); 46 | } 47 | 48 | void loop() 49 | { 50 | if(TryGetSerialData(data, NUM_BYTES)) 51 | { 52 | OkAction(); 53 | } 54 | } 55 | ``` 56 | 57 | 58 | ## ¿Qué hacemos con los bytes recibidos? 59 | ```cpp 60 | void sendBytes(uint8_t value) 61 | { 62 | Serial.write(value); 63 | } 64 | 65 | void sendBytes(uint16_t value) 66 | { 67 | Serial.write(highByte(value)); 68 | Serial.write(lowByte(value)); 69 | } 70 | 71 | void sendBytes(uint32_t value) 72 | { 73 | int temp = value & 0xFFFF; 74 | sendBytes(temp); 75 | temp = value >> 16; 76 | sendBytes(temp); 77 | } 78 | ``` 79 | 80 | ```cpp 81 | uint8_t byteToInt(byte byte1) 82 | { 83 | return (uint8_t)byte1; 84 | } 85 | 86 | uint16_t byteToInt(byte byte1, byte byte2) 87 | { 88 | return (uint16_t)byte1 << 8 | (uint16_t)byte2; 89 | } 90 | 91 | uint32_t byteToLong(byte byte1, byte byte2, byte byte3, byte byte4) 92 | { 93 | return byte1 << 24 94 | | (uint32_t)byte2 << 16 95 | | (uint32_t)byte3 << 8 96 | | (uint32_t)byte4; 97 | } 98 | ``` 99 | 100 | 101 | -------------------------------------------------------------------------------- /030_arduino-avanzado/01 - Puerto serie avanzado/06 - estructuras-puerto-serie-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/estructuras-puerto-serie-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## estructuras-puerto-serie-arduino 8 | ```cpp 9 | void sendStructure(byte *structurePointer, int structureLength) 10 | { 11 | Serial.write(structurePointer, structureLength); 12 | } 13 | sendStructure((byte*)&myStruct, sizeof(myStruct)); 14 | ``` 15 | 16 | ```cpp 17 | void recieveStructure(byte *structurePointer, int structureLength) 18 | { 19 | Serial.readBytes(structurePointer, structureLength); 20 | } 21 | recieveStructure((byte*)&myStruct, sizeof(myStruct)); 22 | ``` 23 | 24 | 25 | ## Ejemplo envío estructura por puesto serie 26 | ```cpp 27 | struct servoMoveMessage 28 | { 29 | int servoNum; 30 | int positionGoal; 31 | float interval; 32 | }; 33 | 34 | struct servoMoveMessage message; 35 | 36 | void sendStructure(byte *structurePointer, int structureLength) 37 | { 38 | Serial.write(structurePointer, structureLength); 39 | } 40 | 41 | void setup() 42 | { 43 | Serial.begin(9600); 44 | 45 | message.servoNum = 10; 46 | message.positionGoal = 1200; 47 | message.interval = 2.5; 48 | 49 | sendStructure((byte*)&message, sizeof(message)); 50 | } 51 | 52 | void loop() 53 | { 54 | } 55 | ``` 56 | 57 | ```cpp 58 | struct servoMoveMessage 59 | { 60 | int servoNum; 61 | int positionGoal; 62 | float interval; 63 | }; 64 | 65 | struct servoMoveMessage message; 66 | 67 | void recieveStructure(byte *structurePointer, int structureLength) 68 | { 69 | if(Serial.available() < sizeof(message)) return; 70 | Serial.readBytes(structurePointer, structureLength); 71 | } 72 | 73 | void setup() 74 | { 75 | Serial.begin(9600); 76 | recieveStructure((byte*)&message, sizeof(message)); 77 | } 78 | 79 | void loop() 80 | { 81 | } 82 | ``` 83 | 84 | 85 | -------------------------------------------------------------------------------- /030_arduino-avanzado/01 - Puerto serie avanzado/07 - arduino-caracteres-control-puerto-serie.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-caracteres-control-puerto-serie/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## arduino-caracteres-control-puerto-serie 8 | ```cpp 9 | const char STX = '\x002'; 10 | const char ETX = '\x003'; 11 | 12 | const int data[] = {0, 50, 100, 150, 200, 250}; 13 | const size_t dataLength = sizeof(data) / sizeof(data[0]); 14 | const int bytesLength = dataLength * sizeof(data[0]); 15 | 16 | void setup() 17 | { 18 | Serial.begin(9600); 19 | Serial.write(STX); 20 | Serial.write((byte*)&data, dataLength); 21 | Serial.write(ETX); 22 | } 23 | 24 | void loop() 25 | { 26 | } 27 | ``` 28 | 29 | ```cpp 30 | const char STX = '\x002'; 31 | const char ETX = '\x003'; 32 | 33 | const int dataLength = 3; 34 | size_t data[dataLength]; 35 | const int bytesLength = dataLength * sizeof(data[0]); 36 | 37 | void setup() 38 | { 39 | Serial.begin(9600); 40 | } 41 | 42 | void loop() 43 | { 44 | if (Serial.available() >= bytesLength) 45 | { 46 | if (Serial.read() == STX) 47 | { 48 | Serial.readBytes((byte*)&data, bytesLength); 49 | 50 | if (Serial.read() == ETX) 51 | { 52 | //performAction(); 53 | } 54 | } 55 | } 56 | } 57 | ``` 58 | 59 | 60 | -------------------------------------------------------------------------------- /030_arduino-avanzado/02 - Filtrado/00 - reducir-ruido-sensores-arduino-muestreo-multiple.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/reducir-ruido-sensores-arduino-muestreo-multiple/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Adquisición por muestras constante 8 | ```cpp 9 | float MeasureN(int samplesNumber, float (*funct)()) 10 | { 11 | float sum; 12 | for (int i = 0; i < samplesNumber; i++) 13 | { 14 | sum += funct(); 15 | } 16 | 17 | return sum / samplesNumber; 18 | } 19 | 20 | //Funcion que simula la medicion de un sensor 21 | float getMeasure() 22 | { 23 | return 0.0; 24 | } 25 | 26 | void setup() 27 | { 28 | float measureN = MeasureN(100, getMeasure); 29 | } 30 | 31 | void loop() 32 | { 33 | 34 | } 35 | ``` 36 | 37 | 38 | ## Adquisición en tiempo constante 39 | ```cpp 40 | float MeasureT(int msInterval, float(*funct)()) 41 | { 42 | float sum; 43 | long startTime = millis(); 44 | int samplesNumber = 0; 45 | 46 | while (millis() - startTime < msInterval) 47 | { 48 | samplesNumber++; 49 | sum += getMeasure(); 50 | } 51 | return sum / samplesNumber; 52 | } 53 | 54 | //Funcion que simula la medicion de un sensor 55 | float getMeasure() 56 | { 57 | return 0.0; 58 | } 59 | 60 | void setup() 61 | { 62 | float measureT = MeasureT(50, getMeasure); 63 | } 64 | 65 | void loop() 66 | { 67 | 68 | } 69 | ``` 70 | 71 | 72 | ## Añadir puntos Max, Min y Mid 73 | ```cpp 74 | float min, max, mid; 75 | float MeasureN(int samplesNumber, float(*funct)()) 76 | { 77 | float value; 78 | 79 | for (int i = 0; i < samplesNumber; i++) 80 | { 81 | value = funct(); 82 | if (value > max) max = value; 83 | if (value < min) min = value; 84 | } 85 | 86 | mid = (max - min) / 2; 87 | return sum / samplesNumber; 88 | } 89 | 90 | float MeasureT(int msInterval, float(*funct)()) 91 | { 92 | float value; 93 | long startTime = millis(); 94 | 95 | while (millis() - startTime < msInterval) 96 | { 97 | value = funct(); 98 | if (value > max) max = value; 99 | if (value < min) min = value; 100 | } 101 | 102 | mid = (max - min) / 2; 103 | return sum / samplesNumber; 104 | } 105 | 106 | float getMeasure() 107 | { 108 | return 0.0; 109 | } 110 | 111 | void setup() 112 | { 113 | MeasureN(100, getMeasure); 114 | MeasureT(50, getMeasure); 115 | } 116 | 117 | void loop() 118 | { 119 | 120 | } 121 | ``` 122 | 123 | 124 | -------------------------------------------------------------------------------- /030_arduino-avanzado/02 - Filtrado/01 - arduino-filtro-media-movil.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-filtro-media-movil/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Implementación en Arduino 8 | ```cpp 9 | const int windowSize = 5; 10 | int circularBuffer[windowSize]; 11 | int* circularBufferAccessor = circularBuffer; 12 | 13 | int values[] = { 7729, 7330, 10075, 10998, 11502, 11781, 12413, 12530, 14070, 13789, 18186, 14401, 16691, 16654, 17424, 21104, 17230, 20656, 21584, 21297, 19986, 20808, 19455, 24029, 21455, 21350, 19854, 23476, 19349, 16996, 20546, 17187, 15548, 9179, 8586, 7095, 9718, 5148, 4047, 3873, 4398, 2989, 3848, 2916, 1142, 2427, 250, 2995, 1918, 4297, 617, 2715, 1662, 1621, 960, 500, 2114, 2354, 2900, 4878, 8972, 9460, 11283, 16147, 16617, 16778, 18711, 22036, 28432, 29756, 24944, 27199, 27760, 30706, 31671, 32185, 32290, 30470, 32616, 32075, 32210, 28822, 30823, 29632, 29157, 31585, 24133, 23245, 22516, 18513, 18330, 15450, 12685, 11451, 11280, 9116, 7975, 8263, 8203, 4641, 5232, 5724, 4347, 4319, 3045, 1099, 2035, 2411, 1727, 852, 1134, 966, 2838, 6033, 2319, 3294, 3587, 9076, 5194, 6725, 6032, 6444, 10293, 9507, 10881, 11036, 12789, 12813, 14893, 16465, 16336, 16854, 19249, 23126, 21461, 18657, 20474, 24871, 20046, 22832, 21681, 21978, 23053, 20569, 24801, 19045, 20092, 19470, 18446, 18851, 18210, 15078, 16309, 15055, 14427, 15074, 10776, 14319, 14183, 7984, 8344, 7071, 9675, 5985, 3679, 2321, 6757, 3291, 5003, 1401, 1724, 1857, 2605, 803, 2742, 2971, 2306, 3722, 3332, 4427, 5762, 5383, 7692, 8436, 13660, 8018, 9303, 10626, 16171, 14163, 17161, 19214, 21171, 17274, 20616, 18281, 21171, 18220, 19315, 22558, 21393, 22431, 20186, 24619, 21997, 23938, 20029, 20694, 20648, 21173, 20377, 19147, 18578, 16839, 15735, 15907, 18059, 12111, 12178, 11201, 10577, 11160, 8485, 7065, 7852, 5865, 4856, 3955, 6803, 3444, 1616, 717, 3105, 704, 1473, 1948, 4534, 5800, 1757, 1038, 2435, 4677, 8155, 6870, 4611, 5372, 6304, 7868, 10336, 9091 }; 14 | int valuesLength = sizeof(values) / sizeof(int); 15 | 16 | int getMeasure() 17 | { 18 | int static index = 0; 19 | index++; 20 | return values[index - 1]; 21 | } 22 | 23 | int appendToBuffer(int value) 24 | { 25 | *circularBufferAccessor = value; 26 | circularBufferAccessor++; 27 | if (circularBufferAccessor >= circularBuffer + windowSize) 28 | circularBufferAccessor = circularBuffer; 29 | } 30 | 31 | long sum; 32 | int elementCount; 33 | float mean; 34 | float AddValue(int value) 35 | { 36 | sum -= *circularBufferAccessor; 37 | sum += value; 38 | appendToBuffer(value); 39 | 40 | if (elementCount < windowSize) 41 | ++elementCount; 42 | return (float) sum / elementCount; 43 | } 44 | 45 | void setup() 46 | { 47 | Serial.begin(115200); 48 | 49 | for (int iCount = 0; iCount < valuesLength; iCount++) 50 | { 51 | float med = AddValue(getMeasure()); 52 | Serial.print(values[iCount]); 53 | Serial.print(",\t"); 54 | Serial.println(med); 55 | } 56 | } 57 | 58 | void loop() 59 | { 60 | } 61 | ``` 62 | 63 | 64 | -------------------------------------------------------------------------------- /030_arduino-avanzado/02 - Filtrado/04 - arduino-paso-bajo-exponencial.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-paso-bajo-exponencial/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Filtro paso bajo y paso alto en Arduino 8 | ```cpp 9 | float EMA_ALPHA = 0.6; 10 | int EMA_LP = 0; 11 | int EMA_HP = 0; 12 | 13 | int values[] = { 7729, 7330, 10075, 10998, 11502, 11781, 12413, 12530, 14070, 13789, 18186, 14401, 16691, 16654, 17424, 21104, 17230, 20656, 21584, 21297, 19986, 20808, 19455, 24029, 21455, 21350, 19854, 23476, 19349, 16996, 20546, 17187, 15548, 9179, 8586, 7095, 9718, 5148, 4047, 3873, 4398, 2989, 3848, 2916, 1142, 2427, 250, 2995, 1918, 4297, 617, 2715, 1662, 1621, 960, 500, 2114, 2354, 2900, 4878, 8972, 9460, 11283, 16147, 16617, 16778, 18711, 22036, 28432, 29756, 24944, 27199, 27760, 30706, 31671, 32185, 32290, 30470, 32616, 32075, 32210, 28822, 30823, 29632, 29157, 31585, 24133, 23245, 22516, 18513, 18330, 15450, 12685, 11451, 11280, 9116, 7975, 8263, 8203, 4641, 5232, 5724, 4347, 4319, 3045, 1099, 2035, 2411, 1727, 852, 1134, 966, 2838, 6033, 2319, 3294, 3587, 9076, 5194, 6725, 6032, 6444, 10293, 9507, 10881, 11036, 12789, 12813, 14893, 16465, 16336, 16854, 19249, 23126, 21461, 18657, 20474, 24871, 20046, 22832, 21681, 21978, 23053, 20569, 24801, 19045, 20092, 19470, 18446, 18851, 18210, 15078, 16309, 15055, 14427, 15074, 10776, 14319, 14183, 7984, 8344, 7071, 9675, 5985, 3679, 2321, 6757, 3291, 5003, 1401, 1724, 1857, 2605, 803, 2742, 2971, 2306, 3722, 3332, 4427, 5762, 5383, 7692, 8436, 13660, 8018, 9303, 10626, 16171, 14163, 17161, 19214, 21171, 17274, 20616, 18281, 21171, 18220, 19315, 22558, 21393, 22431, 20186, 24619, 21997, 23938, 20029, 20694, 20648, 21173, 20377, 19147, 18578, 16839, 15735, 15907, 18059, 12111, 12178, 11201, 10577, 11160, 8485, 7065, 7852, 5865, 4856, 3955, 6803, 3444, 1616, 717, 3105, 704, 1473, 1948, 4534, 5800, 1757, 1038, 2435, 4677, 8155, 6870, 4611, 5372, 6304, 7868, 10336, 9091 }; 14 | int valuesLength = sizeof(values) / sizeof(int); 15 | 16 | int getMeasure() 17 | { 18 | int static index = 0; 19 | index++; 20 | return values[index - 1]; 21 | } 22 | 23 | void setup() 24 | { 25 | Serial.begin(115200); 26 | 27 | for (int iCount = 0; iCount < valuesLength; iCount++) 28 | { 29 | int value = getMeasure(); 30 | int filteredLP = EMALowPassFilter(value); 31 | int filteredHP = EMAHighPassFilter(value); 32 | Serial.print(value); 33 | Serial.print(","); 34 | Serial.print(filteredLP); 35 | Serial.print(","); 36 | Serial.println(filteredHP); 37 | } 38 | } 39 | 40 | void loop() 41 | { 42 | delay(10000); 43 | } 44 | 45 | int EMALowPassFilter(int value) 46 | { 47 | EMA_LP = EMA_ALPHA * value + (1 - EMA_ALPHA) * EMA_LP; 48 | return EMA_LP; 49 | } 50 | 51 | int EMAHighPassFilter(int value) 52 | { 53 | EMA_LP = EMA_ALPHA * value + (1 - EMA_ALPHA) * EMA_LP; 54 | EMA_HP = value - EMA_LP; 55 | 56 | return EMA_HP; 57 | } 58 | ``` 59 | 60 | 61 | -------------------------------------------------------------------------------- /030_arduino-avanzado/02 - Filtrado/05 - arduino-paso-banda.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-paso-banda/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Filtro de paso banda y stop banda en Arduino 8 | ```cpp 9 | float EMA_ALPHA_LOW = 0.025; 10 | float EMA_ALPHA_HIGH = 0.1; 11 | int EMA_LP_LOW = 0; 12 | int EMA_LP_HIGH = 0; 13 | int EMA_BP = 0; 14 | int EMA_BS = 0; 15 | 16 | int values[] = { 7729, 7330, 10075, 10998, 11502, 11781, 12413, 12530, 14070, 13789, 18186, 14401, 16691, 16654, 17424, 21104, 17230, 20656, 21584, 21297, 19986, 20808, 19455, 24029, 21455, 21350, 19854, 23476, 19349, 16996, 20546, 17187, 15548, 9179, 8586, 7095, 9718, 5148, 4047, 3873, 4398, 2989, 3848, 2916, 1142, 2427, 250, 2995, 1918, 4297, 617, 2715, 1662, 1621, 960, 500, 2114, 2354, 2900, 4878, 8972, 9460, 11283, 16147, 16617, 16778, 18711, 22036, 28432, 29756, 24944, 27199, 27760, 30706, 31671, 32185, 32290, 30470, 32616, 32075, 32210, 28822, 30823, 29632, 29157, 31585, 24133, 23245, 22516, 18513, 18330, 15450, 12685, 11451, 11280, 9116, 7975, 8263, 8203, 4641, 5232, 5724, 4347, 4319, 3045, 1099, 2035, 2411, 1727, 852, 1134, 966, 2838, 6033, 2319, 3294, 3587, 9076, 5194, 6725, 6032, 6444, 10293, 9507, 10881, 11036, 12789, 12813, 14893, 16465, 16336, 16854, 19249, 23126, 21461, 18657, 20474, 24871, 20046, 22832, 21681, 21978, 23053, 20569, 24801, 19045, 20092, 19470, 18446, 18851, 18210, 15078, 16309, 15055, 14427, 15074, 10776, 14319, 14183, 7984, 8344, 7071, 9675, 5985, 3679, 2321, 6757, 3291, 5003, 1401, 1724, 1857, 2605, 803, 2742, 2971, 2306, 3722, 3332, 4427, 5762, 5383, 7692, 8436, 13660, 8018, 9303, 10626, 16171, 14163, 17161, 19214, 21171, 17274, 20616, 18281, 21171, 18220, 19315, 22558, 21393, 22431, 20186, 24619, 21997, 23938, 20029, 20694, 20648, 21173, 20377, 19147, 18578, 16839, 15735, 15907, 18059, 12111, 12178, 11201, 10577, 11160, 8485, 7065, 7852, 5865, 4856, 3955, 6803, 3444, 1616, 717, 3105, 704, 1473, 1948, 4534, 5800, 1757, 1038, 2435, 4677, 8155, 6870, 4611, 5372, 6304, 7868, 10336, 9091 }; 17 | int valuesLength = sizeof(values) / sizeof(int); 18 | 19 | int getMeasure() 20 | { 21 | int static index = 0; 22 | index++; 23 | return values[index-1]; 24 | } 25 | 26 | void setup() 27 | { 28 | Serial.begin(115200); 29 | 30 | for (int iCount = 0; iCount < valuesLength; iCount++) 31 | { 32 | int value = getMeasure(); 33 | int filteredBP = EMABandPassFilter(value); 34 | int filteredBS = EMABandStopFilter(value); 35 | Serial.print(value); 36 | Serial.print(","); 37 | Serial.print(filteredBP); 38 | Serial.print(","); 39 | Serial.println(filteredBS); 40 | } 41 | } 42 | 43 | void loop() 44 | { 45 | delay(10000); 46 | } 47 | 48 | int EMABandPassFilter(int value) 49 | { 50 | EMA_LP_LOW = EMA_ALPHA_LOW * value + (1 - EMA_ALPHA_LOW) * EMA_LP_LOW; 51 | EMA_LP_HIGH = EMA_ALPHA_HIGH * value + (1 - EMA_ALPHA_HIGH) * EMA_LP_HIGH; 52 | EMA_BP = EMA_LP_HIGH - EMA_LP_LOW; 53 | return EMA_BP; 54 | } 55 | 56 | int EMABandStopFilter(int value) 57 | { 58 | EMA_LP_LOW = EMA_ALPHA_LOW * value + (1 - EMA_ALPHA_LOW) * EMA_LP_LOW; 59 | EMA_LP_HIGH = EMA_ALPHA_HIGH * value + (1 - EMA_ALPHA_HIGH) * EMA_LP_HIGH; 60 | EMA_BP = EMA_LP_HIGH - EMA_LP_LOW; 61 | EMA_BS = value - EMA_BP; 62 | return EMA_BS; 63 | } 64 | ``` 65 | 66 | 67 | -------------------------------------------------------------------------------- /030_arduino-avanzado/04 - Estructuras de datos y algoritmos/00 - arduino-array-dinamico.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-array-dinamico/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Implementar un array dinámico en Arduino 8 | ```cpp 9 | int* list; 10 | size_t count; 11 | size_t capacity; 12 | 13 | // Crear una nueva lista 14 | void CreateList(size_t _capacity) 15 | { 16 | list = new int[_capacity]; 17 | capacity = _capacity; 18 | count = 0; 19 | } 20 | 21 | // Añadir elemento al final de la lista 22 | void AddItem(int item) 23 | { 24 | ++count; 25 | 26 | if (count > capacity) 27 | { 28 | size_t newSize = capacity * 2; 29 | resize(newSize); 30 | } 31 | 32 | list[count - 1] = item; 33 | } 34 | 35 | // Eliminar ultimo elemento de la lista 36 | void RemoveTail() 37 | { 38 | --count; 39 | } 40 | 41 | // Reducir capacidad de la lista al numero de elementos 42 | void Trim() 43 | { 44 | resize(count); 45 | } 46 | 47 | // Reescalar lista 48 | void resize(size_t newCapacity) 49 | { 50 | int* newList = new int[newCapacity]; 51 | memmove(newList, list, count * sizeof(int)); 52 | delete[] list; 53 | capacity = newCapacity; 54 | list = newList; 55 | } 56 | 57 | // Muestra la lista por Serial para debug 58 | void printList() 59 | { 60 | Serial.print("Capacity:"); 61 | Serial.print(capacity); 62 | 63 | Serial.print(" Count:"); 64 | Serial.print(count); 65 | 66 | Serial.print(" Items:"); 67 | for (size_t index = 0; index < count; index++) 68 | { 69 | Serial.print(list[index]); 70 | Serial.print(' '); 71 | } 72 | Serial.println(); 73 | } 74 | 75 | void setup() 76 | { 77 | Serial.begin(9600); 78 | 79 | Serial.println("Lista con 2 elementos"); 80 | CreateList(2); 81 | 82 | Serial.println(); 83 | Serial.println("Introducir 1 y 2 elementos"); 84 | AddItem(1); 85 | AddItem(2); 86 | printList(); 87 | 88 | Serial.println(); 89 | Serial.println("Resize e introducir 3 y 4 elementos"); 90 | AddItem(3); 91 | AddItem(4); 92 | printList(); 93 | 94 | Serial.println(); 95 | Serial.println("Resize e introducir 5 y 6 elementos"); 96 | AddItem(5); 97 | AddItem(6); 98 | printList(); 99 | 100 | Serial.println(); 101 | Serial.println("Eliminar dos ultimos"); 102 | RemoveTail(); 103 | RemoveTail(); 104 | printList(); 105 | 106 | Serial.println(); 107 | Serial.println("Ajustar tamaño"); 108 | Trim(); 109 | printList(); 110 | } 111 | 112 | void loop() 113 | { 114 | } 115 | ``` 116 | 117 | 118 | -------------------------------------------------------------------------------- /030_arduino-avanzado/04 - Estructuras de datos y algoritmos/01 - arduino-linked-list.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/arduino-linked-list/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Implementar una Linked list en Arduino 8 | ```cpp 9 | struct node { 10 | int value; 11 | node *next; 12 | }; 13 | 14 | node *head; 15 | size_t listSize; 16 | 17 | // Crea una linkedlist con un único elemento 18 | void createLinkedList(int value) 19 | { 20 | listSize = 1; 21 | head = new node(); 22 | head->next = nullptr; 23 | head->value = value; 24 | } 25 | 26 | // Añade un elemento al principio de la linkedlist 27 | void insertHead(int value) 28 | { 29 | node* newHead = new node(); 30 | newHead->next = head; 31 | newHead->value = value; 32 | head = newHead; 33 | listSize++; 34 | } 35 | 36 | // Añade un elemento al final de la linkedlist 37 | void insertTail(int value) 38 | { 39 | node* newTail = new node(); 40 | newTail->next = nullptr; 41 | newTail->value = value; 42 | 43 | node *enumerator = head; 44 | for (size_t index = 0; index < listSize - 1; index++) 45 | enumerator = enumerator->next; 46 | 47 | enumerator->next = newTail; 48 | listSize++; 49 | } 50 | 51 | void removeHead() 52 | { 53 | if(listSize <= 1) return; 54 | 55 | node* newHead = head->next; 56 | delete(head); 57 | head = newHead; 58 | listSize--; 59 | 60 | } 61 | 62 | void removeTail() 63 | { 64 | if(listSize <= 1) return; 65 | 66 | node *enumerator = head; 67 | for (size_t index = 0; index < listSize - 2; index++) 68 | enumerator = enumerator->next; 69 | 70 | delete enumerator->next; 71 | enumerator->next = nullptr; 72 | listSize--; 73 | } 74 | 75 | // Muestra la linkedlist por Serial 76 | void printLinkedList() 77 | { 78 | Serial.print("Size:"); 79 | Serial.print(listSize); 80 | 81 | Serial.print(" Items:"); 82 | node *enumerator; 83 | enumerator = head; 84 | 85 | for (size_t index = 0; index < listSize; index++) 86 | { 87 | Serial.print(enumerator->value); 88 | Serial.print(' '); 89 | enumerator = enumerator->next; 90 | } 91 | Serial.println(); 92 | } 93 | 94 | void setup() 95 | { 96 | Serial.begin(9600); 97 | 98 | Serial.println("Lista con elemento 3"); 99 | createLinkedList(3); 100 | printLinkedList(); 101 | 102 | Serial.println(); 103 | Serial.println("Añadir 4 y 5 al final"); 104 | insertTail(4); 105 | insertTail(5); 106 | printLinkedList(); 107 | 108 | Serial.println(); 109 | Serial.println("Añadir 1 y 2 al principio"); 110 | insertHead(2); 111 | insertHead(1); 112 | printLinkedList(); 113 | 114 | Serial.println(); 115 | Serial.println("Eliminar 1 y 5"); 116 | removeHead(); 117 | removeTail(); 118 | printLinkedList(); 119 | } 120 | 121 | void loop() 122 | { 123 | } 124 | ``` 125 | 126 | 127 | -------------------------------------------------------------------------------- /030_arduino-avanzado/05 - Teoría de control/05 - como-implementar-un-controlador-pid-en-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/como-implementar-un-controlador-pid-en-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Controlador PID a mano 8 | ```cpp 9 | // Asignaciones pins 10 | const int PIN_INPUT = A0; 11 | const int PIN_OUTPUT = 3; 12 | 13 | // Constantes del controlador 14 | double Kp=2, Ki=5, Kd=1; 15 | 16 | // variables externas del controlador 17 | double Input, Output, Setpoint; 18 | 19 | // variables internas del controlador 20 | unsigned long currentTime, previousTime; 21 | double elapsedTime; 22 | double error, lastError, cumError, rateError; 23 | 24 | void setup() 25 | { 26 | Input = analogRead(PIN_INPUT); 27 | Setpoint = 100; 28 | } 29 | 30 | void loop(){ 31 | 32 | pidController.Compute(); 33 | 34 | Input = analogRead(PIN_INPUT); // leer una entrada del controlador 35 | Output = computePID(Input); // calcular el controlador 36 | delay(100); 37 | analogWrite(PIN_OUTPUT, Output); // escribir la salida del controlador 38 | } 39 | 40 | double computePID(double inp){ 41 | currentTime = millis(); // obtener el tiempo actual 42 | elapsedTime = (double)(currentTime - previousTime); // calcular el tiempo transcurrido 43 | 44 | error = Setpoint - Input; // determinar el error entre la consigna y la medición 45 | cumError += error * elapsedTime; // calcular la integral del error 46 | rateError = (error - lastError) / elapsedTime; // calcular la derivada del error 47 | 48 | double output = kp*error + ki*cumError + kd*rateError; // calcular la salida del PID 49 | 50 | lastError = error; // almacenar error anterior 51 | previousTime = currentTime; // almacenar el tiempo anterior 52 | 53 | return output; 54 | } 55 | ``` 56 | 57 | 58 | ## Controlador PID con librería 59 | ```cpp 60 | #include 61 | 62 | const int PIN_INPUT = 0; 63 | const int PIN_OUTPUT = 3; 64 | 65 | PID::PIDParameters parameters(4.0, 0.2, 1); 66 | PID::PIDController pidController(parameters); 67 | 68 | void setup() 69 | { 70 | pidController.Input = analogRead(PIN_INPUT); 71 | pidController.Setpoint = 100; 72 | 73 | pidController.TurnOn(); 74 | } 75 | 76 | void loop() 77 | { 78 | pidController.Input = analogRead(PIN_INPUT); 79 | pidController.Update(); 80 | 81 | analogWrite(PIN_OUTPUT, pidController.Output); 82 | } 83 | ``` 84 | 85 | 86 | -------------------------------------------------------------------------------- /030_arduino-avanzado/05 - Teoría de control/06 - como-hacer-un-control-pid-de-iluminacion-constante-con-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/como-hacer-un-control-pid-de-iluminacion-constante-con-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## como-hacer-un-control-pid-de-iluminacion-constante-con-arduino 8 | ```csharp 9 | #include 10 | 11 | const long A = 1000; //Resistencia en oscuridad en KΩ 12 | const int B = 15; //Resistencia a la luz (10 Lux) en KΩ 13 | const int Rc = 10; //Resistencia calibracion en KΩ 14 | 15 | const int PIN_LDR = A0; 16 | const int PIN_LED = 9; 17 | 18 | PID::PIDParameters < double > parameters(0.4, 6.0, 0.0001); 19 | PID::PIDController < double > pidController(parameters); 20 | 21 | void setup() 22 | { 23 | Serial.begin(115200); 24 | pinMode(PIN_LED, OUTPUT); 25 | 26 | pidController.Input = analogRead(PIN_LDR); 27 | pidController.Setpoint = 350; 28 | 29 | pidController.TurnOn(); 30 | } 31 | 32 | float readLDR() 33 | { 34 | float mean = 0; 35 | for (auto i = 0; i < 100; i++) { 36 | auto V = (float) analogRead(PIN_LDR); 37 | mean += (V * A * 10) / (B * Rc * (1024 - V)); 38 | } 39 | mean /= 100; 40 | return mean; 41 | } 42 | 43 | void loop() 44 | { 45 | auto ilum = readLDR(); 46 | Serial.println(ilum); 47 | 48 | pidController.Input = ilum; 49 | pidController.Update(); 50 | 51 | analogWrite(PIN_LED, (int) pidController.Output); 52 | } 53 | ``` 54 | 55 | 56 | -------------------------------------------------------------------------------- /030_arduino-avanzado/06 - Automatización y robótica/04 - como-usar-freertos-en-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/como-usar-freertos-en-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Ejemplo de FreeRTOS 8 | ```csharp 9 | #include 10 | 11 | void TaskBlink(void *pvParameters) 12 | { 13 | (void) pvParameters; 14 | 15 | pinMode(LED_BUILTIN, OUTPUT); 16 | 17 | while(true) 18 | { 19 | digitalWrite(LED_BUILTIN, HIGH); 20 | vTaskDelay( 500 / portTICK_PERIOD_MS ); 21 | digitalWrite(LED_BUILTIN, LOW); 22 | vTaskDelay( 500 / portTICK_PERIOD_MS ); 23 | } 24 | } 25 | 26 | void setup() 27 | { 28 | Serial.begin(9600); 29 | 30 | xTaskCreate( 31 | TaskBlink 32 | , "Blink" // Nombre de la tarea 33 | , 128 // Tamaño de la pila de la tarea 34 | , NULL 35 | , 2 // Prioridad, siendo 0 la de menor prioridad, y 3 la de mayor 36 | , NULL ); 37 | } 38 | 39 | void loop() 40 | { 41 | Serial.println(millis()); 42 | delay(1000); 43 | } 44 | ``` 45 | 46 | 47 | -------------------------------------------------------------------------------- /030_arduino-avanzado/07 - Comunicación/02 - como-conectar-dos-arduino-por-bus-i2c.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/como-conectar-dos-arduino-por-bus-i2c/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Código Master 8 | ```cpp 9 | #include "Wire.h" 10 | 11 | const byte I2C_SLAVE_ADDR = 0x20; 12 | 13 | long data = 100; 14 | long response = 0; 15 | 16 | void setup() 17 | { 18 | Serial.begin(115200); 19 | Wire.begin(); 20 | } 21 | 22 | void loop() 23 | { 24 | sendToSlave(); 25 | requestToSlave(); 26 | delay(2000); 27 | } 28 | 29 | void sendToSlave() 30 | { 31 | Wire.beginTransmission(I2C_SLAVE_ADDR); 32 | Wire.write((byte*)&data, sizeof(data)); 33 | Wire.endTransmission(); 34 | } 35 | 36 | void requestToSlave() 37 | { 38 | response = 0; 39 | Wire.requestFrom(I2C_SLAVE_ADDR, sizeof(response)); 40 | 41 | uint8_t index = 0; 42 | byte* pointer = (byte*)&response; 43 | while (Wire.available()) 44 | { 45 | *(pointer + index) = (byte)Wire.read(); 46 | index++; 47 | } 48 | 49 | Serial.println(response); 50 | } 51 | ``` 52 | 53 | 54 | ## Código Slave 55 | ```cpp 56 | #include "Wire.h" 57 | 58 | const byte I2C_SLAVE_ADDR = 0x20; 59 | 60 | void setup() 61 | { 62 | Serial.begin(115200); 63 | 64 | Wire.begin(I2C_SLAVE_ADDR); 65 | Wire.onReceive(receiveEvent); 66 | Wire.onRequest(requestEvent); 67 | } 68 | 69 | long data = 0; 70 | long response = 200; 71 | 72 | void receiveEvent(int bytes) 73 | { 74 | data = 0; 75 | uint8_t index = 0; 76 | while (Wire.available()) 77 | { 78 | byte* pointer = (byte*)&data; 79 | *(pointer + index) = (byte)Wire.read(); 80 | index++; 81 | } 82 | } 83 | 84 | void requestEvent() 85 | { 86 | Wire.write((byte*)&response, sizeof(response)); 87 | } 88 | 89 | void loop() { 90 | 91 | if (data != 0) 92 | { 93 | Serial.println(data); 94 | data = 0; 95 | } 96 | } 97 | ``` 98 | 99 | 100 | -------------------------------------------------------------------------------- /030_arduino-avanzado/08 - Hardware/00 - analogicas-mas-precisas.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/analogicas-mas-precisas/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## analogicas-mas-precisas 8 | ```cpp 9 | long readVcc() { 10 | ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); 11 | delay(2); 12 | ADCSRA |= _BV(ADSC); 13 | while (bit_is_set(ADCSRA, ADSC)); 14 | 15 | long result = ADCL; 16 | result |= ADCH << 8; 17 | result = 1126400L / result; // Back-calculate AVcc in mV 18 | return result; 19 | } 20 | 21 | void setup() { 22 | Serial.begin(9600); 23 | } 24 | 25 | void loop() { 26 | Serial.println(readVcc(), DEC); 27 | delay(1000); 28 | } 29 | ``` 30 | 31 | ```cpp 32 | long readVcc() 33 | { 34 | ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); 35 | delay(2); 36 | ADCSRA |= _BV(ADSC); 37 | while (bit_is_set(ADCSRA, ADSC)); 38 | 39 | long result = ADCL; 40 | result |= ADCH << 8; 41 | result = 1126400L / result; // Back-calculate AVcc in mV 42 | return result; 43 | } 44 | 45 | void setup() 46 | { 47 | Serial.begin(9600); 48 | } 49 | 50 | void loop() 51 | { 52 | float vcc = readVcc() / 1000.0; 53 | float voltage = (analogRead(A0) / 1024.0) * Vcc; 54 | 55 | Serial.println(voltage); 56 | delay(1000); 57 | } 58 | ``` 59 | 60 | 61 | -------------------------------------------------------------------------------- /030_arduino-avanzado/08 - Hardware/02 - como-usar-correccion-gamma-en-fuentes-de-luz-con-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/como-usar-correccion-gamma-en-fuentes-de-luz-con-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Aplicar corrección Gamma en Arduino 8 | ```cpp 9 | const static uint8_t PROGMEM GammeTable8[] = { 10 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 12 | 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 13 | 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 14 | 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 15 | 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 16 | 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 24, 24, 25, 17 | 25, 26, 27, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 35, 36, 18 | 37, 38, 39, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 50, 19 | 51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68, 20 | 69, 70, 72, 73, 74, 75, 77, 78, 79, 81, 82, 83, 85, 86, 87, 89, 21 | 90, 92, 93, 95, 96, 98, 99,101,102,104,105,107,109,110,112,114, 22 | 115,117,119,120,122,124,126,127,129,131,133,135,137,138,140,142, 23 | 144,146,148,150,152,154,156,158,160,162,164,167,169,171,173,175, 24 | 177,180,182,184,186,189,191,193,196,198,200,203,205,208,210,213, 25 | 215,218,220,223,225,228,231,233,236,239,241,244,247,249,252,255 }; 26 | 27 | uint8_t CorrectGamma_Table8(uint8_t value) 28 | { 29 | result = pgm_read_byte(&GammeTable8[value]); 30 | } 31 | ``` 32 | 33 | ```cpp 34 | analogWrite(pin, CorrectGamma_Table8(PWM)); 35 | ``` 36 | 37 | ```cpp 38 | uint8_t CorrectGamma8(uint8_t value) 39 | { 40 | return (((45 * ((unsigned long)value + 1) + 3488) * ((unsigned long)value + 1) - 136379) * ((unsigned long)value + 1) + 1305350) / 3722130; 41 | } 42 | ``` 43 | 44 | ```cpp 45 | analogWrite(pin, CorrectGamma8(PWM)); 46 | ``` 47 | 48 | 49 | -------------------------------------------------------------------------------- /030_arduino-avanzado/08 - Hardware/03 - interrupciones-en-todos-los-pines-de-arduino-con-pcint.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/interrupciones-en-todos-los-pines-de-arduino-con-pcint/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## PCINT ejemplo de código 8 | ```cpp 9 | // Activar PCINT en un PIN 10 | void pciSetup(byte pin) 11 | { 12 | *digitalPinToPCMSK(pin) |= bit (digitalPinToPCMSKbit(pin)); // activar pin en PCMSK 13 | PCIFR |= bit (digitalPinToPCICRbit(pin)); // limpiar flag de la interrupcion en PCIFR 14 | PCICR |= bit (digitalPinToPCICRbit(pin)); // activar interrupcion para el grupo en PCICR 15 | } 16 | 17 | // Definir ISR para cada puerto 18 | ISR (PCINT0_vect) 19 | { 20 | // gestionar para PCINT para D8 a D13 21 | } 22 | 23 | ISR (PCINT1_vect) 24 | { 25 | // gestionar PCINT para A0 a A5 26 | } 27 | 28 | ISR (PCINT2_vect) 29 | { 30 | // gestionar PCINT para D0 a D7 31 | } 32 | 33 | void setup() 34 | { 35 | // Activar las PCINT para distintos pins 36 | pciSetup(7); 37 | pciSetup(8); 38 | pciSetup(9); 39 | pciSetup(A0); 40 | } 41 | 42 | void loop() 43 | { 44 | } 45 | ``` 46 | 47 | 48 | ## PCINT en una librería 49 | ```cpp 50 | #define PCINT_PIN A5 51 | 52 | #include 53 | 54 | void pinChanged(const char* message, bool pinstate) { 55 | Serial.print(message); 56 | Serial.println(pinstate ? "HIGH" : "LOW"); 57 | } 58 | 59 | void setup() { 60 | Serial.begin(115200); 61 | pinMode(PCINT_PIN, INPUT_PULLUP); 62 | PcInt::attachInterrupt(PCINT_PIN, pinChanged, "Pin has changed to ", CHANGE); 63 | } 64 | 65 | void loop() {} 66 | ``` 67 | 68 | 69 | -------------------------------------------------------------------------------- /030_arduino-avanzado/08 - Hardware/04 - como-emular-un-teclado-o-un-raton-con-arduino.md: -------------------------------------------------------------------------------- 1 | > Códigos de ejemplo de los tutoriales de www.luisllamas.es 2 | > 3 | > Enlace entrada: https://www.luisllamas.es/como-emular-un-teclado-o-un-raton-con-arduino/ 4 | > 5 | > Todo el contenido distribuido bajo licencia CCC, salvo indicación expresa 6 | 7 | ## Arduino como teclado 8 | ```cpp 9 | // Inicia y finaliza el teclado virtual 10 | Keyboard.begin() 11 | Keyboard.end() 12 | 13 | // Escribe un texto usando el teclado 14 | Keyboard.print() 15 | Keyboard.println() 16 | Keyboard.write() 17 | 18 | // Pulsar y soltar una tecla 19 | Keyboard.press() 20 | Keyboard.release() 21 | Keyboard.releaseAll() 22 | ``` 23 | 24 | 25 | ## Ejemplo teclado sencillo 26 | ```cpp 27 | #include 28 | 29 | void setup() { 30 | Keyboard.begin(); 31 | delay(5000); 32 | } 33 | 34 | void loop() { 35 | Keyboard.println("Hola mundo!"); 36 | delay(1000); 37 | } 38 | ``` 39 | 40 | 41 | ## Ejemplo teclado con combinaciones de teclas 42 | ```cpp 43 | #include 44 | 45 | void setup() { 46 | Keyboard.begin(); 47 | } 48 | 49 | void loop() { 50 | Keyboard.press(KEY_LEFT_CTRL); 51 | Keyboard.press('n'); 52 | delay(100); 53 | Keyboard.releaseAll(); 54 | 55 | // otra forma de hacer el release, tecla a tecla 56 | //Keyboard.release(KEY_LEFT_CTRL); 57 | //Keyboard.release('n'); 58 | 59 | delay(1000); 60 | } 61 | ``` 62 | 63 | 64 | ## Ejemplo teclado abrir notepad 65 | ```cpp 66 | #include 67 | 68 | void setup() { 69 | Keyboard.begin(); 70 | } 71 | 72 | void loop() { 73 | Keyboard.press(KEY_RIGHT_GUI); 74 | Keyboard.press('r'); 75 | delay(100); 76 | Keyboard.releaseAll(); 77 | delay(1000); 78 | 79 | Keyboard.println("notepad"); 80 | 81 | Keyboard.press(KEY_RETURN); 82 | delay(100); 83 | Keyboard.releaseAll(); 84 | 85 | Keyboard.print("Hola mundo!"); 86 | } 87 | ``` 88 | 89 | 90 | ## Emular ratón con Arduino 91 | ```cpp 92 | // Iniciar y detener el ratón virtual 93 | Mouse.begin() 94 | Mouse.end() 95 | 96 | // Movimiento relativo del ratón 97 | Mouse.move() 98 | 99 | // Hacer click con el ratón 100 | Mouse.click() 101 | Mouse.press() 102 | Mouse.release() 103 | Mouse.isPressed() 104 | ``` 105 | 106 | 107 | ## Ejemplo ratón sencillo 108 | ```cpp 109 | #include "Mouse.h" 110 | 111 | void setup() { 112 | Mouse.begin(); 113 | } 114 | 115 | void loop() { 116 | Mouse.move(10, 10, 0); 117 | Mouse.click(); 118 | delay(100); 119 | } 120 | ``` 121 | 122 | 123 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Recopilatorio de códigos de los tutoriales de Arduino 2 | 3 | [![www.luisllamas.es](img/screenshot.png)](https://www.luisllamas.es) 4 | 5 | ❤️ Repositorio con TODO el código y ejemplos de los tutoriales de Arduino de www.luisllamas.es 6 | 7 | 🌈Divididos en entradas y en dificultad (básico, intermedio, y avanzado) 8 | 9 | 10 | 🔗 Para más información de cada código en el tutorial de su respectiva entrada, cuya dirección se indica en la cabecera. 11 | 12 | 13 | ⭐️¡Si te gusta dale a la estrellita! 14 | 15 |

16 | 17 | **Repos con tutoriales de otras secciones** 18 | - Tutoriales Arduino: https://github.com/luisllamasbinaburo/tutoriales-arduino-luisllamas_es 19 | - Tutoriales ESP8266: https://github.com/luisllamasbinaburo/ESP8266-Examples 20 | - Tutoriales ESP32: https://github.com/luisllamasbinaburo/ESP32-Examples 21 | 22 |

23 | **Licencia** 24 | 25 | [![License: CC BY-NC-SA 4.0](https://licensebuttons.net/l/by-nc-sa/4.0/80x15.png)](https://creativecommons.org/licenses/by-nc-sa/4.0/) 26 | Todo el contenido distribuido bajo licencia CC BY-NC-SA, salvo indicación expresa. 27 | 28 | Las referencias y librerías empleadas, si es el caso, se indican en el tutorial correspondiente. Estarán sujetas a sus propia licencia, y no se incluyen en este repo. 29 | -------------------------------------------------------------------------------- /img/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luisllamasbinaburo/tutoriales-arduino-luisllamas_es/e13a82c53eeefbea3beb1ee52291ca7ea8ed1362/img/screenshot.png --------------------------------------------------------------------------------