From 750bba800e4993e37166614c0feb99259453f4a7 Mon Sep 17 00:00:00 2001 From: Adson Breno <101665691+AdsonBreno@users.noreply.github.com> Date: Mon, 30 Oct 2023 17:51:14 -0300 Subject: [PATCH 01/14] ESP32.ino ESP + MQTT. In this code we can generate a pulse virtually, using a MQTT broker, we can also check the state of a magnetic sensor and monitor it through another path on the client MQTT. The pulse will be used to open a lock, and the sensor to check the state of a door, but it's possible to change according to the specific use. --- ESP32.ino | 188 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 188 insertions(+) create mode 100644 ESP32.ino diff --git a/ESP32.ino b/ESP32.ino new file mode 100644 index 0000000..378166a --- /dev/null +++ b/ESP32.ino @@ -0,0 +1,188 @@ +#include +#include +#include + +//Digital Inputs +#define sPin 22 //Sensor +#define aPin 4 //Analogic +#define magPin 21 //Magnetic + +//Digital Outputs +#define pulsePin 15 +#define lockPin 2 + +//ID MQTT +#define pubMag "MAGS" +#define subLock "DOOR" +#define TOPIC_PUBLISH "HALLWAY" +#define TOPIC_SUBSCRIBE "LOCK" + +WiFiClient wifiClient; +PubSubClient MQTT(wifiClient); +PubSubClient MQTT2(wifiClient); + +//Consts +const char* ssid = "LIEC_119"; +const char* pass = "********"; +const char* broker = "public.mqtthq.com"; +int port = 1883; +int state, magnetic; + +void connectWiFi(); +void connectMQTT(); +void keepConnections(); +void receivePacket(char* topic, byte* payload, unsigned int length); + +void setup() { + Serial.begin(9600); + pinMode(pulsePin, OUTPUT); + pinMode(magPin, INPUT_PULLUP); + digitalWrite(lockPin, OUTPUT); + + connectWiFi(); + + MQTT.setServer(broker, port); + MQTT2.setServer(broker, port); + MQTT2.setCallback(receivePacket); +} + +void connectWiFi(){ + Serial.println("Connecting to"); + Serial.print(ssid); + Serial.println("..."); + + WiFi.begin(ssid, pass); + + Serial.print("\nConnecting to "); + Serial.print(ssid); + Serial.print("."); + + while(WiFi.status() != WL_CONNECTED){ + delay(500); + Serial.print("..."); + } + if (WiFi.status() == WL_CONNECTED){ + Serial.print("\nConnected to "); + Serial.print(WiFi.localIP()); + return; + } + +} +void connectMQTT(){ + if (MQTT.connected()){ + return; + } + while (!MQTT.connected()){ + Serial.print("\nConnecting to "); + Serial.print(broker); + if (MQTT.connect(pubMag)){ + Serial.print("\nConnected to Broker for pubMag."); + magnetic = digitalRead(magPin); + if (magnetic == HIGH){ + MQTT.publish(TOPIC_PUBLISH, "1"); + Serial.print("\nPorta Aberta"); + delay(3000); + + } else if (magnetic == LOW) { + MQTT.publish(TOPIC_PUBLISH, "0"); + Serial.print("\nPorta Fechada"); + delay(3000); + } + break; + } + else if(!MQTT.connected()) { + Serial.print("\nCould not connect to pubMag. New attempt in 3 seconds."); + delay(3000); + } + } +} +void connectMQTT2(){ + if (MQTT2.connected()){ + return; + } + while (!MQTT2.connected()){ + Serial.print("\nConnecting to "); + Serial.print(broker); + if (MQTT2.connect(subLock)){ + Serial.print("\nConnected to Broker for subLock."); + MQTT2.subscribe(TOPIC_SUBSCRIBE); + if (MQTT.connected()){ + magnetic = digitalRead(magPin); + if (magnetic == HIGH){ + MQTT.publish(TOPIC_PUBLISH, "1"); + Serial.print("\nPorta Aberta"); + delay(3000); + + } else if (magnetic == LOW) { + MQTT.publish(TOPIC_PUBLISH, "0"); + Serial.print("\nPorta Fechada"); + delay(3000); + } + } + if (MQTT2.connected()){ + break; + } + } + else if(!MQTT2.connected()) { + Serial.print("\nCould not connect to sublock. New attempt in 3 seconds."); + delay(3000); + } + } +} +void pulse(){ + digitalWrite(pulsePin, HIGH); + state = HIGH; + delay(500); + if (state == HIGH){ + digitalWrite(pulsePin, LOW); + state = HIGH; + delay(3000); + } +} + +void keepConnections(){ + if(!MQTT.connected()){ + connectMQTT(); + } + if(!MQTT2.connected()){ + connectMQTT2(); + } + if(WiFi.status() != WL_CONNECTED){ + connectWiFi(); + } +} +void receivePacket(char* topic, byte* payload, unsigned int length){ + String msg; + + for(int i = 0; i < length; i++){ + char c = (char)payload[i]; + msg += c; + } + if (msg == "1"){ + pulse(); + Serial.print("\nMessage Received '1'"); + + } +} + +void magSensor(){ + magnetic = digitalRead(magPin); + + if (magnetic == HIGH){ + MQTT.publish(TOPIC_PUBLISH, "1"); + Serial.print("\nPorta Aberta"); + delay(3000); + + } else if (magnetic == LOW) { + MQTT.publish(TOPIC_PUBLISH, "0"); + Serial.print("\nPorta Fechada"); + delay(3000); + } +} + +void loop() { + magSensor(); + keepConnections(); + MQTT.loop(); + MQTT2.loop(); +} From f0c5fa15b2df7c12a67c4f90947baea360e28fc3 Mon Sep 17 00:00:00 2001 From: Adson Breno <101665691+AdsonBreno@users.noreply.github.com> Date: Mon, 30 Oct 2023 17:53:28 -0300 Subject: [PATCH 02/14] Delete HelloWorld directory --- HelloWorld/HelloWorld.ino | 16 ---------------- 1 file changed, 16 deletions(-) delete mode 100644 HelloWorld/HelloWorld.ino diff --git a/HelloWorld/HelloWorld.ino b/HelloWorld/HelloWorld.ino deleted file mode 100644 index 880d62b..0000000 --- a/HelloWorld/HelloWorld.ino +++ /dev/null @@ -1,16 +0,0 @@ -#include - -LiquidCrystal plate(2,3,4,6,7,8,9,10,11,12,13); - -void setup() { - // put your setup code here, to run once: - plate.begin(16,2); - plate.print("Hello World!"); - - -} - -void loop() { - // put your main code here, to run repeatedly: - -} From 5d2c0880bdb0982883778e2a166a0ebb7522daa8 Mon Sep 17 00:00:00 2001 From: Adson Breno <101665691+AdsonBreno@users.noreply.github.com> Date: Mon, 30 Oct 2023 17:53:47 -0300 Subject: [PATCH 03/14] Delete RGBLed directory --- RGBLed/RGBLed.ino | 38 -------------------------------------- 1 file changed, 38 deletions(-) delete mode 100644 RGBLed/RGBLed.ino diff --git a/RGBLed/RGBLed.ino b/RGBLed/RGBLed.ino deleted file mode 100644 index fd43a15..0000000 --- a/RGBLed/RGBLed.ino +++ /dev/null @@ -1,38 +0,0 @@ -#define Red 13 -#define Green 12 -#define BLUE 11 - -int red = 255; -int green = 255; -int blue = 255; -int red2 = 55; -int green2 = 55; -int blue2 = 55; -void setup() { - // put your setup code here, to run once: - pinMode(Red, OUTPUT); - pinMode(Green, OUTPUT); - pinMode(BLUE, OUTPUT); - -} - -void loop() { - // put your main code here, to run repeatedly: - analogWrite(BLUE, blue2); - delay(500); - analogWrite(BLUE, 0); - delay(500); - analogWrite(Red, red2); - delay(500); - analogWrite(Red, 0); - delay(500); - analogWrite(Green, green2); - delay(500); - analogWrite(Green, 0); - delay(500); - analogWrite(Red, red); - delay(500); - analogWrite(Green, green); - delay(500); - analogWrite(BLUE, blue); -} From 0b1ad14ef4db0a8ecaab20a6d7d576d7c153e637 Mon Sep 17 00:00:00 2001 From: Adson Breno <101665691+AdsonBreno@users.noreply.github.com> Date: Mon, 30 Oct 2023 22:36:30 -0300 Subject: [PATCH 04/14] --- libraries/LiquidCrystal/README.adoc | 25 ------------------------- 1 file changed, 25 deletions(-) diff --git a/libraries/LiquidCrystal/README.adoc b/libraries/LiquidCrystal/README.adoc index 7ec3219..e69de29 100644 --- a/libraries/LiquidCrystal/README.adoc +++ b/libraries/LiquidCrystal/README.adoc @@ -1,25 +0,0 @@ -= Liquid Crystal Library for Arduino = - -This library allows an Arduino board to control LiquidCrystal displays (LCDs) based on the Hitachi HD44780 (or a compatible) chipset, which is found on most text-based LCDs. - -For more information about this library please visit us at -http://www.arduino.cc/en/Reference/LiquidCrystal - -== License == - -Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. -Copyright (c) 2010 Arduino LLC. All right reserved. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA From 9670245f85dffd2f55e4bb1f541d5c88ca7a1474 Mon Sep 17 00:00:00 2001 From: Adson Breno <101665691+AdsonBreno@users.noreply.github.com> Date: Thu, 23 Nov 2023 18:49:28 -0300 Subject: [PATCH 05/14] RFID.cpp --- RFID.cpp | 252 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 252 insertions(+) create mode 100644 RFID.cpp diff --git a/RFID.cpp b/RFID.cpp new file mode 100644 index 0000000..0cad7ed --- /dev/null +++ b/RFID.cpp @@ -0,0 +1,252 @@ +//https://mundoprojetado.com.br/modulo-rfid-rc522/ + +#include +#include +#include +#include +#include +#include + +// Pino para colocar no modo "power-down" +// Não estamos utilizando no circuito proposto +#define PINO_RST 15 +// Pino SS (no módulo está escrito SDA neste pino) +#define PINO_SS 5 + +#define timenegado 300 +#define timeacesso 1000 + +#define EEPROM_SIZE 512 //Define o tamanho da EEPROM (1 - 512) + +#define Door "DOOR" //ID para envio das informações sobre o estado da porta +#define RFID "RFID" +#define TOPIC_PUBLISH "HALLWAY" +#define TOPIC_SUBSCRIBE "RFID" + +WiFiClient wifiClient; +PubSubClient MQTT(wifiClient); +PubSubClient MQTT2(wifiClient); + +//Consts +const char* ssid = "INTELBRAS"; +const char* pass = "marcia12345"; +const char* broker = "public.mqtthq.com"; //Teste + +// UID da tag responsável por liberar o acesso +uint8_t uid_tag_desejada[4] = {0x0F, 0xD8, 0xC8, 0x43}; + +int cont = 0; +int liberado = 0; +int reactRFID = 5; +// Instância do módulo +MFRC522 mfrc522(PINO_SS, PINO_RST); + +void receivePacket(char* topic, byte* payload, unsigned int length); + +//Operações RFID +void rfid(){ + if(reactRFID == 0){ + delay(5000); + if (mfrc522.PICC_IsNewCardPresent()){ + Serial.println(" Tag identified "); + Serial.println ("Writing the new tag on the system..."); + + for (int i = 0; i < 4; i++){ + // Printa o byte atual + Serial.print([i] < 0x10 ? " 0" : " "); + Serial.print(mfrc522.uid.uidByte[i], HEX); + EEPROM.begin(EEPROM_SIZE); //inicia a memória EEPROM + EEPROM.write(cont, mfrc522.uid.uidByte[i]); + cont++; + + } + } + } + if(reactRFID == 1){ + for (int i = 0, i < 4, cont--){ + mfrc522.uid.uidByte[cont] + + } +} +void eeprom(){ + + +} +void setup(){ + // Gravando Cartão na memoria EEPROM + + EEPROM.begin(EEPROM_SIZE); //inicia a memória EEPROM + EEPROM.write(0, 0x0F); + EEPROM.commit(); + EEPROM.write(1, 0xD8); + EEPROM.commit(); + cont ++; + EEPROM.write(2, 0xC8); + EEPROM.commit(); + cont ++; + EEPROM.write(3, 0x43); + EEPROM.commit(); + cont ++; + + pinMode(27,OUTPUT); + pinMode(32,OUTPUT); // PINO BUZZER (+ NO 5V E GND NO PINO 13. LOGICA INVERTIDA.) + digitalWrite(13,LOW); + + Serial.begin(9600); + Serial.println("...Iniciando Sistema"); + + MQTT.setServer(broker, port); + MQTT2.setServer(broker, port); + MQTT2.setCallback(receivePacket); + + // Inicia a comunicação SPI + SPI.begin(); + + // Inicia o módulo + mfrc522.PCD_Init(); + + Serial.print(EEPROM.read(0), HEX); + Serial.print(EEPROM.read(1), HEX); + Serial.print(EEPROM.read(2), HEX); + Serial.print(EEPROM.read(3), HEX); + Serial.println(); + Serial.println("Aguardando tag certa para abrir a porta..."); +} + +void connectWiFi(){ + Serial.println("Connecting to"); + Serial.print(ssid); + Serial.println("..."); + + WiFi.begin(ssid, pass); + + while(WiFi.status() != WL_CONNECTED){ + delay(500); + Serial.print("..."); + } + if (WiFi.status() == WL_CONNECTED){ + Serial.print("\nConnected at "); + Serial.print(WiFi.localIP()); + return; + } + +} +void connectMQTT(){ + if (MQTT.connected() and MQTT2.connected()){ + return; + } + while (!MQTT.connected()){ + Serial.print("\nConnecting to MQTT Broker "); + Serial.print(broker); + if (MQTT.connect(pubMag)){ + Serial.print("\nConnected to Broker for Door."); + } + else if (MQTT2.connect(RFID)){ + Serial.print("\nConnected to Broker for RFID."); + MQTT2.subscribe(TOPIC_SUBSCRIBE); + if (MQTT.connected() and MQTT2.connected()){ + return; + } + } + else if (!MQTT.connected() and !MQTT2.connected()){ + Serial.print("\nCould not connect to broker. New attempt in 5 seconds."); + delay(5000); + } + } +} +void keepConnections(){ + if(!MQTT.connected()){ + connectMQTT(); + } + if(WiFi.status() != WL_CONNECTED){ + connectWiFi(); + } +} +void receivePacket(char* topic, byte* payload, unsigned int length){ + String msg; + + for(int i = 0; i < length; i++){ + char c = (char)payload[i]; + msg += c; + } + if (msg == "0"){ + reactRFID = 0; + delay(500); + } + if (msg == "1"){ + reactRFID = 1; + Serial.print("Erasing Selected Card"); + delay(500); + } +} + +void loop() +{ + // Verifica se existe um cartão presente para leitura + if (mfrc522.PICC_IsNewCardPresent()){ + // Se sim, começa a ler o cartão + if (mfrc522.PICC_ReadCardSerial()){ + uint8_t liberado = 1; + + // Verifica os 4 bytes da UID + Serial.print("Tag identificada: "); + for (byte j = 0; j < 4; j=j+4){ + + for (byte i = 0; i < 4; i++) + { + // Printa o byte atual + Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "); + Serial.print(mfrc522.uid.uidByte[i], HEX); + + // Se o byte for diferente da tag esperada, não libera o acesso + if(EEPROM.read(i) != mfrc522.uid.uidByte[i]) + { + liberado = 0; + } + } + Serial.println(""); + } + if(liberado) + { + delay(50); + digitalWrite(13,HIGH); + Serial.println("Acesso liberado!"); + delay(timeacesso); + digitalWrite(13,LOW); + delay(50); + // Executa outras ações, como abrir uma porta + } + else + { + delay(50); + digitalWrite(13,LOW); + delay(timenegado); + digitalWrite(13,HIGH); + delay(timenegado); + digitalWrite(13,LOW); + delay(timenegado); + digitalWrite(13,HIGH); + delay(timenegado); + digitalWrite(13,LOW); + delay(timenegado); + digitalWrite(13,HIGH); + delay(timenegado); + digitalWrite(13,LOW); + delay(timenegado); + digitalWrite(13,HIGH); + delay(timenegado); + digitalWrite(13,LOW); + delay(timenegado); + digitalWrite(13,HIGH); + delay(timenegado); + digitalWrite(13,LOW); + Serial.println("Acesso negado!"); + delay(50); + } + } + + // Delay para não ficar lendo rapidamente + delay(1000); + Serial.println("Aguardando tag certa para abrir a porta..."); + } +} From ceb718e7f8770a6b05c4eaa2c6c94aa2498a3d6c Mon Sep 17 00:00:00 2001 From: Adson Breno <101665691+AdsonBreno@users.noreply.github.com> Date: Fri, 24 Nov 2023 17:10:47 -0300 Subject: [PATCH 06/14] RFID.cpp --- RFID.cpp | 263 +++++++++++++++++++++++++------------------------------ 1 file changed, 119 insertions(+), 144 deletions(-) diff --git a/RFID.cpp b/RFID.cpp index 0cad7ed..1a3f6ba 100644 --- a/RFID.cpp +++ b/RFID.cpp @@ -1,48 +1,51 @@ //https://mundoprojetado.com.br/modulo-rfid-rc522/ - #include -#include -#include #include -#include +#include #include +#include +#include // Pino para colocar no modo "power-down" // Não estamos utilizando no circuito proposto -#define PINO_RST 15 +#define PINO_RST 15 // Pino SS (no módulo está escrito SDA neste pino) -#define PINO_SS 5 - +#define PINO_SS 5 +#define pinBuzz 32 +#define pinGND 13 #define timenegado 300 #define timeacesso 1000 - #define EEPROM_SIZE 512 //Define o tamanho da EEPROM (1 - 512) -#define Door "DOOR" //ID para envio das informações sobre o estado da porta -#define RFID "RFID" -#define TOPIC_PUBLISH "HALLWAY" +#define ID_PUBLISH "DOOR" +#define ID_SUBSCRIBE "RFID" + +#define TOPIC_PUBLISH "DOOR" #define TOPIC_SUBSCRIBE "RFID" +const char* ssid = "LIEC_119"; +const char* pass = "0987ABCDEF"; +const char* broker = "public.mqtthq.com"; //Test +int port = 1883; + +//Global constants +int cont = 0; +int liberado = 0; +int reactRFID = 0;//5; + WiFiClient wifiClient; PubSubClient MQTT(wifiClient); PubSubClient MQTT2(wifiClient); -//Consts -const char* ssid = "INTELBRAS"; -const char* pass = "marcia12345"; -const char* broker = "public.mqtthq.com"; //Teste +void receivePacket(char* topic, byte* payload, unsigned int length); // UID da tag responsável por liberar o acesso -uint8_t uid_tag_desejada[4] = {0x0F, 0xD8, 0xC8, 0x43}; +uint8_t uid_tag_desejada[3] = {0x0F, 0xD8, 0xC8, 0x43}; +uint8_t uid_tag_nova[3] = mfrc522.uid.uidByte; -int cont = 0; -int liberado = 0; -int reactRFID = 5; // Instância do módulo MFRC522 mfrc522(PINO_SS, PINO_RST); -void receivePacket(char* topic, byte* payload, unsigned int length); - //Operações RFID void rfid(){ if(reactRFID == 0){ @@ -55,8 +58,8 @@ void rfid(){ // Printa o byte atual Serial.print([i] < 0x10 ? " 0" : " "); Serial.print(mfrc522.uid.uidByte[i], HEX); - EEPROM.begin(EEPROM_SIZE); //inicia a memória EEPROM EEPROM.write(cont, mfrc522.uid.uidByte[i]); + EEPROM.commit(); cont++; } @@ -64,17 +67,13 @@ void rfid(){ } if(reactRFID == 1){ for (int i = 0, i < 4, cont--){ - mfrc522.uid.uidByte[cont] - + EEPROM.write(cont, 00); } -} -void eeprom(){ - - + } } void setup(){ - // Gravando Cartão na memoria EEPROM + // Gravando Cartão na memoria EEPROM EEPROM.begin(EEPROM_SIZE); //inicia a memória EEPROM EEPROM.write(0, 0x0F); EEPROM.commit(); @@ -88,165 +87,141 @@ void setup(){ EEPROM.commit(); cont ++; - pinMode(27,OUTPUT); - pinMode(32,OUTPUT); // PINO BUZZER (+ NO 5V E GND NO PINO 13. LOGICA INVERTIDA.) - digitalWrite(13,LOW); + pinMode(pinBuzz,OUTPUT); // PINO BUZZER (+ NO 5V E GND NO PINO 13. LOGICA INVERTIDA.) + digitalWrite(pinGND,LOW); + // Inicia a comunicação serial (monitor serial) Serial.begin(9600); - Serial.println("...Iniciando Sistema"); - - MQTT.setServer(broker, port); - MQTT2.setServer(broker, port); - MQTT2.setCallback(receivePacket); + Serial.println(". . .Booting System "); // Inicia a comunicação SPI SPI.begin(); // Inicia o módulo mfrc522.PCD_Init(); - - Serial.print(EEPROM.read(0), HEX); - Serial.print(EEPROM.read(1), HEX); - Serial.print(EEPROM.read(2), HEX); - Serial.print(EEPROM.read(3), HEX); + for(int i = 0, i < 4, i++){ + Serial.print(EEPROM.read(i), HEX); + } Serial.println(); - Serial.println("Aguardando tag certa para abrir a porta..."); -} -void connectWiFi(){ - Serial.println("Connecting to"); - Serial.print(ssid); - Serial.println("..."); + Serial.println("Aguardando tag correta para abrir a porta..."); - WiFi.begin(ssid, pass); + MQTT.setServer(broker, port); + MQTT2.setServer(broker, port); + MQTT2.setCallback(receivePacket); +} +void receivePacket(char* topic, byte* payload, unsigned int length){ + String msg; - while(WiFi.status() != WL_CONNECTED){ - delay(500); - Serial.print("..."); + for(int i = 0; i < length; i++){ + char c = (char)payload[i]; + msg += c; } - if (WiFi.status() == WL_CONNECTED){ - Serial.print("\nConnected at "); - Serial.print(WiFi.localIP()); - return; + if (msg == "0"){ + Serial.print("\nMessage Received '0'"); + for (e = 0, e < 4, e++){ + EEPROM.write(e, uid_tag_nova[e]) + EEPROM.commit(); + } + } +} +void buzz(){ + delay(50); + for(int b = 0, b < 6, b++){ + digitalWrite(pinBuzz, LOW); + delay(timeNegado); + digitalWrite(pinBuzz, HIGH); + delay(timeNegado); } - + Serial.println("Acesso negado!"); + delay(50); } -void connectMQTT(){ - if (MQTT.connected() and MQTT2.connected()){ + +void connectMQTT2(){ + if (MQTT2.connected()){ return; } - while (!MQTT.connected()){ - Serial.print("\nConnecting to MQTT Broker "); + while (!MQTT2.connected()){ + Serial.print("\nConnecting to "); Serial.print(broker); - if (MQTT.connect(pubMag)){ - Serial.print("\nConnected to Broker for Door."); - } - else if (MQTT2.connect(RFID)){ - Serial.print("\nConnected to Broker for RFID."); + if (MQTT2.connect(subLock)){ + Serial.print("\nConnected to Broker for subLock."); MQTT2.subscribe(TOPIC_SUBSCRIBE); - if (MQTT.connected() and MQTT2.connected()){ - return; + if (MQTT.connected()){ + magnetic = digitalRead(magPin); + if (liberado == 3){ + MQTT.publish(TOPIC_PUBLISH, "1"); + Serial.print("\nAccess Granted"); + + } else if (liberado == 0) { + MQTT.publish(TOPIC_PUBLISH, "0"); + Serial.print("\nAccess Denied"); + delay(3000); + } + } + if (MQTT2.connected()){ + break; } } - else if (!MQTT.connected() and !MQTT2.connected()){ - Serial.print("\nCould not connect to broker. New attempt in 5 seconds."); - delay(5000); - } + else if(!MQTT2.connected()) { + Serial.print("\nCould not connect to sublock. New attempt in 3 seconds."); + delay(3000); + } } } + void keepConnections(){ if(!MQTT.connected()){ connectMQTT(); } + if(!MQTT2.connected()){ + connectMQTT2(); + } if(WiFi.status() != WL_CONNECTED){ connectWiFi(); } } -void receivePacket(char* topic, byte* payload, unsigned int length){ - String msg; - for(int i = 0; i < length; i++){ - char c = (char)payload[i]; - msg += c; - } - if (msg == "0"){ - reactRFID = 0; - delay(500); - } - if (msg == "1"){ - reactRFID = 1; - Serial.print("Erasing Selected Card"); - delay(500); - } -} - -void loop() -{ +void loop(){ // Verifica se existe um cartão presente para leitura if (mfrc522.PICC_IsNewCardPresent()){ - // Se sim, começa a ler o cartão - if (mfrc522.PICC_ReadCardSerial()){ - uint8_t liberado = 1; - - // Verifica os 4 bytes da UID - Serial.print("Tag identificada: "); - for (byte j = 0; j < 4; j=j+4){ - for (byte i = 0; i < 4; i++) - { - // Printa o byte atual - Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "); - Serial.print(mfrc522.uid.uidByte[i], HEX); - - // Se o byte for diferente da tag esperada, não libera o acesso - if(EEPROM.read(i) != mfrc522.uid.uidByte[i]) - { - liberado = 0; - } - } - Serial.println(""); + int liberado = 0; + + if (mfrc522.PICC_ReadCardSerial()){ // Verifica os 4 bytes da UID + Serial.print("Tag identificada: "); + for (byte j = 0; j < 3; j=j+3){ + for (byte i = 0; i < 3; i++){ + // Printa o byte atual + Serial.print((mfrc522.uid.uidByte[i] < 0x10) ? " 0" : " "); + Serial.print(mfrc522.uid.uidByte[i], HEX); + //Inverter + somador + if(EEPROM.read(i) != mfrc522.uid.uidByte[i]){ + liberado = 0; + } + } } - if(liberado) - { + for(i = 0, i < 4, i++){ + if(uid_tag_desejada[i] == mfrc522.uid.uidByte[i]){ + liberado++; + } + } + if(liberado == 3) { delay(50); - digitalWrite(13,HIGH); + digitalWrite(pinBuzz,HIGH); Serial.println("Acesso liberado!"); delay(timeacesso); - digitalWrite(13,LOW); + digitalWrite(pinBuzz,LOW); delay(50); // Executa outras ações, como abrir uma porta + // Send packet to broker, so it'll open the door } - else - { - delay(50); - digitalWrite(13,LOW); - delay(timenegado); - digitalWrite(13,HIGH); - delay(timenegado); - digitalWrite(13,LOW); - delay(timenegado); - digitalWrite(13,HIGH); - delay(timenegado); - digitalWrite(13,LOW); - delay(timenegado); - digitalWrite(13,HIGH); - delay(timenegado); - digitalWrite(13,LOW); - delay(timenegado); - digitalWrite(13,HIGH); - delay(timenegado); - digitalWrite(13,LOW); - delay(timenegado); - digitalWrite(13,HIGH); - delay(timenegado); - digitalWrite(13,LOW); - Serial.println("Acesso negado!"); - delay(50); + else { + buzz(); } } - // Delay para não ficar lendo rapidamente - delay(1000); - Serial.println("Aguardando tag certa para abrir a porta..."); + delay(2000); + Serial.println("Aguardando tag correta para abrir a porta..."); } } From 7cb05e6cd354aeb96ddfa93fc028ba9b2be3bb47 Mon Sep 17 00:00:00 2001 From: Adson Breno <101665691+AdsonBreno@users.noreply.github.com> Date: Fri, 24 Nov 2023 17:49:14 -0300 Subject: [PATCH 07/14] RFID.cpp --- RFID.cpp | 140 +++++++++++++++++++++++++++++++++---------------------- 1 file changed, 85 insertions(+), 55 deletions(-) diff --git a/RFID.cpp b/RFID.cpp index 1a3f6ba..fe23c31 100644 --- a/RFID.cpp +++ b/RFID.cpp @@ -54,25 +54,29 @@ void rfid(){ Serial.println(" Tag identified "); Serial.println ("Writing the new tag on the system..."); - for (int i = 0; i < 4; i++){ - // Printa o byte atual - Serial.print([i] < 0x10 ? " 0" : " "); - Serial.print(mfrc522.uid.uidByte[i], HEX); - EEPROM.write(cont, mfrc522.uid.uidByte[i]); - EEPROM.commit(); - cont++; - - } + for (int i = 0; i < 4; i++){ + // Printa o byte atual + Serial.print([i] < 0x10 ? " 0" : " "); + Serial.print(mfrc522.uid.uidByte[i], HEX); + EEPROM.write((cont+1), mfrc522.uid.uidByte[i]); + EEPROM.commit(); + cont++; + } } } if(reactRFID == 1){ - for (int i = 0, i < 4, cont--){ + for (int i = 0, i < 4, i++){ EEPROM.write(cont, 00); + cont--; } } } -void setup(){ +void setup(){ + // Inicia a comunicação serial (monitor serial) + Serial.begin(9600); + Serial.println(". . .Booting System "); + // Gravando Cartão na memoria EEPROM EEPROM.begin(EEPROM_SIZE); //inicia a memória EEPROM EEPROM.write(0, 0x0F); @@ -89,10 +93,6 @@ void setup(){ pinMode(pinBuzz,OUTPUT); // PINO BUZZER (+ NO 5V E GND NO PINO 13. LOGICA INVERTIDA.) digitalWrite(pinGND,LOW); - - // Inicia a comunicação serial (monitor serial) - Serial.begin(9600); - Serial.println(". . .Booting System "); // Inicia a comunicação SPI SPI.begin(); @@ -125,16 +125,69 @@ void receivePacket(char* topic, byte* payload, unsigned int length){ } } } + void buzz(){ delay(50); - for(int b = 0, b < 6, b++){ - digitalWrite(pinBuzz, LOW); - delay(timeNegado); - digitalWrite(pinBuzz, HIGH); - delay(timeNegado); + if(liberado == 0){ + MQTT.publish(TOPIC_PUBLISH, "0"); + Serial.print("\nAccess Denied"); + for(b = 0, b < 6, b++){ + digitalWrite(pinBuzz, LOW); + delay(timeNegado); + digitalWrite(pinBuzz, HIGH); + delay(timeNegado); + } + } else if(liberado == 3){ + delay(50); + MQTT.publish(TOPIC_PUBLISH, "1"); + Serial.print("\nAccess Granted"); + + digitalWrite(pinBuzz,HIGH); + delay(timeacesso); + digitalWrite(pinBuzz,LOW); + delay(50); + } + } +} +void connectWiFi(){ + Serial.println("Connecting to"); + Serial.print(ssid); + Serial.println("..."); + + WiFi.begin(ssid, pass); + + Serial.print("\nConnecting to "); + Serial.print(ssid); + Serial.print("."); + + while(WiFi.status() != WL_CONNECTED){ + delay(500); + Serial.print("..."); + } + if (WiFi.status() == WL_CONNECTED){ + Serial.print("\nConnected to "); + Serial.print(WiFi.localIP()); + return; + } +} + +void connectMQTT(){ + if (MQTT.connected()){ + return; + } + while (!MQTT.connected()){ + Serial.print("\nConnecting to "); + Serial.print(broker); + if (MQTT.connect(ID_PUBLISH)){ + Serial.print("\nConnected to Broker."); + } + break; + } + else if(!MQTT.connected()) { + Serial.print("\nCould not connect. New attempt in 3 seconds."); + delay(3000); + } } - Serial.println("Acesso negado!"); - delay(50); } void connectMQTT2(){ @@ -147,18 +200,7 @@ void connectMQTT2(){ if (MQTT2.connect(subLock)){ Serial.print("\nConnected to Broker for subLock."); MQTT2.subscribe(TOPIC_SUBSCRIBE); - if (MQTT.connected()){ - magnetic = digitalRead(magPin); - if (liberado == 3){ - MQTT.publish(TOPIC_PUBLISH, "1"); - Serial.print("\nAccess Granted"); - - } else if (liberado == 0) { - MQTT.publish(TOPIC_PUBLISH, "0"); - Serial.print("\nAccess Denied"); - delay(3000); - } - } + if (MQTT2.connected()){ break; } @@ -184,11 +226,8 @@ void keepConnections(){ void loop(){ // Verifica se existe um cartão presente para leitura - if (mfrc522.PICC_IsNewCardPresent()){ - - int liberado = 0; - - if (mfrc522.PICC_ReadCardSerial()){ // Verifica os 4 bytes da UID + if (mfrc522.PICC_IsNewCardPresent()){ // Check if there is a card on the sensor + if (mfrc522.PICC_ReadCardSerial()){ // CHeck UID 4 bytes Serial.print("Tag identificada: "); for (byte j = 0; j < 3; j=j+3){ for (byte i = 0; i < 3; i++){ @@ -201,23 +240,14 @@ void loop(){ } } } - for(i = 0, i < 4, i++){ - if(uid_tag_desejada[i] == mfrc522.uid.uidByte[i]){ - liberado++; - } - } - if(liberado == 3) { - delay(50); - digitalWrite(pinBuzz,HIGH); - Serial.println("Acesso liberado!"); - delay(timeacesso); - digitalWrite(pinBuzz,LOW); - delay(50); - // Executa outras ações, como abrir uma porta - // Send packet to broker, so it'll open the door + for(int j = 0, j < cont, j++){ + for(i = 0, i < 4, i++){ + if(EEPROM.read(i) == mfrc522.uid.uidByte[i]){ + liberado++; + } } - else { - buzz(); + } + buzz(); } } // Delay para não ficar lendo rapidamente From 5d3cf08b32778b67a23e43162ac0cd502379e27c Mon Sep 17 00:00:00 2001 From: Adson Breno <101665691+AdsonBreno@users.noreply.github.com> Date: Thu, 7 Dec 2023 02:00:17 -0300 Subject: [PATCH 08/14] RFID.cpp --- RFID.cpp | 320 ++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 199 insertions(+), 121 deletions(-) diff --git a/RFID.cpp b/RFID.cpp index fe23c31..ed53928 100644 --- a/RFID.cpp +++ b/RFID.cpp @@ -1,128 +1,153 @@ -//https://mundoprojetado.com.br/modulo-rfid-rc522/ #include #include -#include +//#include +//#include +#include //https://mundoprojetado.com.br/modulo-rfid-rc522/ #include #include #include -// Pino para colocar no modo "power-down" -// Não estamos utilizando no circuito proposto -#define PINO_RST 15 -// Pino SS (no módulo está escrito SDA neste pino) -#define PINO_SS 5 -#define pinBuzz 32 -#define pinGND 13 -#define timenegado 300 -#define timeacesso 1000 +#define PINO_RST 15 //SDA no módulo RFID +#define PINO_SS 5 +#define pinBuzz 32 +#define pinGND 13 + +#define timeNegado 300 +#define timeAcesso 750 + #define EEPROM_SIZE 512 //Define o tamanho da EEPROM (1 - 512) +#define NUM_CARTOES 10 // Defina o número máximo de cartões -#define ID_PUBLISH "DOOR" -#define ID_SUBSCRIBE "RFID" +#define ID_PUBLISH "EstadoPorta" +#define ID_SUBSCRIBE "UnidadeCard" +#define ID_SUBSCRIBE2 "AcaoMemoria" -#define TOPIC_PUBLISH "DOOR" -#define TOPIC_SUBSCRIBE "RFID" +#define TOPIC_PUBLISH "EstadoPorta" +#define TOPIC_SUBSCRIBE "CARD" +#define TOPIC_SUBSCRIBE2 "EEPROM" const char* ssid = "LIEC_119"; -const char* pass = "0987ABCDEF"; +const char* pass = "********"; const char* broker = "public.mqtthq.com"; //Test int port = 1883; +//TaskHandle_t ConnectWiFi; + //Global constants -int cont = 0; +String idCard = ""; + +bool cartaoEncontrado = false; + int liberado = 0; -int reactRFID = 0;//5; +int act = 2; +int card = 10; //Por padrão o endereço usado é o último, para evitar que dados sejam perdidos +uint8_t uid_tag_nova[4]; + +//Conexões WiFiClient wifiClient; PubSubClient MQTT(wifiClient); -PubSubClient MQTT2(wifiClient); +//PubSubClient MQTT2(wifiClient); +PubSubClient MQTT3(wifiClient); +MFRC522 mfrc522(PINO_SS, PINO_RST); -void receivePacket(char* topic, byte* payload, unsigned int length); +// Matriz para armazenar os cartões +uint8_t cartoes[NUM_CARTOES][4]; -// UID da tag responsável por liberar o acesso -uint8_t uid_tag_desejada[3] = {0x0F, 0xD8, 0xC8, 0x43}; -uint8_t uid_tag_nova[3] = mfrc522.uid.uidByte; +//void receivePacket2(char* topic, byte* payload, unsigned int length); +void receivePacket3(char* topic, byte* payload, unsigned int length); -// Instância do módulo -MFRC522 mfrc522(PINO_SS, PINO_RST); +void setup() { + EEPROM.begin(EEPROM_SIZE); -//Operações RFID -void rfid(){ - if(reactRFID == 0){ - delay(5000); - if (mfrc522.PICC_IsNewCardPresent()){ - Serial.println(" Tag identified "); - Serial.println ("Writing the new tag on the system..."); - - for (int i = 0; i < 4; i++){ - // Printa o byte atual - Serial.print([i] < 0x10 ? " 0" : " "); - Serial.print(mfrc522.uid.uidByte[i], HEX); - EEPROM.write((cont+1), mfrc522.uid.uidByte[i]); - EEPROM.commit(); - cont++; - } - } - } - if(reactRFID == 1){ - for (int i = 0, i < 4, i++){ - EEPROM.write(cont, 00); - cont--; - } - } -} + pinMode(pinBuzz, OUTPUT); + digitalWrite(pinGND, LOW); + digitalWrite(pinBuzz, LOW); -void setup(){ - // Inicia a comunicação serial (monitor serial) Serial.begin(9600); + Serial.setDebugOutput(true); Serial.println(". . .Booting System "); - - // Gravando Cartão na memoria EEPROM - EEPROM.begin(EEPROM_SIZE); //inicia a memória EEPROM - EEPROM.write(0, 0x0F); - EEPROM.commit(); - EEPROM.write(1, 0xD8); - EEPROM.commit(); - cont ++; - EEPROM.write(2, 0xC8); - EEPROM.commit(); - cont ++; - EEPROM.write(3, 0x43); - EEPROM.commit(); - cont ++; - pinMode(pinBuzz,OUTPUT); // PINO BUZZER (+ NO 5V E GND NO PINO 13. LOGICA INVERTIDA.) - digitalWrite(pinGND,LOW); - - // Inicia a comunicação SPI SPI.begin(); - // Inicia o módulo mfrc522.PCD_Init(); - for(int i = 0, i < 4, i++){ - Serial.print(EEPROM.read(i), HEX); - } - Serial.println(); + + connectWiFi(); + MQTT.setServer(broker, port); + //MQTT2.setServer(broker, port); + MQTT3.setServer(broker, port); + + //MQTT2.setCallback(receivePacket2); //Pacote com o endereço do cartão + MQTT3.setCallback(receivePacket3); //Pactote com a ação para a memória - Serial.println("Aguardando tag correta para abrir a porta..."); + keepConnections(); - MQTT.setServer(broker, port); - MQTT2.setServer(broker, port); - MQTT2.setCallback(receivePacket); + Serial.println("\nAguardando tag correta para abrir a porta..."); +}/* +void receivePacket2(char* topic, byte* payload, unsigned int length){ + String msg; + + for(int i = 0; i < length; i++){ + char c = (char)payload[i]; + msg += c; + } + card = msg.toInt(); //Índice de escrita ou para apagar da memória } -void receivePacket(char* topic, byte* payload, unsigned int length){ +*/ +void receivePacket3(char* topic, byte* payload, unsigned int length){ String msg; for(int i = 0; i < length; i++){ char c = (char)payload[i]; msg += c; } - if (msg == "0"){ + if (msg == "0"){ //Comando para ESCREVER a Tag lida na memória Serial.print("\nMessage Received '0'"); - for (e = 0, e < 4, e++){ - EEPROM.write(e, uid_tag_nova[e]) - EEPROM.commit(); + eeprom(1, card, 0); //Escreve no endereço 'card' da matriz, pode SOBRESCREVER dados, cuidado! + } + if (msg == "1"){ //Comando para APAGAR a Tag selecionada da memória + Serial.print("\nMessage Received '1'"); + eeprom(0, card, 0); + } + if(msg == "2"){ //Comando para LER toda a memória + Serial.print("\nMessage Received '2"); + eeprom(2, 0, 1); //Act = Nada, Card = Indiferente, READ!! + } +} +void eeprom(int act, int card, bool read) { //Recebe uma Ação e um índice de Cartão + if(act == 1){ //Ação para escrever na memória + for (int i = 0; i < 4; i++) { + EEPROM.write(card * 4 + i, uid_tag_nova[i]); + Serial.println("Writing the new tag on the system..."); + } + act = 2; //Não faz nada + } else if(act == 0){ //Ação para apagar da memória + for (int i = 0; i < 4; i++) { + EEPROM.write(card * 4 + i, 0); + Serial.println("Erasing card "); + Serial.print(card+1); //0 é o endereço do cartão 1.. + Serial.print(" from the system..."); } + act = 2; //NOP + } + EEPROM.commit(); + Serial.println("Process complete"); + //Leitura de dados da EEPROM + if(read){ + Serial.println("Conteúdo da EEPROM:"); + + for (int c = 0; c < NUM_CARTOES; c++) { + Serial.print("Cartão "); + Serial.print(c+1); + Serial.print(": "); + + for (int i = 0; i < 4; i++) { + cartoes[c][i] = EEPROM.read(c * 4 + i); + Serial.print(cartoes[c][i], HEX); + Serial.print(" "); + } + } + Serial.println("\nFim da leitura da EEPROM"); } } @@ -131,23 +156,22 @@ void buzz(){ if(liberado == 0){ MQTT.publish(TOPIC_PUBLISH, "0"); Serial.print("\nAccess Denied"); - for(b = 0, b < 6, b++){ + for(int b = 0; b < 6; b++){ digitalWrite(pinBuzz, LOW); delay(timeNegado); digitalWrite(pinBuzz, HIGH); delay(timeNegado); } - } else if(liberado == 3){ + digitalWrite(pinBuzz, LOW); + } else if(liberado == 1){ delay(50); MQTT.publish(TOPIC_PUBLISH, "1"); Serial.print("\nAccess Granted"); - digitalWrite(pinBuzz,HIGH); - delay(timeacesso); + delay(timeAcesso); digitalWrite(pinBuzz,LOW); - delay(50); + delay(50); } - } } void connectWiFi(){ Serial.println("Connecting to"); @@ -183,13 +207,12 @@ void connectMQTT(){ } break; } - else if(!MQTT.connected()) { - Serial.print("\nCould not connect. New attempt in 3 seconds."); + if(!MQTT.connected()) { + Serial.print("\nCould not publish. New attempt in 3 seconds."); delay(3000); - } } } - +/* void connectMQTT2(){ if (MQTT2.connected()){ return; @@ -197,16 +220,37 @@ void connectMQTT2(){ while (!MQTT2.connected()){ Serial.print("\nConnecting to "); Serial.print(broker); - if (MQTT2.connect(subLock)){ - Serial.print("\nConnected to Broker for subLock."); + if (MQTT2.connect(ID_SUBSCRIBE)){ + Serial.print("\nConnected to Broker."); MQTT2.subscribe(TOPIC_SUBSCRIBE); if (MQTT2.connected()){ break; } + } else if(!MQTT2.connected()) { + Serial.print("\nCould not subscribe. New attempt in 3 seconds."); + delay(3000); } - else if(!MQTT2.connected()) { - Serial.print("\nCould not connect to sublock. New attempt in 3 seconds."); + } +}*/ + +void connectMQTT3(){ + if (MQTT3.connected()){ + return; + } + while (!MQTT3.connected()){ + Serial.print("\nConnecting to "); + Serial.print(broker); + if (MQTT3.connect(ID_SUBSCRIBE2)){ + Serial.print("\nConnected to Broker."); + MQTT3.subscribe(TOPIC_SUBSCRIBE2); + + if (MQTT3.connected()){ + break; + } + } + else if(!MQTT3.connected()){ + Serial.print("\nCould not subscribe. New attempt in 3 seconds."); delay(3000); } } @@ -215,43 +259,77 @@ void connectMQTT2(){ void keepConnections(){ if(!MQTT.connected()){ connectMQTT(); - } + }/* if(!MQTT2.connected()){ connectMQTT2(); + }*/ + if(!MQTT3.connected()){ + connectMQTT3(); } if(WiFi.status() != WL_CONNECTED){ connectWiFi(); } } -void loop(){ - // Verifica se existe um cartão presente para leitura - if (mfrc522.PICC_IsNewCardPresent()){ // Check if there is a card on the sensor - if (mfrc522.PICC_ReadCardSerial()){ // CHeck UID 4 bytes - Serial.print("Tag identificada: "); - for (byte j = 0; j < 3; j=j+3){ - for (byte i = 0; i < 3; i++){ - // Printa o byte atual - Serial.print((mfrc522.uid.uidByte[i] < 0x10) ? " 0" : " "); - Serial.print(mfrc522.uid.uidByte[i], HEX); - //Inverter + somador - if(EEPROM.read(i) != mfrc522.uid.uidByte[i]){ +void loop() { + // Verifica se existe um cartão presente para leitura, e faz a leitura do cartão + if (mfrc522.PICC_IsNewCardPresent()) { + if (mfrc522.PICC_ReadCardSerial()) { + Serial.println("\nTag identificada: "); + idCard = ""; // Limpa a string antes de cada leitura + memset(uid_tag_nova, 0, sizeof(uid_tag_nova));// Limpa a uid_tag_nova antes de armazenar novos valores + for (int i = 0; i < 4; i++) { + idCard += (mfrc522.uid.uidByte[i] < 0x10 ? "0" : " "); + idCard += String(mfrc522.uid.uidByte[i], HEX); + uid_tag_nova[i] = mfrc522.uid.uidByte[i]; + } + keepConnections(); + } + for (int c = 0; c < NUM_CARTOES; c++) { //Endereço do cartão na matrix de cartões + for (int i = 0; i < 4; i++) { + if (EEPROM.read(c * 4 + i) != uid_tag_nova[i]) { //Compara a tag lida com os valores da memória liberado = 0; + } else { + liberado = 1; + } } } - for(int j = 0, j < cont, j++){ - for(i = 0, i < 4, i++){ - if(EEPROM.read(i) == mfrc522.uid.uidByte[i]){ - liberado++; - } + Serial.print("UID Nova: "); + for (int i = 0; i < 4; i++) { + Serial.print(uid_tag_nova[i], HEX); + Serial.print(" "); } - } - buzz(); + + // Verifica se a UID está na lista de cartões + if (!cartaoEncontrado) { + for (int c = 0; c < NUM_CARTOES; c++) { + bool cartaoCorrespondente = true; + + for (int i = 0; i < 4; i++) { + if (uid_tag_nova[i] != cartoes[c][i]) { + cartaoCorrespondente = false; + break; + } + } + + if (cartaoCorrespondente) { + liberado = 1; + cartaoEncontrado = true; //O cartão já foi encontrado na memória + break; + } else { + liberado = 0; + } + } } + + buzz(); } + // Delay para não ficar lendo rapidamente - delay(2000); - Serial.println("Aguardando tag correta para abrir a porta..."); - } + delay(1000); + Serial.println("\nAguardando tag correta para abrir a porta..."); + MQTT.loop(); + //MQTT2.loop(); + MQTT3.loop(); } From 201d81f37563ce6fa1af8ee004061afdccd643db Mon Sep 17 00:00:00 2001 From: Adson Breno <101665691+AdsonBreno@users.noreply.github.com> Date: Thu, 7 Dec 2023 12:08:06 -0300 Subject: [PATCH 09/14] RFID short MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sem MQTT, EEPROM, Checagem, nem Relé --- RFID short | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 RFID short diff --git a/RFID short b/RFID short new file mode 100644 index 0000000..dd2cd34 --- /dev/null +++ b/RFID short @@ -0,0 +1,66 @@ +#include +#include //https://mundoprojetado.com.br/modulo-rfid-rc522/ +//#include +#include +#include + +#define PINO_RST 15 //SDA no módulo RFID +#define PINO_SS 5 + +#define pinRel 27 +#define pinBuzz 32 +#define pinGND 13 + +#define timeNegado 300 +#define timeAcesso 750 + + +#define timenegado 300 +#define timeacesso 1000 + +// Instância do módulo +MFRC522 mfrc522(PINO_SS, PINO_RST); + +void setup(){ + + pinMode(pinRel,OUTPUT); + pinMode(pinGND,OUTPUT); + pinMode(pinBuzz,OUTPUT); // PINO BUZZER (+ NO 5V E GND NO PINO 13. LOGICA INVERTIDA.) + + digitalWrite(pinGND,LOW); + + // Inicia a comunicação serial (monitor serial) + Serial.begin(9600); + Serial.println("...Iniciando Sistema"); + + // Inicia a comunicação SPI + SPI.begin(); + + // Inicia o módulo + mfrc522.PCD_Init(); + + Serial.println("Aguardando tag certa para abrir a porta..."); +} + +void loop(){ + // Verifica se existe um cartão presente para leitura + if (mfrc522.PICC_IsNewCardPresent()){ + // Se sim, começa a ler o cartão + if (mfrc522.PICC_ReadCardSerial()){ + // Verifica os 4 bytes da UID + Serial.print("Tag identificada: "); + for (byte j = 0; j < 4; j=j+4){ + for (byte i = 0; i < 4; i++){ + // Printa o byte atual + Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "); + Serial.print(mfrc522.uid.uidByte[i], HEX); + + } + Serial.println("\nEnviando ID para o Banco de Dados"); + // Delay para não ficar lendo rapidamente + delay(3000); + Serial.println("Aguardando tag certa para abrir a porta..."); + } + } + } +} From 0d89e8f948fbaa371579ef6e0b3528bc184684d8 Mon Sep 17 00:00:00 2001 From: Adson Breno <101665691+AdsonBreno@users.noreply.github.com> Date: Mon, 11 Dec 2023 17:46:55 -0300 Subject: [PATCH 10/14] RFIDServer.cpp --- RFIDServer.cpp | 127 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 RFIDServer.cpp diff --git a/RFIDServer.cpp b/RFIDServer.cpp new file mode 100644 index 0000000..832739e --- /dev/null +++ b/RFIDServer.cpp @@ -0,0 +1,127 @@ +#include +#include +#include //https://mundoprojetado.com.br/modulo-rfid-rc522/ +//#include +#include +#include + +#define PINO_RST 15 //SDA no módulo RFID +#define PINO_SS 5 + +#define pinRel 27 +#define pinBuzz 32 +#define pinGND 13 + +#define timeNegado 300 +#define timeAcesso 750 + +const char* serverAddress = "http://your-server-url"; + +MFRC522 mfrc522(PINO_SS, PINO_RST); + +void sendUIDToServer(String uid) { + // Replace the following with your server details + + HTTPClient http; + http.begin(serverAddress); + http.addHeader("Content-Type", "application/x-www-form-urlencoded"); + + String payload = "uid=" + uid; + int httpResponseCode = http.POST(payload); + + if (httpResponseCode > 0) { + Serial.print("HTTP Response code: "); + Serial.println(httpResponseCode); + + // Read the response from the server + String response = http.getString(); + Serial.print("Server Response: "); + Serial.println(response); + + // Parse the response (assuming '1' for success and '0' for failure) + if (response == "1") { + Serial.println("UID is in the database"); + buzz(1); + } else { + Serial.println("UID is NOT in the database"); + buzz(0); + } + } else { + Serial.print("HTTP Request failed. Error code: "); + Serial.println(httpResponseCode); + } + + http.end(); +} + +void buzz(int liberado){ + delay(50); + if(liberado == 1){ + delay(50); + Serial.print("\nAccess Granted"); + digitalWrite(pinBuzz,HIGH); + digitalWrite(pinRel,HIGH); + delay(timeAcesso); + digitalWrite(pinBuzz,LOW); + delay(timeAcesso*2); + digitalWrite(pinRel,LOW); + } else if(liberado == 0){ + Serial.print("\nAccess Denied"); + for(int b = 0; b < 6; b++){ + digitalWrite(pinBuzz, LOW); + delay(timeNegado); + digitalWrite(pinBuzz, HIGH); + delay(timeNegado); + } + digitalWrite(pinBuzz, LOW); + } +} + +void setup(){ + + pinMode(pinRel,OUTPUT); + pinMode(pinGND,OUTPUT); + pinMode(pinBuzz,OUTPUT); // PINO BUZZER (+ NO 5V E GND NO PINO 13. LOGICA INVERTIDA.) + + digitalWrite(pinGND,LOW); + + // Inicia a comunicação serial (monitor serial) + Serial.begin(9600); + Serial.println(". . . Booting System"); + + // Inicia a comunicação SPIE + SPI.begin(); + + // Inicia o módulo + mfrc522.PCD_Init(); + + Serial.println("Aguardando tag correta para abrir a porta..."); +} + +void loop(){ + String uid = ""; + // Verifica se existe um cartão presente para leitura + if (mfrc522.PICC_IsNewCardPresent()){ + // Se sim, começa a ler o cartão + if (mfrc522.PICC_ReadCardSerial()){ + // Verifica os 4 bytes da UID + Serial.print("Tag identificada: "); + for (byte j = 0; j < 4; j=j+4){ + for (byte i = 0; i < 4; i++){ + // Printa o byte atual + Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "); + Serial.print(mfrc522.uid.uidByte[i], HEX); + uid += String(mfrc522.uid.uidByte[i], HEX); + + } + } + + Serial.println("The ID Card: "); + Serial.println(uid); + Serial.println(" will be send to "); + Serial.println(serverAddress); + sendUIDToServer(uid); //Envia UID para o Servidor + + delay(3000); // Delay para não ficar lendo rapidamente + Serial.println("Aguardando tag certa para abrir a porta..."); +} From 558a00a7bd1f3df6b8cfe4412dfc910caf73e4a6 Mon Sep 17 00:00:00 2001 From: Adson Breno <101665691+AdsonBreno@users.noreply.github.com> Date: Mon, 11 Dec 2023 17:50:15 -0300 Subject: [PATCH 11/14] RFIDServer.cpp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Compilado, não testado --- RFIDServer.cpp | 48 +++++++++++++++++++++++++----------------------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/RFIDServer.cpp b/RFIDServer.cpp index 832739e..d994651 100644 --- a/RFIDServer.cpp +++ b/RFIDServer.cpp @@ -19,6 +19,29 @@ const char* serverAddress = "http://your-server-url"; MFRC522 mfrc522(PINO_SS, PINO_RST); +void buzz(int liberado){ + delay(50); + if(liberado == 1){ + delay(50); + Serial.print("\nAccess Granted"); + digitalWrite(pinBuzz,HIGH); + digitalWrite(pinRel,HIGH); + delay(timeAcesso); + digitalWrite(pinBuzz,LOW); + delay(timeAcesso*2); + digitalWrite(pinRel,LOW); + } else if(liberado == 0){ + Serial.print("\nAccess Denied"); + for(int b = 0; b < 6; b++){ + digitalWrite(pinBuzz, LOW); + delay(timeNegado); + digitalWrite(pinBuzz, HIGH); + delay(timeNegado); + } + digitalWrite(pinBuzz, LOW); + } +} + void sendUIDToServer(String uid) { // Replace the following with your server details @@ -54,29 +77,6 @@ void sendUIDToServer(String uid) { http.end(); } -void buzz(int liberado){ - delay(50); - if(liberado == 1){ - delay(50); - Serial.print("\nAccess Granted"); - digitalWrite(pinBuzz,HIGH); - digitalWrite(pinRel,HIGH); - delay(timeAcesso); - digitalWrite(pinBuzz,LOW); - delay(timeAcesso*2); - digitalWrite(pinRel,LOW); - } else if(liberado == 0){ - Serial.print("\nAccess Denied"); - for(int b = 0; b < 6; b++){ - digitalWrite(pinBuzz, LOW); - delay(timeNegado); - digitalWrite(pinBuzz, HIGH); - delay(timeNegado); - } - digitalWrite(pinBuzz, LOW); - } -} - void setup(){ pinMode(pinRel,OUTPUT); @@ -124,4 +124,6 @@ void loop(){ delay(3000); // Delay para não ficar lendo rapidamente Serial.println("Aguardando tag certa para abrir a porta..."); + } + } } From ec9963bc67e3e560aaa275ab6f67dd999fd6e709 Mon Sep 17 00:00:00 2001 From: Adson Breno <101665691+AdsonBreno@users.noreply.github.com> Date: Mon, 11 Dec 2023 17:51:25 -0300 Subject: [PATCH 12/14] Add files via upload --- Module 01 - ESP32/include/README | 39 ++++++++++ Module 01 - ESP32/lib/README | 46 +++++++++++ Module 01 - ESP32/platformio.ini | 18 +++++ Module 01 - ESP32/src/main.cpp | 129 +++++++++++++++++++++++++++++++ Module 01 - ESP32/test/README | 11 +++ 5 files changed, 243 insertions(+) create mode 100644 Module 01 - ESP32/include/README create mode 100644 Module 01 - ESP32/lib/README create mode 100644 Module 01 - ESP32/platformio.ini create mode 100644 Module 01 - ESP32/src/main.cpp create mode 100644 Module 01 - ESP32/test/README diff --git a/Module 01 - ESP32/include/README b/Module 01 - ESP32/include/README new file mode 100644 index 0000000..45496b1 --- /dev/null +++ b/Module 01 - ESP32/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/Module 01 - ESP32/lib/README b/Module 01 - ESP32/lib/README new file mode 100644 index 0000000..8c9c29c --- /dev/null +++ b/Module 01 - ESP32/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/Module 01 - ESP32/platformio.ini b/Module 01 - ESP32/platformio.ini new file mode 100644 index 0000000..664db8a --- /dev/null +++ b/Module 01 - ESP32/platformio.ini @@ -0,0 +1,18 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:nodemcu-32s] +platform = espressif32 +board = nodemcu-32s +framework = arduino +lib_deps = + miguelbalboa/MFRC522@^1.4.10 + mbed-jackb/EEPROM@0.0.0+sha.b90c5754d8db + ESPNow diff --git a/Module 01 - ESP32/src/main.cpp b/Module 01 - ESP32/src/main.cpp new file mode 100644 index 0000000..57c3420 --- /dev/null +++ b/Module 01 - ESP32/src/main.cpp @@ -0,0 +1,129 @@ +#include +#include +#include //https://mundoprojetado.com.br/modulo-rfid-rc522/ +//#include +#include +#include + +#define PINO_RST 15 //SDA no módulo RFID +#define PINO_SS 5 + +#define pinRel 27 +#define pinBuzz 32 +#define pinGND 13 + +#define timeNegado 300 +#define timeAcesso 750 + +const char* serverAddress = "http://your-server-url"; + +MFRC522 mfrc522(PINO_SS, PINO_RST); + +void buzz(int liberado){ + delay(50); + if(liberado == 1){ + delay(50); + Serial.print("\nAccess Granted"); + digitalWrite(pinBuzz,HIGH); + digitalWrite(pinRel,HIGH); + delay(timeAcesso); + digitalWrite(pinBuzz,LOW); + delay(timeAcesso*2); + digitalWrite(pinRel,LOW); + } else if(liberado == 0){ + Serial.print("\nAccess Denied"); + for(int b = 0; b < 6; b++){ + digitalWrite(pinBuzz, LOW); + delay(timeNegado); + digitalWrite(pinBuzz, HIGH); + delay(timeNegado); + } + digitalWrite(pinBuzz, LOW); + } +} + +void sendUIDToServer(String uid) { + // Replace the following with your server details + + HTTPClient http; + http.begin(serverAddress); + http.addHeader("Content-Type", "application/x-www-form-urlencoded"); + + String payload = "uid=" + uid; + int httpResponseCode = http.POST(payload); + + if (httpResponseCode > 0) { + Serial.print("HTTP Response code: "); + Serial.println(httpResponseCode); + + // Read the response from the server + String response = http.getString(); + Serial.print("Server Response: "); + Serial.println(response); + + // Parse the response (assuming '1' for success and '0' for failure) + if (response == "1") { + Serial.println("UID is in the database"); + buzz(1); + } else { + Serial.println("UID is NOT in the database"); + buzz(0); + } + } else { + Serial.print("HTTP Request failed. Error code: "); + Serial.println(httpResponseCode); + } + + http.end(); +} + +void setup(){ + + pinMode(pinRel,OUTPUT); + pinMode(pinGND,OUTPUT); + pinMode(pinBuzz,OUTPUT); // PINO BUZZER (+ NO 5V E GND NO PINO 13. LOGICA INVERTIDA.) + + digitalWrite(pinGND,LOW); + + // Inicia a comunicação serial (monitor serial) + Serial.begin(9600); + Serial.println(". . . Booting System"); + + // Inicia a comunicação SPIE + SPI.begin(); + + // Inicia o módulo + mfrc522.PCD_Init(); + + Serial.println("Aguardando tag correta para abrir a porta..."); +} + +void loop(){ + String uid = ""; + // Verifica se existe um cartão presente para leitura + if (mfrc522.PICC_IsNewCardPresent()){ + // Se sim, começa a ler o cartão + if (mfrc522.PICC_ReadCardSerial()){ + // Verifica os 4 bytes da UID + Serial.print("Tag identificada: "); + for (byte j = 0; j < 4; j=j+4){ + for (byte i = 0; i < 4; i++){ + // Printa o byte atual + Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "); + Serial.print(mfrc522.uid.uidByte[i], HEX); + uid += String(mfrc522.uid.uidByte[i], HEX); + + } + } + + Serial.println("The ID Card: "); + Serial.println(uid); + Serial.println(" will be send to "); + Serial.println(serverAddress); + sendUIDToServer(uid); //Envia UID para o Servidor + + delay(3000); // Delay para não ficar lendo rapidamente + Serial.println("Aguardando tag certa para abrir a porta..."); + } + } +} \ No newline at end of file diff --git a/Module 01 - ESP32/test/README b/Module 01 - ESP32/test/README new file mode 100644 index 0000000..b0416ad --- /dev/null +++ b/Module 01 - ESP32/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PlatformIO Test Runner and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PlatformIO Unit Testing: +- https://docs.platformio.org/en/latest/advanced/unit-testing/index.html From 1b118b602465dc6f0cff1aa97a104be546627c40 Mon Sep 17 00:00:00 2001 From: Adson Breno <101665691+AdsonBreno@users.noreply.github.com> Date: Mon, 29 Jul 2024 21:01:54 -0300 Subject: [PATCH 13/14] First test with a display and ESP32 This code shows a small ball that bounces on the wall of a 240x280 pixels display --- Bouncing_ball.cpp | 55 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Bouncing_ball.cpp diff --git a/Bouncing_ball.cpp b/Bouncing_ball.cpp new file mode 100644 index 0000000..0e7f0dc --- /dev/null +++ b/Bouncing_ball.cpp @@ -0,0 +1,55 @@ +#include +#include + +int pot; +float x, y, bin, b; + +TFT_eSPI tft = TFT_eSPI(); + +void setup() { + + Serial.begin(115200); + Serial.println("\n\n TFT_eSP Starting"); + + tft.init(); + tft.setRotation(0); //0 = 0°; 1 = 90°; 2 = 180° clockwise + + x = 0.0; + y = 12.0; //Starts at (0,12), avoiding top border + bin = 1.0; + b = 0.5; + +} + +void loop() { //Comments for debugging + + tft.fillScreen(0x000000); + tft.fillCircle(x, y, 10, 0xFFFFFF); + + if (x == 228){ + bin = -1; + //Serial.println("\nSubtraindo x"); + }else if (x == 12){ + bin = 1; + //Serial.print("\n Somando x"); + } + x += bin; + + if (y == 268){ + b = -0.5; + //Serial.print("\nSubtraindo y"); + }else if (y == 12){ + b = 0.5; + //Serial.println("\n Somando y"); + } + y += b; + + tft.drawString(String(x), 30, 90, 5); + tft.drawString(String(y), 70, 90, 5); + /*Serial.print("x = "); + Serial.println(x); + Serial.print("\n"); + Serial.print("y = "); + Serial.print(y);*/ + delay(100); +} From e9399cc3a48867765ae3044e4e12bc6d2fd6ba17 Mon Sep 17 00:00:00 2001 From: Adson Breno <101665691+AdsonBreno@users.noreply.github.com> Date: Mon, 29 Jul 2024 21:04:49 -0300 Subject: [PATCH 14/14] Bouncing_ball.cpp --- Bouncing_ball.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Bouncing_ball.cpp b/Bouncing_ball.cpp index 0e7f0dc..be7629f 100644 --- a/Bouncing_ball.cpp +++ b/Bouncing_ball.cpp @@ -17,14 +17,14 @@ void setup() { x = 0.0; y = 12.0; //Starts at (0,12), avoiding top border bin = 1.0; - b = 0.5; + b = 0.5; // Y changes by +/-0.5 } void loop() { //Comments for debugging tft.fillScreen(0x000000); - tft.fillCircle(x, y, 10, 0xFFFFFF); + tft.fillCircle(x, y, 10, 0xFFFFFF); // position in x, position in y, radius, colour if (x == 228){ bin = -1; @@ -44,8 +44,6 @@ void loop() { //Comments for debugging } y += b; - tft.drawString(String(x), 30, 90, 5); - tft.drawString(String(y), 70, 90, 5); /*Serial.print("x = "); Serial.println(x); Serial.print("\n");