Projeto Arduino
Gostaria de reagir a esta mensagem? Crie uma conta em poucos cliques ou inicie sessão para continuar.

Arduino UNO e SIM908 com comportamento estranho

Ir para baixo

Arduino UNO e SIM908 com comportamento estranho Empty Arduino UNO e SIM908 com comportamento estranho

Mensagem  undercrazy Ter 9 Jun - 11:16

Pessoal estou desenvolvendo o projeto abaixo, tudo separado funciona, quando eu junto tudo, tem horas que funciona horas que não, em alguns momentos reinicia e outros começa a mostrar um monte de caracteres estranhos (Estou usando o Arduino UNO e o Sim908 GPS / GSM / GPRS shield da projetoarduino) Alguém pode me ajudar por gentileza, quanto ao código podem usar a vontade.


#include "OneButton.h"
#include
#include


//int txPin = 3;
//int rxPin = 2;
//int powerkey =  5;
//int statuspin = 6;
int pinState = 0;
//int pos = 0;
//int tam = 40; //tamanho do registro
int8_t answer;


char nrorigem[15];
char frame[200];
char latitude[15];
char longitude[15];
char altitude[6];
char velocidade[10];

OneButton botao(7, false);
SoftwareSerial meuGSM(2, 3);

void setup() {
 Serial.println("Iniciando SecretSecurity!!");
 pinMode(5, OUTPUT);
 pinMode(6, INPUT);
 meuGSM.begin(9600);
 Serial.begin(9600);
 checaGSM();
 pinMode(8, OUTPUT); //led verde
 pinMode(9, OUTPUT); //led vermelho;
 sendATcommand("AT+CPIN=1010", "OK", 2000);
 ligaGPS();
 if (checaGPS() == 1) {
   pega_Dados();
 }
 botao.attachClick(envia1); //chama enviar alerta 1 ao pressionar o botão uma vez
 botao.attachDoubleClick(envia2); //chama enviar alerta 2 ao pressionar o botão duas vezes
 botao.attachPress(envia1);//chama enviar alerta 3 ao pressionar o botão durante um segundo
 botao.setClickTicks(1000); //define tempo de detecção do pressionamento do botão
 botao.setPressTicks(3000);  //define um tempo pressionando botão para enviar o alerta 3
 delay(200);
}

void loop() {
 botao.tick(); //checa botão
 lerSMS();  
 checaGSM();
}
void envia1() {
 Serial.println("Alerta 1");
 enviaAlerta(1);
}
void envia2() {
 Serial.println("Alerta 2");
 enviaAlerta(2);
}
void envia3() {
 Serial.println("Alerta 3");
 enviaAlerta(3);
}
int8_t lerSMS() {
 char message[180];
 int x = 0;
 char posicao;
 String msgRecebida = "";
 Serial.println("Lendo SMS");
 memset(message, '\0', 180);
 sendATcommand("AT+CMGF=1", "OK", 1000);    // Define modo texto
 sendATcommand("AT+CMGL=\"REC UNREAD\"", "OK", 1000);
 sendATcommand("AT+CPMS=\"SM\",\"SM\",\"SM\"", "OK", 1000);    // Seleciona o tipo de memória a considerar
 answer = sendATcommand("AT+CMGR=1", "+CMGR:", 2000);    // Ler o SMS do Slot 1
 if (answer == 1)
 {
   answer = 0;
   while (meuGSM.available() == 0);
   // ler os dados do SMS
   do {
     if (meuGSM.available() > 0) {
       message[x] = meuGSM.read();
       x++;
       //Checa se a resposta foi OK!
       if (strstr(message, "OK") != NULL)
       {
         answer = 1;
       }
     }
   } while (answer == 0);   // Aguarda fim da operação
   message[x] = '\0';
   strtok(message, ",");
   String origem(strcpy(nrorigem, strtok(NULL, ",")));
   strtok(NULL, "\r");
   String msgRecebida(strtok(NULL, "\r"));
   origem.replace("\"", "");
   origem.replace("+55", "");
   origem.trim();
   memset(nrorigem, '\0', 15);
   origem.toCharArray(nrorigem, 15);
   msgRecebida.trim();
   Serial.println(msgRecebida);
   Serial.println(nrorigem);
   if (msgRecebida.startsWith("#"))
   {
     if (msgRecebida.startsWith("#Validar"))
     {
       grava(7, msgRecebida.substring(Cool);
       enviaSMS(nrorigem, "#Validado");
       delay(3000);
     }
     if (msgRecebida.startsWith("#Formatar"))
     {
       enviaSMS(nrorigem, "#5594");
       delay(3000);
     }
     if (msgRecebida.startsWith("#$0000"))
     {
       limpaEPROM();
       delay(3000);
     }
   }
   if (msgRecebida.startsWith("C"))
   {
     //Serial.println(msgRecebida.substring(1, 15));
     //Serial.println(msgRecebida.substring(16, 30));
     //Serial.println(msgRecebida.substring(31, 45));

     grava(4, msgRecebida.substring(1, 15)); //grava
     delay(500);
     grava(5, msgRecebida.substring(16, 30)); //grava
     delay(500);
     grava(6, msgRecebida.substring(31, 45)); //grava
     delay(500);
     enviaSMS(nrorigem, "#COK");
     delay(3000);
   }
   if (msgRecebida.startsWith("A"))
   {
     grava(1, msgRecebida.substring(1, 40)); //grava
     delay(500);
     grava(2, msgRecebida.substring(41, 80)); //grava
     delay(500);
     grava(3, msgRecebida.substring(81, 120)); //grava
     delay(500);
     enviaSMS(nrorigem, "#AOK");
     delay(500);
   }
   if (msgRecebida.startsWith("#1A"))
   {
     enviaAlerta(1);
     delay(3000);
   }
   if (msgRecebida.startsWith("#2A"))
   {
     enviaAlerta(2);
     delay(3000);
   }
   if (msgRecebida.startsWith("#3A"))
   {
     enviaAlerta(3);
     delay(3000);
   }
   msgRecebida = "";
   if (x >= 5) {
     Serial.println("Deletando SMS no Slot 1");
     meuGSM.println("AT+CMGD=1");  //Apaga menssagem do slot 1
     delay(500);
     meuGSM.flush();
     x = 0;
   }
   delay(200);
 }
}

// Liga GPS
int8_t ligaGPS() {
 Serial.println("Inicializando o Modulo");
 answer = sendATcommand("ATE0", "OK", 1000);
 answer = sendATcommand("AT+CMGF=1", "OK", 1000);
 answer = sendATcommand("AT&W0", "OK", 1000);
 answer = sendATcommand("AT+CGPSRST=1", "OK", 1000);
}


int8_t enviaSMS(char *numero, char *mensagem) {
  char aux_string[180];
 // while ( (sendATcommand("AT+CREG?", "+CREG: 0,1", 500) ||sendATcommand("AT+CREG?", "+CREG: 0,5", 500)) == 0 );
 Serial.print("Configurando modo SMS...");
 sendATcommand("AT+CMGF=1", "OK", 1000);
 Serial.println("Enviando SMS");
 memset(aux_string, '\0', 180);
 sprintf(aux_string, "AT+CMGS=\"%s\"", numero);
 Serial.println(aux_string);
 answer = sendATcommand(aux_string, ">", 2000);    // send the SMS number
 if (answer == 1)
 {
   meuGSM.println(mensagem);
   meuGSM.write(0x1A);
   answer = sendATcommand("", "OK", 20000);
   if (answer == 1)
   {
     acende_led_verde ();
   }
   else
   {
     acende_led_vermelho ();
   }
 }
 else
 {
   acende_led_vermelho ();
   Serial.println(answer, DEC);
 }
 meuGSM.println("AT+CMGD=1");
 delay(500);
 meuGSM.flush();
 
}

int8_t checaGPS() {
 answer = 0;
 Serial.println("Verifica GPS");
 if (sendATcommand("AT+CGPSPWR?", "OK", 1000) == 0) {
   answer = sendATcommand("AT+CGPSPWR=1", "OK", 1000);
 }
 if (answer != 1) {
   answer = sendATcommand("AT+CGPSRST=0", "OK", 1000);
 }
 return answer;
}


int8_t enviaAlerta(int botao) {
 char numero[15];
 Serial.println("Enviando Alerta!");
 pega_Dados();
 if (botao > 3) {
   botao = 3;
 }
 char comp[180];
 memset(comp, '\0', 180);
 sprintf(comp, "%s:maps.google.com/?q=%s,%s", le(botao), latitude, longitude);
 String lera1(le(4));
 String lera2(le(5));
 String lera3(le(6));
 memset(numero, '\0', 15);
 lera1.trim();
 lera2.trim();
 lera3.trim();
 lera1.toCharArray(numero, lera1.length() + 1);
 Serial.println(numero);
 enviaSMS(numero, comp);
 delay(5000);
 memset(numero, '\0', 15);
 lera2.toCharArray(numero, lera2.length() + 1);
 Serial.println(numero);
 enviaSMS(numero, comp);
 delay(5000);
 memset(numero, '\0', 15);
 lera3.toCharArray(numero, lera3.length() + 1);
 Serial.println(numero);
 enviaSMS(numero, comp);
 memset(numero, '\0', 15);
 if (conectaIternet() == 1) {
   enviarCordenadas();
 }
 delay(200);

}
int8_t  conectaIternet() {
 answer = sendATcommand("AT+CIFSR", "AT+CIFSR", 200);
 if (answer == 1) {
   if (sendATcommand2("AT+CSTT=\"tim.com.br\",\"tim\",\"tim\"", "OK",  "ERROR", 3000) == 1) {
     answer = sendATcommand2("AT+CIICR", "OK",  "ERROR", 10000);
     answer = sendATcommand2("AT+CIFSR", ".", "ERROR", 4000);
     answer = sendATcommand("AT+CDNSCFG?", "OK", 4000);
   }
 }
}

int8_t enviarCordenadas() {
 uint8_t answer = 0;
 memset(frame, '\0', 200);
 sprintf(frame, "GET allthepeople.org/ss/add_localizacao.php?lat=%s&log=%s&altitude=%s&numero=%s&velocidade=%s", latitude, longitude, altitude, le(7), velocidade);
 if (sendATcommand2("AT+CIPSTART=1,\"TCP\",\"allthepeople.org\",\"80\"", "CONNECT OK", "CONNECT FAIL", 30000) == 1) {
   meuGSM.println(frame);
   meuGSM.println("AT+CIPSEND");
   delay(1000);
   meuGSM.write(10); //Equivalente a ctrl+j
   meuGSM.write(26); //CTRL+z
   delay(4000);
   meuGSM.println("AT+CIPCLOSE");
   delay(4000);
   meuGSM.flush();
 }
}

int8_t sendATcommand(char* ATcommand, char* expected_answer, unsigned int timeout) {
 uint8_t x = 0, answer = 0;
 char response[100];
 unsigned long previous;
 memset(response, '\0', 100); // initalize string
 delay(100);

 while (meuGSM.available() > 0) {
   meuGSM.read(); // clears the buffer
 }
 meuGSM.println(ATcommand);
 x = 0;
 previous = millis();
 do {
   if (meuGSM.available() != 0) {
     response[x] = meuGSM.read();
     x++;
     if (strstr(response, expected_answer) != NULL) {
       answer = 1;
     }
   }
 } while ((answer == 0) && ((millis() - previous) < timeout));
 Serial.println(response);
 meuGSM.flush();
 return answer;
}

int8_t sendATcommand2(char* ATcommand, char* expected_answer1, char* expected_answer2, unsigned int timeout) {
 uint8_t x = 0,  answer = 0;
 char response[100];
 unsigned long previous;
 memset(response, '\0', 100);    // Initialize the string
 delay(100);
 while ( meuGSM.available() > 0) meuGSM.read();   // Clean the input buffer
 meuGSM.println(ATcommand);    // Send the AT command
 x = 0;
 previous = millis();
 // this loop waits for the answer
 do {
   // if there are data in the UART input buffer, reads it and checks for the asnwer
   if (meuGSM.available() != 0) {
     response[x] = meuGSM.read();
     x++;
     // check if the desired answer 1  is in the response of the module
     if (strstr(response, expected_answer1) != NULL)
     {
       answer = 1;
     }
     // check if the desired answer 2 is in the response of the module
     else if (strstr(response, expected_answer2) != NULL)
     {
       answer = 2;
     }
   }
 }
 // Waits for the asnwer with time out
 while ((answer == 0) && ((millis() - previous) < timeout));
 Serial.println(response);
 meuGSM.flush();
 return answer;
}

int8_t pega_Dados() {
 Serial.println("Pega dados GPS...");
 int8_t counter, answer;
 long previous;

 // First get the NMEA string
 // Clean the input buffer
 while ( meuGSM.available() > 0) meuGSM.read();
 // request Basic string
 sendATcommand("AT+CGPSINF=0", "AT+CGPSINF=0\r\n\r\n", 2000);
 counter = 0;
 answer = 0;
 memset(frame, '\0', 100);    // Initialize the string
 previous = millis();
 // this loop waits for the NMEA string
 do {

   if (meuGSM.available() != 0) {
     frame[counter] = meuGSM.read();
     counter++;
     // check if the desired answer is in the response of the module
     if (strstr(frame, "OK") != NULL)
     {
       answer = 1;
     }
   }
   // Waits for the asnwer with time out
 }
 while ((answer == 0) && ((millis() - previous) < 2000));

 frame[counter - 3] = '\0';

 // Parses the string
 //0,0.000000,0.000000,0.000000,19800105235950.000,0,0,0.000000,0.000000
 strtok(frame, ",");
 strcpy(longitude, strtok(NULL, ",")); // pega longitude
 strcpy(latitude, strtok(NULL, ",")); // pega latitude
 strcpy(altitude, strtok(NULL, ".")); // pega altitude
 strtok(NULL, ",");
 strtok(NULL, "."); // pega data
 strtok(NULL, ",");
 strtok(NULL, ",");
 strtok(NULL, ","); // pega satelite
 strcpy(velocidade, strtok(NULL, ",")); // pega velocidade.
 strtok(NULL, "\r"); // pega crso

 convert2Degrees(latitude);
 convert2Degrees(longitude);
 return answer;
}


int8_t convert2Degrees(char* input) {

 float deg;
 float minutes;
 boolean neg = false;
 //auxiliar variable
 char aux[10];

 if (input[0] == '-')
 {
   neg = true;
   strcpy(aux, strtok(input + 1, "."));
 }
 else
 {
   strcpy(aux, strtok(input, "."));
 }
 // convert string to integer and add it to final float variable
 deg = atof(aux);
 strcpy(aux, strtok(NULL, '\0'));
 minutes = atof(aux);
 minutes /= 1000000;
 if (deg < 100)
 {
   minutes += deg;
   deg = 0;
 }
 else
 {
   minutes += int(deg) % 100;
   deg = int(deg) / 100;
 }
 // add minutes to degrees
 deg = deg + minutes / 60;
 if (neg == true)
 {
   deg *= -1.0;
 }
 neg = false;
 if ( deg < 0 ) {
   neg = true;
   deg *= -1;
 }

 float numeroFloat = deg;
 int parteEntera[10];
 int cifra;
 long numero = (long)numeroFloat;
 int size = 0;
 while (1) {
   size = size + 1;
   cifra = numero % 10;
   numero = numero / 10;
   parteEntera[size - 1] = cifra;
   if (numero == 0) {
     break;
   }
 }
 int indice = 0;
 if ( neg ) {
   indice++;
   input[0] = '-';
 }
 for (int i = size - 1; i >= 0; i--)
 {
   input[indice] = parteEntera[i] + '0';
   indice++;
 }

 input[indice] = '.';
 indice++;

 numeroFloat = (numeroFloat - (int)numeroFloat);
 for (int i = 1; i <= 6 ; i++)
 {
   numeroFloat = numeroFloat * 10;
   cifra = (long)numeroFloat;
   numeroFloat = numeroFloat - cifra;
   input[indice] = char(cifra) + 48;
   indice++;
 }
 input[indice] = '\0';
}

void checaGSM() {
 pinState = digitalRead(6);
 if (pinState == LOW) {
   digitalWrite(5, HIGH);   // set the LED on
   delay(2000);
   digitalWrite(5, LOW);
 }
 if (Serial.available())
 {
   meuGSM.write(Serial.read());
 }
 else  if (meuGSM.available())
 {
   Serial.write(meuGSM.read());
 }

}

char* le(int record) {
 byte value;
 String a = "";
 for (int i = (record - 1) * 40; i < (record - 1)*40 + 40; i++) {
   value = EEPROM.read(i);
   a += char(value);
 }
 char * c = (char *) malloc (a.length() + 1);
 a.toCharArray(c, a.length() + 1);
 return c;
}

void grava(int record, String a) {
 char b[40 + 1];
 a.concat("                                        ");
 a.toCharArray(b, 40 + 1);
 int pos = (record - 1) * 40;
 for (int i = pos; i < pos + 40; i++) {
   EEPROM.write(i, b[i - pos]);
 }
}
void acende_led_verde () {
 Serial.println("Inicio - Acende led verde");
 digitalWrite(8, HIGH);
 delay(2000);
 digitalWrite(8, LOW);
}

void acende_led_vermelho () {
 Serial.println("Inicio - Acende led vermelho");
 digitalWrite(9, HIGH);
 delay(2000);
 digitalWrite(9, LOW);
}
void limpaEPROM() {
 for (int i = 0; i < 512; i++)
   EEPROM.write(i, 0);
 acende_led_verde();
}

undercrazy

Mensagens : 1
Data de inscrição : 09/06/2015

Ir para o topo Ir para baixo

Ir para o topo

- Tópicos semelhantes

 
Permissões neste sub-fórum
Não podes responder a tópicos