diff --git a/Bouncing_ball.cpp b/Bouncing_ball.cpp new file mode 100644 index 0000000..be7629f --- /dev/null +++ b/Bouncing_ball.cpp @@ -0,0 +1,53 @@ +#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; // Y changes by +/-0.5 + +} + +void loop() { //Comments for debugging + + tft.fillScreen(0x000000); + tft.fillCircle(x, y, 10, 0xFFFFFF); // position in x, position in y, radius, colour + + 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; + + /*Serial.print("x = "); + Serial.println(x); + Serial.print("\n"); + Serial.print("y = "); + Serial.print(y);*/ + delay(100); +} 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(); +} 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: - -} 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 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..."); + } + } + } +} diff --git a/RFID.cpp b/RFID.cpp new file mode 100644 index 0000000..ed53928 --- /dev/null +++ b/RFID.cpp @@ -0,0 +1,335 @@ +#include +#include +//#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 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 "EstadoPorta" +#define ID_SUBSCRIBE "UnidadeCard" +#define ID_SUBSCRIBE2 "AcaoMemoria" + +#define TOPIC_PUBLISH "EstadoPorta" +#define TOPIC_SUBSCRIBE "CARD" +#define TOPIC_SUBSCRIBE2 "EEPROM" + +const char* ssid = "LIEC_119"; +const char* pass = "********"; +const char* broker = "public.mqtthq.com"; //Test +int port = 1883; + +//TaskHandle_t ConnectWiFi; + +//Global constants +String idCard = ""; + +bool cartaoEncontrado = false; + +int liberado = 0; +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 MQTT3(wifiClient); +MFRC522 mfrc522(PINO_SS, PINO_RST); + +// Matriz para armazenar os cartões +uint8_t cartoes[NUM_CARTOES][4]; + +//void receivePacket2(char* topic, byte* payload, unsigned int length); +void receivePacket3(char* topic, byte* payload, unsigned int length); + +void setup() { + EEPROM.begin(EEPROM_SIZE); + + pinMode(pinBuzz, OUTPUT); + digitalWrite(pinGND, LOW); + digitalWrite(pinBuzz, LOW); + + Serial.begin(9600); + Serial.setDebugOutput(true); + Serial.println(". . .Booting System "); + + SPI.begin(); + + mfrc522.PCD_Init(); + + 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 + + keepConnections(); + + 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 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"){ //Comando para ESCREVER a Tag lida na memória + Serial.print("\nMessage Received '0'"); + 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"); + } +} + +void buzz(){ + delay(50); + if(liberado == 0){ + MQTT.publish(TOPIC_PUBLISH, "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); + } else if(liberado == 1){ + 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; + } + if(!MQTT.connected()) { + Serial.print("\nCould not publish. 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(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); + } + } +}*/ + +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); + } + } +} + +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, 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; + + } + } + } + Serial.print("UID Nova: "); + for (int i = 0; i < 4; i++) { + Serial.print(uid_tag_nova[i], HEX); + Serial.print(" "); + } + + // 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(1000); + Serial.println("\nAguardando tag correta para abrir a porta..."); + MQTT.loop(); + //MQTT2.loop(); + MQTT3.loop(); +} diff --git a/RFIDServer.cpp b/RFIDServer.cpp new file mode 100644 index 0000000..d994651 --- /dev/null +++ b/RFIDServer.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..."); + } + } +} 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); -} 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