En este tutorial veremos como controlar un aire acondicionado, con un esp32 y la aplicación telegram, desde cualquier parte del mundo, donde tengamos acceso a internet. El dispositivo, puede capturar con un módulo receptor infrarrojo, los comandos de un aire acondicionado, y en este proyecto controlaremos el encendido y apagado con la aplicación telegram, pero además podremos monitorear, el cambio de temperatura, para ver si realmente se ha encendido.
Tal vez pueda interesarte proyectos en arduino, pic, robótica, telecomunicaciones, suscribete en http://www.youtube.com/user/carlosvolt?sub_confirmation=1 mucho videos con código fuentes completos y diagramas
Componentes electrónicos
Un Esp32
Características del módulo ESP32-T
Conectividad
El módulo ESP32 dispone de todas las variantes del WiFi:
- 802.11 b/g/n/e/i/n
- Wi-Fi Direct (P2P), P2P Discovery, P2P Group Owner mode and P2P Power Management
Esta versión nueva incluye la conectividad mediante Bluethoot de bajo consumo
- Bluetooth v4.2 BR/EDR and BLE
- BLE Beacon
Además, puede comunicarse mediante los protocoles SPI, I2C, UART, MAC Ethernet, Host SD
Prestaciones del microcontrolador
La CPU está formado por un SoC modelo Tensilica LX6 con las siguientes características y memoria
- Doble núcleo de 32 bits con velocidad de 160MHz
- Memoria ROM de 448 kBytes
- Memoria SRAM de 520kBytes
Dispne de 48 Pines
- 18 ADC de 12 bits
- 2 DAC de 8 bits
- 10 pines sensores de contacto
- 16 PWM
- 20 Entradas/salidas digitales
Alimentación y modos de consumo
Para un correcto funcionamiento del ESP32 es necesario subministrar un voltaje de entre 2,8V y 3,6V. La energía que consume depende del modo de funcionamiento. Contiene un modo, el Ultra Low Power Solution (ULP), en que se continúan realizando tareas básicas (ADC, RTC…) en el modo Sleep.
Pines hembra
Módulo receptor infrarrojo ky-022
Tamaño: 6.4 * 7.4 * 5.1MM, ángulo de aceptación 90 °, voltaje de trabajo 2.7-5.5V.
Frecuencia 37.9KHZ, recibiendo la distancia 18 m.
Rechazo de luz diurna hasta 500LUX, capacidad de interferencia electromagnética, IC dedicado de infrarrojos incorporado.
Ampliamente utilizado: estéreo, TV, VCR, CD, decodificadores, marco de fotos digital, audio para el automóvil, juguetes de control remoto, receptores de satélite, disco duro, aire acondicionado, calefacción, ventiladores, iluminación y otros electrodomésticos.
Pinout:
1 …. GND (-)
2 …. + 5V
3 …. Salida (S)
Un transistor 2n3904
Descripción
|
SMALL SIGNAL BIPOLAR TRANSISTOR
|
|
Descripción detallada
|
Transistores – Bipolar (BJT) – Simple NPN 40 V 200 mA 300MHz 625 mW Orificio pasante TO-92-3
|
Hoja de datos
Pinout
Un resistor de 100 Ohm
Un resistor de 470 Ohm
Un Sensor de temperatura y humedad DHT11
Este módulo consta de un sensor digital de humedad y temperatura DHT11 y una resistencia de 1 kΩ. El DHT11 utiliza un termistor interno y un sensor de humedad capacitivo para determinar las condiciones ambientales, un chip interno es responsable de convertir las lecturas a una señal digital en serie.
Tensión de funcionamiento | 3.3V a 5.5V |
Rango de medición de humedad | 20% a 90% HR |
Precisión de medición de humedad | ± 5% HR |
Resolución de medición de humedad | 1% HR |
Rango de medición de temperatura | 0ºC a 50ºC [32ºF a 122ºF] |
Precisión de medición de temperatura | ± 2ºC |
Resolución de medición de temperatura | 1ºC |
Rango de transmisión de señal | 20m |
Cables Dupont
Un emisor infrarrojo
Un PCB
Archivo gerber —> Gerber_Control aire acondicionado por telegram
Circuito
Código fuente emisor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 |
#include <WiFi.h> #include <WiFiClientSecure.h> #include <UniversalTelegramBot.h> #include "PinDefinitionsAndMore.h"//Configuración y definición de pines #include <IRremote.hpp> #include "DHT.h" // Reemplazar con los datos de tu red wifi #define WIFI_SSID "Tu_red_wifi" #define WIFI_PASSWORD "tu_clave_wifi" //Token de Telegram BOT se obtenienen desde Botfather en telegram #define BOT_TOKEN "tu_token_de_telegram" const unsigned long tiempo = 1000; //tiempo medio entre mensajes de escaneo WiFiClientSecure secured_client; UniversalTelegramBot bot(BOT_TOKEN, secured_client); unsigned long tiempoAnterior; //última vez que se realizó el análisis de mensajes int inicio = 1; String datos; String stringT; String stringH; int aireEstado = 0; // Descomenta la linea dependiendo del sensor que vas a usar #define DHTTYPE DHT11 // DHT 11 //#define DHTTYPE DHT21 // DHT 21 //#define DHTTYPE DHT22 // DHT 22 #define DHTPin 23 //Pin del sensor DHT; DHT dht(DHTPin, DHTTYPE); float t; float h; String chat_id; #define ID_Chat "id_chat_telegram"//ID_Chat se obtiene de telegram void mensajesNuevos(int numerosMensajes) { for (int i = 0; i < numerosMensajes; i++) { String chat_id = bot.messages[i].chat_id; String text = bot.messages[i].text; if (text == "/TyH") { h = dht.readHumidity();//Lectura de la humedad t = dht.readTemperature();//Lectura de la temperatura stringT = String(t); stringH = String(h); Serial.print("T:" ); Serial.println(t); Serial.print("H:" ); Serial.println(h); datos = "Temperatura: "+ stringT + " Humedad: " +stringH; bot.sendMessage(chat_id, datos, "");//Enviamos la temperatura y humedad } //////////Comando para encender el aire acondicionado////// if (text == "/Aireon") { const uint16_t irSignal[227] = { //Código para encendido de aire acondicionado marca Electra 3100, 1600 , 500, 1100 , 450, 1100 , 450, 300 , 500, 350 , 450, 350 , 450, 1100 , 450, 350 , 450, 350 , 450, 1150 , 400, 1150 , 400, 400 , 400, 1150 , 450, 350 , 450, 350 , 450, 1100 , 450, 1150 , 400, 400 , 400, 1150 , 400, 1150 , 400, 400 , 400, 400 , 400, 1150 , 450, 350 , 450, 350 , 450, 1100 , 450, 350 , 450, 350 , 450, 350 , 450, 350 , 450, 350 , 450, 350 , 450, 350 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 1150 , 400, 400 , 400, 400 , 400, 1150 , 450, 350 , 450, 350 , 400, 400 , 400, 1150 , 450, 350 , 450, 350 , 450, 350 , 450, 350 , 450, 350 , 450, 350 , 450, 350 , 400, 400 , 400, 400 , 400, 1150 , 450, 350 , 450, 350 , 450, 350 , 450, 350 , 450, 350 , 450, 350 , 450, 350 , 400, 400 , 400, 400 , 400, 400 , 400, 1150 , 400, 400 , 450, 350 , 450, 350 , 450, 350 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 350, 450 , 400, 400 , 350, 450 , 400, 400 , 400, 400 , 400, 400 , 350, 450 , 350, 450 , 350, 450 , 350, 450 , 350, 1200 , 400, 1150 , 400, 1150 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400 }; IrSender.sendRaw(irSignal, 227, 38); bot.sendMessage(chat_id, "Comando encendido ejecutado", ""); aireEstado = 1; } //////////Comando para apagar el aire acondicionado//////// if (text == "/Aireoff") { const uint16_t irSignal2[227] = { //Código para apagado de aire acondicionado marca Electra 3100, 1600 , 450, 1100 , 500, 1100 , 450, 350 , 450, 350 , 450, 350 , 450, 1100 , 450, 400 , 400, 350 , 450, 1150 , 400, 1150 , 400, 400 , 400, 1150 , 400, 400 , 400, 400 , 400, 1150 , 400, 1150 , 400, 400 , 450, 1150 , 400, 1150 , 400, 400 , 400, 400 , 400, 1150 , 400, 400 , 400, 400 , 400, 1150 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 350 , 400, 1200 , 400, 400 , 400, 400 , 400, 1150 , 400, 1150 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 1150 , 400, 450 , 350, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 1150 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 350, 450 , 350, 450 , 350, 450 , 350, 450 , 350, 450 , 350, 450 , 350, 450 , 350, 450 , 350, 450 , 350, 450 , 350, 450 , 350, 450 , 350, 450 , 350, 450 , 350, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 1150 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 400, 400 , 350, 500 , 300, 450 , 400 }; IrSender.sendRaw(irSignal2, 227, 38); bot.sendMessage(chat_id, "Comando apagado ejecutado", ""); aireEstado = 2; } ////////Último comando enviado /////// if (text == "/Estado") { ////Ultimo comando enviado//// if (aireEstado == 0) { bot.sendMessage(chat_id, "No definido", ""); } if (aireEstado == 1) { bot.sendMessage(chat_id, "Último comando: Encendido", ""); } if (aireEstado == 2) { bot.sendMessage(chat_id, "Último comando: Apagado", ""); } } if (text == "/Ayuda") { String ayuda = "Bienvenido al sistema de control luces con Esp32, " ".\n"; ayuda += "Estas son tus opciones.\n\n"; ayuda += "/Aireon: para encender el aire \n"; ayuda += "/Aireoff: para apagar el aire \n"; ayuda += "/TyH : Muestra la Temperatura y Humedad \n"; ayuda += "/Ayuda: Imprime este menú \n"; ayuda += "Recuerda el sistema distingue entre mayuculas y minusculas \n"; bot.sendMessage(chat_id, ayuda, ""); } } } void setup() { Serial.begin(115200); dht.begin();//Inicializar el sensor DHT // Intenta conectarse a la red wifi Serial.print("Conectando a la red "); Serial.print(WIFI_SSID); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); //Agregar certificado raíz para api.telegram.org while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.print("\nConectado a la red wifi. Dirección IP: "); Serial.println(WiFi.localIP()); if(inicio == 1){ Serial.println("Sistema preparado"); bot.sendMessage(ID_Chat, "Sistema preparado!!!, escribe /Ayuda para ver las opciones", "");//Enviamos un mensaje a telegram para informar que el sistema está listo inicio = 0; } } void loop() { //Verifica si hay datos nuevos en telegram cada 1 segundo if (millis() - tiempoAnterior > tiempo) { int numerosMensajes = bot.getUpdates(bot.last_message_received + 1); while (numerosMensajes) { Serial.println("Comando recibido"); mensajesNuevos(numerosMensajes); numerosMensajes = bot.getUpdates(bot.last_message_received + 1); } tiempoAnterior = millis(); } } |
Definición de pines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 |
/* * PinDefinitionsAndMore.h * * Contains pin definitions for IRremote examples for various platforms * as well as definitions for feedback LED and tone() and includes * * Copyright (C) 2021-2022 Armin Joachimsmeyer * armin.joachimsmeyer@gmail.com * * This file is part of IRremote https://github.com/Arduino-IRremote/Arduino-IRremote. * * Arduino-IRremote is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/gpl.html>. * */ /* * Pin mapping table for different platforms * * Platform IR input IR output Tone Core/Pin schema * -------------------------------------------------------------- * DEFAULT/AVR 2 3 4 * ATtinyX5 0|PB0 4|PB4 3|PB3 * ATtiny167 3|PA3 2|PA2 7|PA7 ATTinyCore * ATtiny167 9|PA3 8|PA2 5|PA7 Digispark pro * ATtiny3217 18|PA1 19|PA2 20|PA3 MegaTinyCore * ATtiny1604 2 3|PA5 % * SAMD21 3 4 5 * ESP8266 14|D5 12|D6 % * ESP32 15 4 27 * BluePill PA6 PA7 PA3 * APOLLO3 11 12 5 * RP2040 3|GPIO15 4|GPIO16 5|GPIO17 */ //#define _IR_MEASURE_TIMING // For debugging purposes. /* * We do not have pin restrictions for this CPU's, so lets use the hardware PWM for send carrier signal generation */ #if defined(ESP32) || defined(ARDUINO_ARCH_RP2040) || defined(PARTICLE) #define SEND_PWM_BY_TIMER #endif #if defined(ESP8266) #define FEEDBACK_LED_IS_ACTIVE_LOW // The LED on my board (D4) is active LOW #define IR_RECEIVE_PIN 14 // D5 #define IR_RECEIVE_PIN_STRING "D5" #define IR_SEND_PIN 12 // D6 - D4/pin 2 is internal LED #define IR_SEND_PIN_STRING "D6" #define _IR_TIMING_TEST_PIN 13 // D7 #define APPLICATION_PIN 0 // D3 #define tone(...) void() // tone() inhibits receive timer #define noTone(a) void() #define TONE_PIN 42 // Dummy for examples using it #elif defined(ESP32) #include <Arduino.h> #define TONE_LEDC_CHANNEL 1 // Using channel 1 makes tone() independent of receiving timer -> No need to stop receiving timer. void tone(uint8_t _pin, unsigned int frequency){ ledcAttachPin(_pin, TONE_LEDC_CHANNEL); ledcWriteTone(TONE_LEDC_CHANNEL, frequency); } void tone(uint8_t _pin, unsigned int frequency, unsigned long duration){ ledcAttachPin(_pin, TONE_LEDC_CHANNEL); ledcWriteTone(TONE_LEDC_CHANNEL, frequency); delay(duration); ledcWriteTone(TONE_LEDC_CHANNEL, 0); } void noTone(uint8_t _pin){ ledcWriteTone(TONE_LEDC_CHANNEL, 0); } #define IR_RECEIVE_PIN 15 // D15 #define IR_SEND_PIN 4 // D4 #define TONE_PIN 27 // D27 25 & 26 are DAC0 and 1 #define APPLICATION_PIN 16 // RX2 pin #elif defined(ARDUINO_ARCH_STM32) || defined(ARDUINO_ARCH_STM32F1) // BluePill // Timer 3 blocks PA6, PA7, PB0, PB1 for use by Servo or tone() #define IR_RECEIVE_PIN PA6 #define IR_RECEIVE_PIN_STRING "PA6" #define IR_SEND_PIN PA7 #define IR_SEND_PIN_STRING "PA7" #define TONE_PIN PA3 #define _IR_TIMING_TEST_PIN PA5 #define APPLICATION_PIN PA2 #elif defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) // Digispark board #include "ATtinySerialOut.hpp" // Available as Arduino library "ATtinySerialOut". saves 370 bytes program space and 38 bytes RAM for digistump core #define IR_RECEIVE_PIN 0 #define IR_SEND_PIN 4 // Pin 2 is serial output with ATtinySerialOut. Pin 1 is internal LED and Pin3 is USB+ with pullup on Digispark board. #define TONE_PIN 3 #define _IR_TIMING_TEST_PIN 3 #elif defined(__AVR_ATtiny87__) || defined(__AVR_ATtiny167__) // Digispark pro board #include "ATtinySerialOut.hpp" // Available as Arduino library "ATtinySerialOut" // For ATtiny167 Pins PB6 and PA3 are usable as interrupt source. # if defined(ARDUINO_AVR_DIGISPARKPRO) #define IR_RECEIVE_PIN 9 // PA3 - on Digispark board labeled as pin 9 //#define IR_RECEIVE_PIN 14 // PB6 / INT0 is connected to USB+ on DigisparkPro boards #define IR_SEND_PIN 8 // PA2 - on Digispark board labeled as pin 8 #define TONE_PIN 5 // PA7 #define _IR_TIMING_TEST_PIN 10 // PA4 # else #define IR_RECEIVE_PIN 3 #define IR_SEND_PIN 2 #define TONE_PIN 7 # endif #elif defined(__AVR_ATtiny88__) // MH-ET Tiny88 board #include "ATtinySerialOut.hpp" // Available as Arduino library "ATtinySerialOut". Saves 128 bytes program space // Pin 6 is TX pin 7 is RX #define IR_RECEIVE_PIN 3 // INT1 #define IR_SEND_PIN 4 #define TONE_PIN 9 #define _IR_TIMING_TEST_PIN 8 #elif defined(__AVR_ATtiny1616__) || defined(__AVR_ATtiny3216__) || defined(__AVR_ATtiny3217__) // Tiny Core Dev board #define IR_RECEIVE_PIN 18 #define IR_SEND_PIN 19 #define TONE_PIN 20 #define APPLICATION_PIN 0 // PA4 #undef LED_BUILTIN // No LED available on the TinyCore 32 board, take the one on the programming board which is connected to the DAC output #define LED_BUILTIN 2 // PA6 #elif defined(__AVR_ATtiny1604__) #define IR_RECEIVE_PIN 2 // To be compatible with interrupt example, pin 2 is chosen here. #define IR_SEND_PIN 3 #define APPLICATION_PIN 5 #define tone(...) void() // Define as void, since TCB0_INT_vect is also used by tone() #define noTone(a) void() #define TONE_PIN 42 // Dummy for examples using it # elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) \ || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644P__) \ || defined(__AVR_ATmega324P__) || defined(__AVR_ATmega324A__) \ || defined(__AVR_ATmega324PA__) || defined(__AVR_ATmega164A__) \ || defined(__AVR_ATmega164P__) || defined(__AVR_ATmega32__) \ || defined(__AVR_ATmega16__) || defined(__AVR_ATmega8535__) \ || defined(__AVR_ATmega64__) || defined(__AVR_ATmega128__) \ || defined(__AVR_ATmega1281__) || defined(__AVR_ATmega2561__) \ || defined(__AVR_ATmega8515__) || defined(__AVR_ATmega162__) #define IR_RECEIVE_PIN 2 #define IR_SEND_PIN 13 #define TONE_PIN 4 #define APPLICATION_PIN 5 #define ALTERNATIVE_IR_FEEDBACK_LED_PIN 6 // E.g. used for examples which use LED_BUILDIN for example output. #define _IR_TIMING_TEST_PIN 7 #elif defined(ARDUINO_ARCH_APOLLO3) // Sparkfun Apollo boards #define IR_RECEIVE_PIN 11 #define IR_SEND_PIN 12 #define TONE_PIN 5 #elif defined(ARDUINO_ARCH_MBED) && defined(ARDUINO_ARCH_MBED_NANO) // Arduino Nano 33 BLE #define IR_RECEIVE_PIN 3 // GPIO15 Start with pin 3 since pin 2|GPIO25 is connected to LED on Pi pico #define IR_SEND_PIN 4 // GPIO16 #define TONE_PIN 5 #define APPLICATION_PIN 6 #define ALTERNATIVE_IR_FEEDBACK_LED_PIN 7 // E.g. used for examples which use LED_BUILDIN for example output. #define _IR_TIMING_TEST_PIN 8 #elif defined(ARDUINO_ARCH_RP2040) // Arduino Nano Connect, Pi Pico with arduino-pico core https://github.com/earlephilhower/arduino-pico #define IR_RECEIVE_PIN 15 // to be compatible with the Arduino Nano RP2040 Connect (pin3) #define IR_SEND_PIN 16 #define TONE_PIN 17 #define APPLICATION_PIN 18 #define ALTERNATIVE_IR_FEEDBACK_LED_PIN 19 // E.g. used for examples which use LED_BUILDIN for example output. #define _IR_TIMING_TEST_PIN 20 // If you program the Nano RP2040 Connect with this core, then you must redefine LED_BUILTIN // and use the external reset with 1 kOhm to ground to enter UF2 mode //#undef LED_BUILTIN //#define LED_BUILTIN 6 #elif defined(PARTICLE) // !!!UNTESTED!!! #define IR_RECEIVE_PIN A4 #define IR_SEND_PIN A5 // Particle supports multiple pins #define LED_BUILTIN D7 /* * 4 times the same (default) layout for easy adaption in the future */ #elif defined(TEENSYDUINO) #define IR_RECEIVE_PIN 2 #define IR_SEND_PIN 3 #define TONE_PIN 4 #define APPLICATION_PIN 5 #define ALTERNATIVE_IR_FEEDBACK_LED_PIN 6 // E.g. used for examples which use LED_BUILDIN for example output. #define _IR_TIMING_TEST_PIN 7 #elif defined(__AVR__) // Default as for ATmega328 like on Uno, Nano etc. #define IR_RECEIVE_PIN 2 // To be compatible with interrupt example, pin 2 is chosen here. #define IR_SEND_PIN 3 #define TONE_PIN 4 #define APPLICATION_PIN 5 #define ALTERNATIVE_IR_FEEDBACK_LED_PIN 6 // E.g. used for examples which use LED_BUILDIN for example output. #define _IR_TIMING_TEST_PIN 7 # if defined(ARDUINO_AVR_PROMICRO) // Sparkfun Pro Micro is __AVR_ATmega32U4__ but has different external circuit // We have no built in LED at pin 13 -> reuse RX LED #undef LED_BUILTIN #define LED_BUILTIN LED_BUILTIN_RX # endif #elif defined(ARDUINO_ARCH_MBED) // Arduino Nano 33 BLE #define IR_RECEIVE_PIN 2 #define IR_SEND_PIN 3 #define TONE_PIN 4 #define APPLICATION_PIN 5 #define ALTERNATIVE_IR_FEEDBACK_LED_PIN 6 // E.g. used for examples which use LED_BUILDIN for example output. #define _IR_TIMING_TEST_PIN 7 #elif defined(ARDUINO_ARCH_SAMD) || defined(ARDUINO_ARCH_SAM) #define IR_RECEIVE_PIN 2 #define IR_SEND_PIN 3 #define TONE_PIN 4 #define APPLICATION_PIN 5 #define ALTERNATIVE_IR_FEEDBACK_LED_PIN 6 // E.g. used for examples which use LED_BUILDIN for example output. #define _IR_TIMING_TEST_PIN 7 // On the Zero and others we switch explicitly to SerialUSB #define Serial SerialUSB // Definitions for the Chinese SAMD21 M0-Mini clone, which has no led connected to D13/PA17. // Attention!!! D2 and D4 are switched on these boards!!! // If you connect the LED, it is on pin 24/PB11. In this case activate the next two lines. //#undef LED_BUILTIN //#define LED_BUILTIN 24 // PB11 // As an alternative you can choose pin 25, it is the RX-LED pin (PB03), but active low.In this case activate the next 3 lines. //#undef LED_BUILTIN //#define LED_BUILTIN 25 // PB03 //#define FEEDBACK_LED_IS_ACTIVE_LOW // The RX LED on the M0-Mini is active LOW #elif defined (NRF51) // BBC micro:bit #define IR_RECEIVE_PIN 2 #define IR_SEND_PIN 3 #define APPLICATION_PIN 1 #define _IR_TIMING_TEST_PIN 4 #define tone(...) void() // no tone() available #define noTone(a) void() #define TONE_PIN 42 // Dummy for examples using it #else #warning Board / CPU is not detected using pre-processor symbols -> using default values, which may not fit. Please extend PinDefinitionsAndMore.h. // Default valued for unidentified boards #define IR_RECEIVE_PIN 2 #define IR_SEND_PIN 3 #define TONE_PIN 4 #define APPLICATION_PIN 5 #define ALTERNATIVE_IR_FEEDBACK_LED_PIN 6 // E.g. used for examples which use LED_BUILDIN for example output. #define _IR_TIMING_TEST_PIN 7 #endif // defined(ESP8266) #if !defined (FLASHEND) #define FLASHEND 0xFFFF // Dummy value for platforms where FLASHEND is not defined #endif /* * Helper macro for getting a macro definition as string */ #if !defined(STR_HELPER) #define STR_HELPER(x) #x #define STR(x) STR_HELPER(x) #endif |
ReceiveDemo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
/* * ReceiveDemo.cpp * * Demonstrates receiving IR codes with the IRremote library. * If debug button is pressed (pin connected to ground) a long output is generated. * * This file is part of Arduino-IRremote https://github.com/Arduino-IRremote/Arduino-IRremote. * ************************************************************************************ * MIT License * * Copyright (c) 2020-2022 Armin Joachimsmeyer * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished * to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ************************************************************************************ */ #include <Arduino.h> /* * Specify which protocol(s) should be used for decoding. * If no protocol is defined, all protocols are active. * This must be done before the #include <IRremote.hpp> */ //#define DECODE_LG //#define DECODE_NEC // etc. see IRremote.hpp // #define RAW_BUFFER_LENGTH 750 // 750 is the value for air condition remotes. //#define NO_LED_FEEDBACK_CODE // saves 92 bytes program space #if FLASHEND <= 0x1FFF // For 8k flash or less, like ATtiny85. Exclude exotic protocols. #define EXCLUDE_EXOTIC_PROTOCOLS # if !defined(DIGISTUMPCORE) // ATTinyCore is bigger than Digispark core #define EXCLUDE_UNIVERSAL_PROTOCOLS // Saves up to 1000 bytes program space. # endif #endif //#define EXCLUDE_UNIVERSAL_PROTOCOLS // Saves up to 1000 bytes program space. //#define EXCLUDE_EXOTIC_PROTOCOLS // saves around 650 bytes program space if all other protocols are active //#define _IR_MEASURE_TIMING // MARK_EXCESS_MICROS is subtracted from all marks and added to all spaces before decoding, // to compensate for the signal forming of different IR receiver modules. //#define MARK_EXCESS_MICROS 20 // 20 is recommended for the cheap VS1838 modules //#define RECORD_GAP_MICROS 12000 // Activate it for some LG air conditioner protocols //#define DEBUG // Activate this for lots of lovely debug output from the decoders. #define INFO // To see valuable informations from universal decoder for pulse width or pulse distance protocols /* * First define macros for input and output pin etc. */ #include "PinDefinitionsAndMore.h" #include <IRremote.hpp> #if defined(APPLICATION_PIN) #define DEBUG_BUTTON_PIN APPLICATION_PIN // if low, print timing for each received data set #else #define DEBUG_BUTTON_PIN 6 #endif // On the Zero and others we switch explicitly to SerialUSB #if defined(ARDUINO_ARCH_SAMD) #define Serial SerialUSB #endif void setup() { #if defined(_IR_MEASURE_TIMING) && defined(_IR_TIMING_TEST_PIN) pinMode(_IR_TIMING_TEST_PIN, OUTPUT); #endif #if FLASHEND >= 0x3FFF // For 16k flash or more, like ATtiny1604. Code does not fit in program space of ATtiny85 etc. pinMode(DEBUG_BUTTON_PIN, INPUT_PULLUP); #endif Serial.begin(115200); #if defined(__AVR_ATmega32U4__) || defined(SERIAL_PORT_USBVIRTUAL) || defined(SERIAL_USB) || defined(SERIALUSB_PID) || defined(ARDUINO_attiny3217) delay(4000); // To be able to connect Serial monitor after reset or power up and before first print out. Do not wait for an attached Serial Monitor! #endif // Just to know which program is running on my Arduino Serial.println(F("START " __FILE__ " from " __DATE__ "\r\nUsing library version " VERSION_IRREMOTE)); // In case the interrupt driver crashes on setup, give a clue // to the user what's going on. Serial.println(F("Enabling IRin...")); // Start the receiver and if not 3. parameter specified, take LED_BUILTIN pin from the internal boards definition as default feedback LED IrReceiver.begin(IR_RECEIVE_PIN, ENABLE_LED_FEEDBACK); Serial.print(F("Ready to receive IR signals of protocols: ")); printActiveIRProtocols(&Serial); Serial.print(F("at pin ")); #if defined(ARDUINO_ARCH_STM32) || defined(ESP8266) Serial.println(IR_RECEIVE_PIN_STRING); #else Serial.println(IR_RECEIVE_PIN); #endif #if FLASHEND >= 0x3FFF // For 16k flash or more, like ATtiny1604. Code does not fit in program space of ATtiny85 etc. Serial.print(F("Debug button pin is ")); Serial.println(DEBUG_BUTTON_PIN); // infos for receive Serial.print(RECORD_GAP_MICROS); Serial.println(F(" us is the (minimum) gap, after which the start of a new IR packet is assumed")); Serial.print(MARK_EXCESS_MICROS); Serial.println(F(" us are subtracted from all marks and added to all spaces for decoding")); #endif } void loop() { /* * Check if received data is available and if yes, try to decode it. * Decoded result is in the IrReceiver.decodedIRData structure. * * E.g. command is in IrReceiver.decodedIRData.command * address is in command is in IrReceiver.decodedIRData.address * and up to 32 bit raw data in IrReceiver.decodedIRData.decodedRawData */ if (IrReceiver.decode()) { Serial.println(); #if FLASHEND >= 0x3FFF // For 16k flash or more, like ATtiny1604 if (IrReceiver.decodedIRData.flags & IRDATA_FLAGS_WAS_OVERFLOW) { Serial.println(F("Overflow detected")); Serial.println(F("Try to increase the \"RAW_BUFFER_LENGTH\" value of " STR(RAW_BUFFER_LENGTH) " in " __FILE__)); // see also https://github.com/Arduino-IRremote/Arduino-IRremote#modifying-compile-options-with-sloeber-ide # if !defined(ESP8266) && !defined(NRF5) /* * do double beep */ # if !defined(ESP32) IrReceiver.stop(); // ESP32 uses another timer for tone() # endif tone(TONE_PIN, 1100, 10); delay(50); tone(TONE_PIN, 1100, 10); delay(50); # if !defined(ESP32) IrReceiver.start(100000); // to compensate for 100 ms stop of receiver. This enables a correct gap measurement. # endif # endif } else { // Print a short summary of received data IrReceiver.printIRResultShort(&Serial); if (IrReceiver.decodedIRData.protocol == UNKNOWN || digitalRead(DEBUG_BUTTON_PIN) == LOW) { // We have an unknown protocol, print more info IrReceiver.printIRResultRawFormatted(&Serial, true); } } // tone on esp8266 works once, then it disables the successful IrReceiver.start() / timerConfigForReceive(). # if !defined(ESP8266) && !defined(NRF5) if (IrReceiver.decodedIRData.protocol != UNKNOWN) { /* * If a valid protocol was received, play tone, wait and restore IR timer. * Otherwise do not play a tone to get exact gap time between transmissions. * This will give the next CheckForRecordGapsMicros() call a chance to eventually propose a change of the current RECORD_GAP_MICROS value. */ # if !defined(ESP32) IrReceiver.stop(); // ESP32 uses another timer for tone() # endif tone(TONE_PIN, 2200, 8); # if !defined(ESP32) delay(8); IrReceiver.start(8000); // to compensate for 8 ms stop of receiver. This enables a correct gap measurement. # endif } # endif #else // Print a minimal summary of received data IrReceiver.printIRResultMinimal(&Serial); #endif // FLASHEND /* * !!!Important!!! Enable receiving of the next value, * since receiving has stopped after the end of the current received data packet. */ IrReceiver.resume(); /* * Finally check the received data and perform actions according to the received address and commands */ if (IrReceiver.decodedIRData.address == 0) { if (IrReceiver.decodedIRData.command == 0x10) { // do something } else if (IrReceiver.decodedIRData.command == 0x11) { // do something else } } } // if (IrReceiver.decode()) /* * Your code here * For all users of the FastLed library, use this code for strip.show() to improve receiving performance (which is still not 100%): * if (IrReceiver.isIdle()) { * strip.show(); * } */ } |
PROYECTO RECOMENDADO