Advertisement
RuiViana

RFID_SD_S

Oct 9th, 2017
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 9.39 KB | None | 0 0
  1. //Programa desenvolvido por Stella Marques
  2. //Data : 09/10/2017
  3. //Lavras - MG
  4. //Hora da compilação - 13:29hs
  5.  
  6. /*
  7.   Inormações tecnicas:
  8.   Led vermelho na porta A2 - res 330 no positivo
  9.   Led verde porta A1 - res 330 no positivo
  10.   BUZZER porta 6
  11.   Bluetooth:
  12.   RX - 1
  13.   TX - 0
  14. */
  15. #include <SPI.h>
  16. #include <MFRC522.h>
  17. #include "LiquidCrystal_I2C.h"
  18. #include <Wire.h>
  19. #include <SD.h>
  20.  
  21. //RFID////
  22. #define SS_PIN 9
  23. #define RST_PIN 8
  24. MFRC522 mfrc522(SS_PIN, RST_PIN);   // Cria a instancia do tipo MFRC522.
  25. MFRC522::MIFARE_Key key;
  26. /////RFID//
  27.  
  28. // Inicializa o display LCD no endereco 0x27////
  29. //LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7,3, POSITIVE);
  30. LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
  31. char st[20];
  32. ///////LCd//////
  33.  
  34. const int buzzer = 3;
  35. #define LEDVERDE  A1
  36. #define LEDVERMELHO  A2
  37.  
  38. //Ponteiro para o arquivo do GPS
  39. File myFile;
  40.  
  41. //Variaveis Global
  42. //int i = 5;
  43.  
  44. void setup()
  45. {
  46.   Serial.begin(9600);  //Inicializa Comunicacao serial do Arduino Mega do pino 0[RX] e 1[TX] para depuracao do codigo
  47.   Serial2.begin(9600); //Inicializa Bluetooth do Arduino Mega TX do bluetooth conectado ao pino 17[RX2] e RXD do Bluetooth conectado ao pino digital 16[TX2]
  48.   SPI.begin();      // Inicia  SPI bus
  49.   mfrc522.PCD_Init();   // Inicia MFRC522
  50.   //Inicializa o LCD 16x2
  51.   lcd.begin(16, 2);
  52.   //Prepara chave - padrao de fabrica = FFFFFFFFFFFFh
  53.   for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;
  54.   // Define os pinos dos leds e buzzer como saida
  55.   pinMode(LEDVERDE, OUTPUT);
  56.   pinMode(LEDVERMELHO, OUTPUT);
  57.   pinMode(buzzer, OUTPUT);
  58.   Serial.print("\nInicializando SD...");
  59.   if (!SD.begin(4))
  60.   {
  61.     Serial.println("Falha-SD");
  62.     Serial2.println("Falha-SD");
  63.     return;
  64.   }
  65.   Serial.println("SD-OK");
  66.   Serial2.println("SD-OK");
  67.   //Serial.println("Teste Inicializacao");
  68. }
  69. ///////////////////////////////////////////////// Fim SETUP Inicio LOOP ////////////////////////////////////////////////
  70. void loop()
  71. {
  72.   String cartao = "";
  73.   String inicia = "ok";
  74.   String retorno = "";
  75.   delay(2000);
  76.   digitalWrite(LEDVERDE, HIGH);
  77.   inicia =  recebeStringSerial2();
  78.   while (inicia != "fim")
  79.   {
  80.     retorno = leituraCartao();
  81.     //Serial.println(retorno); //Teste para ver o retorno da função de leitura
  82.     if (retorno != "NADA")
  83.     {
  84.       if ((retorno == "ERRO1") || (retorno == "ERRO2"))
  85.       {
  86.         erroLeitura();
  87.         delay(500);
  88.       } else { //caso a leitura da TAG tenha ocorrido com sucesso
  89.         Serial.print("'" + retorno + "';");
  90.         Serial2.print("'" + retorno + "';");
  91.         cartao = escreveSD(retorno);
  92.         Serial1.print("SD: ");
  93.         Serial1.println(retorno);
  94.       }
  95.     }
  96.     inicia =  recebeStringSerial2();
  97.     if (inicia == "fim")
  98.     {
  99.       Serial.print("Inicio Descarregar SD...");
  100.       lcd_SD();
  101.       delay(2000);
  102.       descarregaSD();
  103.       deletaArquivosSD();
  104.       Serial.print("Fim Descarregar SD.");
  105.       delay(2000);
  106.     }
  107.   }
  108. }
  109.  
  110. ////////////////////////////////////////// Funcoes para funcionamento do cartao SD ////////////////////////////
  111. void descarregaSD()
  112. {
  113.   myFile = SD.open("tags.txt");
  114.   if (myFile)
  115.   {
  116.     // Le todo o arquivo txt
  117.     while (myFile.available())
  118.     {
  119.       //Descarrega todo o arquivo gps na serial
  120.       Serial.write(myFile.read());
  121.     }
  122.     // fecha o arquivo
  123.     myFile.close();
  124.     delay(10);
  125.  
  126.     myFile = SD.open("tags.txt");
  127.     // Le todo o arquivo txt
  128.     while (myFile.available())
  129.     {
  130.       //Descarrega todo o arquivo gps na serial 2 - Bluetooth conectado
  131.       Serial2.write(myFile.read());
  132.     }
  133.     // fecha o arquivo
  134.     myFile.close();
  135.   } else {
  136.     //Imprime erro ao abrir caso o arquivo teste nao possa ser aberto
  137.     Serial.println("Erro ao abrir tags.txt");
  138.   }
  139. }
  140.  
  141. void deletaArquivosSD()
  142. {
  143.   SD.remove("tags.txt");
  144. }
  145.  
  146. String escreveSD(String dados)
  147. {
  148.   myFile = SD.open("tags.txt", FILE_WRITE);
  149.   if (myFile)
  150.   {
  151.     //Serial.print("Escrevendo no gps.txt... ");
  152.     //myFile.println("Teste Stella Marques! :)");
  153.     myFile.print(dados + "\n");
  154.     // close the file:
  155.     myFile.close();
  156.     //Serial.println(" ...OK");
  157.     dados = "OK";
  158.   } else {
  159.     // retorna um erro caso o arquvino testeStella.txt nao possa ser aberto
  160.     Serial.println("Erro ao abrir tags.txt");
  161.     dados = "Falha";
  162.   }
  163.   delay(50);
  164.   return dados;
  165. }
  166.  
  167. String recebeStringSerial()
  168. {
  169.   String dados = "";
  170.   char caractere;
  171.  
  172.   // Enquanto receber algo pela serial do usb
  173.   if (Serial.available() > 0) {
  174.     while (Serial.available() > 0)
  175.     {
  176.       // Lê byte da serial
  177.       caractere = Serial.read();
  178.       // Ignora caractere de quebra de linha
  179.       if (caractere != '\n')
  180.       {
  181.         // Concatena valores
  182.         dados.concat(caractere);
  183.       }
  184.       // Aguarda buffer serial ler próximo caractere
  185.       delay(10);
  186.     }
  187.   } else {
  188.     return "ok";
  189.   }
  190.  
  191.   Serial.print("Recebido: ");
  192.   Serial.println(dados);
  193.  
  194.   return dados;
  195. }
  196.  
  197. String recebeStringSerial2()
  198. {
  199.   String dados = "";
  200.   char caractere;
  201.   if (Serial2.available() > 0) {
  202.     //Enquanto receber algo pela serial do usb
  203.     while (Serial2.available() > 0)
  204.     {
  205.       //Lê byte da serial
  206.       caractere = Serial2.read();
  207.       // Ignora caractere de quebra de linha
  208.       if (caractere != '\n')
  209.       {
  210.         //Concatena valores
  211.         dados.concat(caractere);
  212.       }
  213.       //Aguarda buffer serial ler próximo caractere
  214.       delay(10);
  215.     }
  216.   } else {
  217.     return "ok";
  218.   }
  219.  
  220.   Serial.print("Recebido: ");
  221.   Serial.println(dados);
  222.  
  223.   return dados;
  224. }
  225.  
  226. void ligaBuzzer() {
  227.   // Aciona o buzzer 3 vezes
  228.   //for (int i = 1; i <= 2; i++)
  229.   //{
  230.   //Pisca ligando e desligando led vermelho,verdee buzzer
  231.   digitalWrite(LEDVERDE, HIGH);
  232.   digitalWrite(LEDVERMELHO, HIGH);
  233.   tone(buzzer, 1500, 1000);
  234.   delay(200);
  235.   noTone(buzzer);
  236.   tone(buzzer, 1500, 1000);
  237.   delay(200);
  238.   noTone(buzzer);
  239.   //Desligando o buzzer.
  240.   //digitalWrite(LEDVERDE, LOW);
  241.   digitalWrite(LEDVERMELHO, LOW);
  242.   //delay(500);
  243.   //}
  244.   // noTone(buzzer);
  245. }
  246.  
  247. String leituraCartao()
  248. {
  249.   if ( ! mfrc522.PICC_IsNewCardPresent())
  250.   {
  251.     delay(100);
  252.   }
  253.   if ( ! mfrc522.PICC_ReadCardSerial())
  254.   {
  255.     // Serial.print(" -1 "); //-1 Representa erro na serial
  256.     return "NADA" ;
  257.   }
  258.  
  259.   String conteudo = "";
  260.   byte letra;
  261.  
  262.   //bloco abaixo imprime o ID da tag
  263.   for (byte i = 0; i < mfrc522.uid.size; i++)
  264.   {
  265.     ///Essa parte é nessearia para concatenar e imprimir a tag, em letras maiusculas
  266.     //Retirei a parte que imprime em maiusculo, e colocoquei somente para concatenar.
  267.     //Abaixo eu imprimo o resultado da concatenação na serial
  268.     //Para imprimir em Maiusculo e durante a concatenação basta descomentar as 2 linhas abaixo e o println logo abaixo.
  269.     //Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
  270.     //Serial.print(mfrc522.uid.uidByte[i], HEX);
  271.     conteudo.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : ""));
  272.     conteudo.concat(String(mfrc522.uid.uidByte[i], HEX));
  273.   }
  274.   //Serial.println();
  275.   //Serial.println(conteudo);
  276.  
  277.   //Obtem os dados do setor 1, bloco 4 = Sobrenome
  278.   byte sector         = 1;
  279.   byte blockAddr      = 4;
  280.   byte trailerBlock   = 7;
  281.   byte status;
  282.   byte buffer[18];
  283.   byte size = sizeof(buffer);
  284.   //Autenticacao usando chave A (Nome)
  285.   status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
  286.   if (status != MFRC522::STATUS_OK) {
  287.     return "ERRO1";
  288.   }
  289.   status = mfrc522.MIFARE_Read(blockAddr, buffer, &size);
  290.   if (status != MFRC522::STATUS_OK) {}
  291.   //Mostra os dados do nome no Serial Monitor e LCD
  292.   lcd.clear();
  293.   lcd.setCursor(0, 0);
  294.   for (byte i = 0; i < 16; i++)
  295.   {
  296.     //fSerial.print(char(buffer[i])); //Imprime o nome na Serial
  297.     lcd.write(char(buffer[i]));
  298.   }
  299.   //Serial.println();
  300.  
  301.   //Obtem os dados do setor 0, bloco 1 = Nome
  302.   sector         = 0;
  303.   blockAddr      = 1;
  304.   trailerBlock   = 3;
  305.  
  306.   //Autenticacao usando chave B (Escola)
  307.   status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
  308.   if (status != MFRC522::STATUS_OK)
  309.   {
  310.     return "ERRO2";
  311.   }
  312.   status = mfrc522.MIFARE_Read(blockAddr, buffer, &size);
  313.   if (status != MFRC522::STATUS_OK) { }
  314.   //Mostra os dados do sobrenome no Serial Monitor e LCD
  315.   lcd.setCursor(0, 1);
  316.   for (byte i = 0; i < 16; i++)
  317.   {
  318.     //Serial.print(char(buffer[i])); //Imprime o sobrenome na serial
  319.     lcd.write(char(buffer[i]));
  320.   }
  321.  
  322.   ligaBuzzer();
  323.   // Serial.println(); //Teste na serial
  324.   delay(500);
  325.   // Halt PICC
  326.   mfrc522.PICC_HaltA();
  327.   // Stop encryption on PCD
  328.   mfrc522.PCD_StopCrypto1();
  329.   delay(1000);
  330.   //mensagem_inicial_cartao();
  331.   //Se chegou ate aqui é porque leu um cartão valido então conta uma pessoa, com o retorno 3
  332.   return conteudo;
  333. }
  334.  
  335. void mensagem_inicial_cartao()
  336. {
  337.   //Serial.println("Aproxime o seu cartao do leitor..."); //teste na serial
  338.   lcd.clear();
  339.   lcd.print(" Aproxime o seu");
  340.   lcd.setCursor(0, 1);
  341.   lcd.print("cartao do leitor");
  342. }
  343.  
  344. void lcd_SD()
  345. {
  346.   //Serial.println("Aproxime o seu cartao do leitor..."); //teste na serial
  347.   lcd.clear();
  348.   lcd.print("   Conectando");
  349.   lcd.setCursor(0, 1);
  350.   lcd.print(" Banco de Dados");
  351. }
  352.  
  353. void erroLeitura()
  354. {
  355.   //Serial.println("Equilibrio Administrativo"); //teste na serial
  356.   lcd.clear();
  357.   lcd.setCursor(0, 0);
  358.   lcd.print("Erro na leitura");
  359.   //lcd.setCursor(2, 1);
  360.   //lcd.print(" ");
  361. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement