Advertisement
RuiViana

CRemoto_E _Ethernet

Jan 26th, 2017
345
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 10.35 KB | None | 0 0
  1. /*
  2.    http://labdegaragem.com/forum/topics/alguem-me-ajuda-ajuntar-esses-dois-projeto-por-favor
  3.  
  4.    IRremote: IRrecvDemo - demonstrates receiving IR codes with IRrecv
  5.    An IR detector/demodulator must be connected to the input RECV_PIN.
  6.    Version 0.1 July, 2009
  7.    Copyright 2009 Ken Shirriff
  8.    http://arcfn.com
  9.  
  10.  
  11.   #include <IRremote.h>
  12.   #include <SerialRelay.h>
  13.  
  14.  
  15.   int RECV_PIN = 11;
  16.   const byte NumModules = 1;
  17.   SerialRelay relays(8,9,NumModules);
  18.  
  19.   IRrecv irrecv(RECV_PIN);
  20.  
  21.   decode_results results;
  22.  
  23.   void setup()
  24.   {
  25.   Serial.begin(9600);
  26.   irrecv.enableIRIn(); // Start the receiver
  27.   }
  28.  
  29.  
  30.   void loop()
  31.   {
  32.     if (irrecv.decode(&results)) {
  33.        Serial.println(results.value, DEC);
  34.     if(results.value == 3041579055){
  35.       relays.SetRelay(1, SERIAL_RELAY_ON, 1);
  36.       delay(500);
  37.       relays.SetRelay(1, SERIAL_RELAY_OFF, 1);
  38.       delay(500);
  39.     }
  40.     if(results.value == 3041546415){
  41.       relays.SetRelay(2, SERIAL_RELAY_ON, 1);
  42.       delay(500);
  43.       relays.SetRelay(2, SERIAL_RELAY_OFF, 1);
  44.       delay(500);
  45.     }
  46.     if(results.value == 3041532645){
  47.       relays.SetRelay(3, SERIAL_RELAY_ON, 1);
  48.       delay(500);
  49.       relays.SetRelay(3, SERIAL_RELAY_OFF, 1);
  50.       delay(500);
  51.     }
  52.     irrecv.resume(); // Receive the next value
  53.   }
  54.   }
  55. */
  56.  
  57. //ROBOCORE TECNOLOGIA - Rele Serial Ethernet v.1.0
  58. //Código para utilizar o Módulo Relé Serial através de rede ethernet
  59.  
  60. //O código abaixo requer o seguinte hardware:
  61. //01 x BlackBoard:
  62. //https://www.robocore.net/modules.php?name=GR_LojaVirtual&prod=530
  63. //01 x Arduino Shield - Ethernet:
  64. //https://www.robocore.net/modules.php?name=GR_LojaVirtual&prod=96
  65. //01 x Cartão de Memória MicroSD
  66. //https://www.robocore.net/modules.php?name=GR_LojaVirtual&prod=294
  67. //01 x Pacote com 10 Jumper Premium de 10 cm M/F
  68. //https://www.robocore.net/modules.php?name=GR_LojaVirtual&prod=365
  69. //até 10 x Módulos Rele Serial:
  70. //https://www.robocore.net/modules.php?name=GR_LojaVirtual&prod=663
  71.  
  72. //É necessário instalar as seguintes bibliotecas:
  73. //Serial Relay:
  74. //https://github.com/RoboCore/SerialRelay
  75. //Para instalar a bliblioteca basta acessar o menu "Sketch > Include Library > Add .ZIP Library" na IDE do Arduino e selecionar o Arquivo SerialRelay.zip contido no mesmo ZIP deste arquivo.
  76. //Ethernet_v2
  77. //https://github.com/RoboCore/Ethernet
  78. //Para instalar a bliblioteca basta acessar o menu "Sketch > Include Library > Add .ZIP Library" na IDE do Arduino e selecionar o Arquivo Ethernet_v2_1.6.5.zip contido no mesmo ZIP deste arquivo.
  79.  
  80. //Salve o arquivo index.htm (que veio junto com esse arquivo) em um cartão micro SD e o coloque no shield Ethernet.
  81.  
  82. #include <SPI.h>
  83. #include <SD.h>
  84. #include <Ethernet_v2.h>
  85. #include <SerialRelay.h>
  86.  
  87. #include <IRremote.h>
  88. int RECV_PIN = 11;
  89. IRrecv irrecv(RECV_PIN);
  90. decode_results results;
  91.  
  92.  
  93. //Define o Mac Address da placa de rede. Essa informação pode ser encontrada em uma etiqueta colada embaixo da mesma.
  94. byte mac[] = { 0x90, 0xA2, 0xDA, 0x10, 0xC6, 0x65 };
  95. //Define o IP da placa. Caso necessário altere o mesmo para se adequar a sua rede.
  96. IPAddress ip(192, 168, 0, 99);
  97. EthernetServer server(8484);
  98. File webFile;
  99. //na linha de baixo está sendo definido as portas em que o módulo relé serial está conectado.
  100. SerialRelay relays(8, 9, 3); // (pino de data, pino de clock, quantidade de módulos)
  101. #define REQ_BUF_SZ   60
  102. char HTTP_req[REQ_BUF_SZ] = {0};
  103. char req_index = 0;
  104. int estado_botao[41];
  105. char * pch;
  106. //---------------------------------------
  107. void setup()
  108. {
  109.   //ESTADO INICIAL DOS BOTOES 0 -> desligado, 1 -> ligado:
  110.   estado_botao[1] = 0;
  111.   estado_botao[2] = 0;
  112.   estado_botao[3] = 0;
  113.   estado_botao[4] = 0;
  114.   estado_botao[5] = 0;
  115.   estado_botao[6] = 0;
  116.   estado_botao[7] = 0;
  117.   estado_botao[8] = 0;
  118.   estado_botao[9] = 0;
  119.   estado_botao[10] = 0;
  120.   estado_botao[11] = 0;
  121.   estado_botao[12] = 0;
  122.   estado_botao[13] = 0;
  123.   estado_botao[14] = 0;
  124.   estado_botao[15] = 0;
  125.   estado_botao[16] = 0;
  126.   estado_botao[17] = 0;
  127.   estado_botao[18] = 0;
  128.   estado_botao[19] = 0;
  129.   estado_botao[20] = 0;
  130.   estado_botao[21] = 0;
  131.   estado_botao[22] = 0;
  132.   estado_botao[23] = 0;
  133.   estado_botao[24] = 0;
  134.   estado_botao[25] = 0;
  135.   estado_botao[26] = 0;
  136.   estado_botao[27] = 0;
  137.   estado_botao[28] = 0;
  138.   estado_botao[29] = 0;
  139.   estado_botao[30] = 0;
  140.   estado_botao[31] = 0;
  141.   estado_botao[32] = 0;
  142.   estado_botao[33] = 0;
  143.   estado_botao[34] = 0;
  144.   estado_botao[35] = 0;
  145.   estado_botao[36] = 0;
  146.   estado_botao[37] = 0;
  147.   estado_botao[38] = 0;
  148.   estado_botao[39] = 0;
  149.   estado_botao[40] = 0;
  150.   Serial.begin(9600);
  151.   Serial.println("Inicializando cartao microSD...");
  152.   if (!SD.begin(4))
  153.   {
  154.     Serial.println("ERRO - inicializacao do cartao falhou!");
  155.     return;
  156.   }
  157.   Serial.println("SUCESSO - cartao microSD inicializado.");
  158.   if (!SD.exists("index.htm"))
  159.   {
  160.     Serial.println("ERRO - index.htm nao foi encontrado!");
  161.     return;
  162.   }
  163.   Serial.println("SUCESSO - Encontrado arquivo index.htm.");
  164.   Ethernet.begin(mac, ip);
  165.   server.begin();
  166. }
  167. //---------------------------------------
  168. void loop()
  169. {
  170.   RemotoControl();
  171.   EthernetClient client = server.available();  //verifica se existe alguém querendo se conectar
  172.   if (client)   // existe cliente?
  173.   {
  174.     boolean currentLineIsBlank = true;
  175.     while (client.connected())
  176.     {
  177.       if (client.available())    // Existe informacao vinda do cliente
  178.       {
  179.         char c = client.read(); // Le cada byte enviado pelo cliente, ou seja, cada caracter.
  180.         // Por padrao, o ultimo caracter enviado pelo cliente (nosso navegador) é em branco  e termina com \n
  181.         // Dessa forma conseguimos saber se o cliente acabou de enviar informacoes para o servidor (Arduino)
  182.         if (req_index < (REQ_BUF_SZ - 1))
  183.         {
  184.           HTTP_req[req_index] = c;          // salva os caracteres das solicitacoes do browser
  185.           req_index++;
  186.         }
  187.         if (c == '\n' && currentLineIsBlank)
  188.         {
  189.           // envia para o cliente o protocolo padrao de sucesso HTTP
  190.           client.println("HTTP/1.1 200 OK");
  191.           client.println("Content-Type: text/html");
  192.           client.println("Connection: close");
  193.           client.println();
  194.           //caso a request seja pela ação de um botão:
  195.           if (StrContains(HTTP_req, "ajax_botao"))
  196.           {
  197.             for (int i = 1 ; i <= 40 ; i++)
  198.             {
  199.               //Serial.println(HTTP_req);
  200.               char botao[] = "botaoxx";
  201.               if (i < 10)
  202.               {
  203.                 botao[5] = '0';
  204.                 botao[6] = '0' + i;
  205.               } else {
  206.                 botao[5] = '0' + (i / 10);
  207.                 botao[6] = '0' + (i % 10);
  208.               }
  209.               //Serial.println(botao);
  210.               if (StrContains(HTTP_req, botao))
  211.               {
  212.                 SetBotao(i, client);
  213.               }
  214.             }
  215.           }
  216.           else {
  217.             // grava no arquivo webFile a página que temos no microSD
  218.             webFile = SD.open("index.htm");
  219.             if (webFile) {
  220.               while (webFile.available())
  221.               {
  222.                 client.write(webFile.read()); // envia para o cliente a página - nessa linha de fato o Arduino imprime no browser a página
  223.               }
  224.               webFile.close();
  225.             }
  226.           }
  227.           Serial.println(HTTP_req); //para debug, verifica no monitor serial a requisição
  228.           req_index = 0; //reseta o index do buffer e a variável que armazena as requisições
  229.           StrClear(HTTP_req, REQ_BUF_SZ);
  230.           break;
  231.         }
  232.         // toda linha de texto recebida do cliente termina com \r\n
  233.         if (c == '\n')
  234.         {
  235.           //verifica se acabou a linha, já que \n é o ultimo caracter
  236.           currentLineIsBlank = true;
  237.         }
  238.         else if (c != '\r')
  239.         {
  240.           // o cliente ainda está enviando informações
  241.           currentLineIsBlank = false;
  242.         }
  243.       }
  244.     }
  245.     delay(1);      // dá um tempo para o browser receber os dados
  246.     client.stop(); // fecha a conexão
  247.   }
  248. }
  249. //---------------------------------------
  250. void RemotoControl()
  251. {
  252.   if (irrecv.decode(&results)) {
  253.     Serial.println(results.value, DEC);
  254.     if (results.value == 3041579055)
  255.     {
  256.       relays.SetRelay(1, SERIAL_RELAY_ON, 1);
  257.       delay(500);
  258.       relays.SetRelay(1, SERIAL_RELAY_OFF, 1);
  259.       delay(500);
  260.     }
  261.     if (results.value == 3041546415)
  262.     {
  263.       relays.SetRelay(2, SERIAL_RELAY_ON, 1);
  264.       delay(500);
  265.       relays.SetRelay(2, SERIAL_RELAY_OFF, 1);
  266.       delay(500);
  267.     }
  268.     if (results.value == 3041532645)
  269.     {
  270.       relays.SetRelay(3, SERIAL_RELAY_ON, 1);
  271.       delay(500);
  272.       relays.SetRelay(3, SERIAL_RELAY_OFF, 1);
  273.       delay(500);
  274.     }
  275.     irrecv.resume(); // Receive the next value
  276.   }
  277. }
  278. //---------------------------------------
  279. void SetBotao(int botao, EthernetClient client)
  280. {
  281.   int modulo = (botao - 1) / 4 + 1;
  282.   int rele = botao % 4;
  283.   if (rele == 0) {
  284.     rele = 4;
  285.   }
  286.   Serial.print("modulo:");
  287.   Serial.print(modulo);
  288.   Serial.print(" rele:");
  289.   Serial.print(rele);
  290.   Serial.print(" - ");
  291.   if (estado_botao[botao] == 0) {
  292.     relays.SetRelay(rele, SERIAL_RELAY_ON, modulo);
  293.     delay(500);
  294.     estado_botao[botao] = 1;
  295.     //client.print("1");
  296.     Serial.println("1");
  297.     relays.SetRelay(rele, SERIAL_RELAY_OFF, modulo);
  298.     delay(500);
  299.     estado_botao[botao] = 0;
  300.     //client.print("0");
  301.     Serial.println("0");
  302.   }
  303.   client.print("0|");
  304.   for (int i = 1 ; i <= 40 ; i++)
  305.   {
  306.     client.print(estado_botao[i]);
  307.     client.print("|");
  308.   }
  309. }
  310. //---------------------------------------
  311. // funcao para limpar arrays (no nosso caso, as variaveis que armazenam requests)
  312. void StrClear(char *str, char length)
  313. {
  314.   for (int i = 0; i < length; i++)
  315.   {
  316.     str[i] = 0;
  317.   }
  318. }
  319. //---------------------------------------
  320. // funcao que procura pela string SFIND em STR
  321. // retorna 1 se a string for encontrada
  322. // retorna 0 se a setring não for encontrada
  323. char StrContains(char *str, char* sfind)
  324. {
  325.   char found = 0;
  326.   char index = 0;
  327.   char len;
  328.   len = strlen(str);
  329.   if (strlen(sfind) > len)
  330.   {
  331.     return 0;
  332.   }
  333.   while (index < len)
  334.   {
  335.     if (str[index] == sfind[found])
  336.     {
  337.       found++;
  338.       if (strlen(sfind) == found)
  339.       {
  340.         return 1;
  341.       }
  342.     }
  343.     else
  344.     {
  345.       found = 0;
  346.     }
  347.     index++;
  348.   }
  349.   return 0;
  350. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement