Advertisement
Guest User

Untitled

a guest
Dec 11th, 2015
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.02 KB | None | 0 0
  1. //ROBOCORE TECNOLOGIA - Rele Serial Ethernet v.1.0
  2. //Código para utilizar o Módulo Relé Serial através de rede ethernet
  3.  
  4. //O código abaixo requer o seguinte hardware:
  5. //01 x BlackBoard:
  6. //https://www.robocore.net/modules.php?name=GR_LojaVirtual&prod=530
  7. //01 x Arduino Shield - Ethernet:
  8. //https://www.robocore.net/modules.php?name=GR_LojaVirtual&prod=96
  9. //01 x Cartão de Memória MicroSD
  10. //https://www.robocore.net/modules.php?name=GR_LojaVirtual&prod=294
  11. //01 x Pacote com 10 Jumper Premium de 10 cm M/F
  12. //https://www.robocore.net/modules.php?name=GR_LojaVirtual&prod=365
  13. //até 10 x Módulos Rele Serial:
  14. //https://www.robocore.net/modules.php?name=GR_LojaVirtual&prod=663
  15.  
  16. //É necessário instalar as seguintes bibliotecas:
  17. //Serial Relay:
  18. //https://github.com/RoboCore/SerialRelay
  19. //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.
  20. //Ethernet_v2
  21. //https://github.com/RoboCore/Ethernet
  22. //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.
  23.  
  24. //Salve o arquivo index.htm (que veio junto com esse arquivo) em um cartão micro SD e o coloque no shield Ethernet.
  25.  
  26. #include <SPI.h>
  27. #include <SD.h>
  28. #include <Ethernet_v2.h>
  29. #include <SerialRelay.h>
  30.  
  31. //Define o Mac Address da placa de rede. Essa informação pode ser encontrada em uma etiqueta colada embaixo da mesma.
  32. byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0xA1, 0x5C };
  33. //Define o IP da placa. Caso necessário altere o mesmo para se adequar a sua rede.
  34. IPAddress ip(192, 168, 0, 90);
  35.  
  36. EthernetServer server(80);
  37. File webFile;
  38.  
  39. //na linha de baixo está sendo definido as portas em que o módulo relé serial está conectado.
  40. SerialRelay relays(8, 9, 10); // (pino de data, pino de clock, quantidade de módulos)
  41.  
  42. #define REQ_BUF_SZ 60
  43. char HTTP_req[REQ_BUF_SZ] = {0};
  44. char req_index = 0;
  45.  
  46. int estado_botao[41];
  47.  
  48. char * pch;
  49.  
  50. void setup()
  51. {
  52. //ESTADO INICIAL DOS BOTOES 0 -> desligado, 1 -> ligado:
  53. estado_botao[1] = 0;
  54. estado_botao[2] = 0;
  55. estado_botao[3] = 0;
  56. estado_botao[4] = 0;
  57.  
  58.  
  59. Serial.begin(9600);
  60.  
  61. Serial.println("Inicializando cartao microSD...");
  62. if (!SD.begin(4)) {
  63. Serial.println("ERRO - inicializacao do cartao falhou!");
  64. return;
  65. }
  66. Serial.println("SUCESSO - cartao microSD inicializado.");
  67.  
  68. if (!SD.exists("index.htm")) {
  69. Serial.println("ERRO - index.htm nao foi encontrado!");
  70. return;
  71. }
  72. Serial.println("SUCESSO - Encontrado arquivo index.htm.");
  73.  
  74. Ethernet.begin(mac, ip);
  75. server.begin();
  76. }
  77.  
  78. void loop()
  79. {
  80. EthernetClient client = server.available(); //verifica se existe alguém querendo se conectar
  81.  
  82. if (client) { // existe cliente?
  83. boolean currentLineIsBlank = true;
  84. while (client.connected()) {
  85. if (client.available()) { // Existe informacao vinda do cliente
  86. char c = client.read(); // Le cada byte enviado pelo cliente, ou seja, cada caracter.
  87. // Por padrao, o ultimo caracter enviado pelo cliente (nosso navegador) é em branco e termina com \n
  88. // Dessa forma conseguimos saber se o cliente acabou de enviar informacoes para o servidor (Arduino)
  89. if (req_index < (REQ_BUF_SZ - 1)) {
  90. HTTP_req[req_index] = c; // salva os caracteres das solicitacoes do browser
  91. req_index++;
  92. }
  93. if (c == '\n' && currentLineIsBlank) {
  94. // envia para o cliente o protocolo padrao de sucesso HTTP
  95. client.println("HTTP/1.1 200 OK");
  96. client.println("Content-Type: text/html");
  97. client.println("Connection: close");
  98. client.println();
  99.  
  100.  
  101. //caso a request seja pela ação de um botão:
  102. if (StrContains(HTTP_req, "ajax_botao")) {
  103. for (int i = 1 ; i <= 40 ; i++) {
  104. //Serial.println(HTTP_req);
  105. char botao[] = "botaoxx";
  106. if (i < 10) {
  107. botao[5] = '0';
  108. botao[6] = '0' + i;
  109. } else {
  110. botao[5] = '0' + (i / 10);
  111. botao[6] = '0' + (i % 10);
  112. }
  113.  
  114. //Serial.println(botao);
  115. if (StrContains(HTTP_req, botao)) {
  116. SetBotao(i, client);
  117. }
  118. }
  119. }
  120. else {
  121. // grava no arquivo webFile a página que temos no microSD
  122. webFile = SD.open("index.htm");
  123. if (webFile) {
  124. while (webFile.available()) {
  125. client.write(webFile.read()); // envia para o cliente a página - nessa linha de fato o Arduino imprime no browser a página
  126. }
  127. webFile.close();
  128. }
  129. }
  130. Serial.println(HTTP_req); //para debug, verifica no monitor serial a requisição
  131. req_index = 0; //reseta o index do buffer e a variável que armazena as requisições
  132. StrClear(HTTP_req, REQ_BUF_SZ);
  133. break;
  134. }
  135. // toda linha de texto recebida do cliente termina com \r\n
  136. if (c == '\n') {
  137. //verifica se acabou a linha, já que \n é o ultimo caracter
  138. currentLineIsBlank = true;
  139. }
  140. else if (c != '\r') {
  141. // o cliente ainda está enviando informações
  142. currentLineIsBlank = false;
  143. }
  144. }
  145. }
  146. delay(1); // dá um tempo para o browser receber os dados
  147. client.stop(); // fecha a conexão
  148. }
  149. }
  150.  
  151.  
  152.  
  153. void SetBotao(int botao, EthernetClient client) {
  154.  
  155. int modulo = (botao - 1) / 4 + 1;
  156. int rele = botao % 4;
  157. if (rele == 0) {
  158. rele = 4;
  159. }
  160.  
  161. Serial.print("modulo:");
  162. Serial.print(modulo);
  163. Serial.print(" rele:");
  164. Serial.print(rele);
  165. Serial.print(" - ");
  166.  
  167. if (estado_botao[botao] == 0) {
  168. relays.SetRelay(rele, SERIAL_RELAY_ON, modulo);
  169. estado_botao[botao] = 1;
  170. //client.print("1");
  171. Serial.println("1");
  172. }
  173. else {
  174. relays.SetRelay(rele, SERIAL_RELAY_OFF, modulo);
  175. estado_botao[botao] = 0;
  176. //client.print("0");
  177. Serial.println("0");
  178. }
  179. client.print("0|");
  180. for (int i = 1 ; i <= 40 ; i++) {
  181. client.print(estado_botao[i]);
  182. client.print("|");
  183. }
  184.  
  185. }
  186.  
  187. // funcao para limpar arrays (no nosso caso, as variaveis que armazenam requests)
  188. void StrClear(char *str, char length)
  189. {
  190. for (int i = 0; i < length; i++) {
  191. str[i] = 0;
  192. }
  193. }
  194.  
  195. // funcao que procura pela string SFIND em STR
  196. // retorna 1 se a string for encontrada
  197. // retorna 0 se a setring não for encontrada
  198. char StrContains(char *str, char* sfind)
  199. {
  200. char found = 0;
  201. char index = 0;
  202. char len;
  203.  
  204. len = strlen(str);
  205.  
  206. if (strlen(sfind) > len) {
  207. return 0;
  208. }
  209. while (index < len) {
  210. if (str[index] == sfind[found]) {
  211. found++;
  212. if (strlen(sfind) == found) {
  213. return 1;
  214. }
  215. }
  216. else {
  217. found = 0;
  218. }
  219. index++;
  220. }
  221. return 0;
  222. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement