Arduino - Uso de redes WiFi y GSM/GPRS

 
Vista:
sin imagen de perfil
Val: 3
Ha disminuido su posición en 5 puestos en Arduino (en relación al último mes)
Gráfica de Arduino

Uso de redes WiFi y GSM/GPRS

Publicado por Andres (3 intervenciones) el 30/10/2019 04:00:43
Hola a todos, vengo analizando un par de códigos (para darme una idea para un proyecto) donde en uno se envían datos de temperatura a Internet a través de wifi y en el otro datos sobre el estado de una batería a través de una red gsm/gprs Estos son los códigos:

-Para Temperatura por wifi:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <WiFi.h>
#include <SoftwareSerial.h>                            // Librería Software Serial para utilizar otros pines como conexión serial
#include <OneWire.h>
#include <DallasTemperature.h>
 
const char* ssid     = "xxxxx";      // SSID
const char* password = "xxxxx";      // Password
const char* host = "192.168.1.x";  // Dirección IP local o remota, del Servidor Web
const int   port = 80;            // Puerto, HTTP es 80 por defecto, cambiar si es necesario.
const int   watchdog = 2000;        // Frecuencia del Watchdog
unsigned long previousMillis = millis();
 
String dato;
String cade;
String line;
 
int ID_TARJ=1;
 
// GPIO where the DS18B20 is connected to
const int oneWireBus = 4;
 
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);
 
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);
 
void setup() {
  Serial.begin(115200);
  Serial.print("Conectando a...");
  Serial.println(ssid);
 
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
 
  Serial.println("");
  Serial.println("WiFi conectado");
  Serial.println("Dirección IP: ");
  Serial.println(WiFi.localIP());
 
  // Start the DS18B20 sensor
  sensors.begin();
}
 
void loop() {
  unsigned long currentMillis = millis();
 
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
 
  sensors.requestTemperatures();
  float temperatureC = sensors.getTempCByIndex(0);
  Serial.print(temperatureC);
  Serial.println("ºC");
  delay(2000);
 
  if ( currentMillis - previousMillis > watchdog ) {
    previousMillis = currentMillis;
    WiFiClient client;
 
    if (!client.connect(host, port)) {
      Serial.println("Conexión falló...");
      return;
    }
 
    String url = "/temperatura/proceso_eventos/programa1.php?temperatura=";
    url += temperatureC;
    url += "&ID_TARJ=";
    url += ID_TARJ;
 
 
    // Envío de la solicitud al Servidor
    client.print(String("POST ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
    unsigned long timeout = millis();
    while (client.available() == 0) {
      if (millis() - timeout > 5000) {
        Serial.println(">>> Superado tiempo de espera!");
        client.stop();
        return;
      }
    }
 
    // Lee respuesta del servidor
    while(client.available()){
      line = client.readStringUntil('\r');
      Serial.print(line);
    }
      Serial.print("Dato ENVIADO");
      delay(4000);
 
  }
}


-Para estado de bateria por gsm/gprs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
// This program collects data (battery voltage) once per hour and reports it to a URL on the internet.
// To eliminate unecessary data usage, the data is reported using a HEAD method.
// Uses a SIM800L to connect to the GPRS network.
 
#include <SoftwareSerial.h>
#define GSM_TX 3
#define GSM_RX 4
#define GSM_RESET 2
#define BATTERY A3
#define STATUS 13
 
// Set the GPRS Access Point Name (APN) to suit your SIM card.
#define AccessPointName "hologram"
// Set the address of the server where the measurements should be reported.
#define HTTPserver "http://xyz.000webhostapp.com"
// Set the URL of the program that receives the measurements.
#define HTTPurl "/newdata.php?"
 
SoftwareSerial GSM_serial(GSM_RX, GSM_TX);
// Note that only GSM_TX is used. GSM_RX is not used.
 
void connect()
{
  GSM_serial.print("+++");
  delay(1000);
  GSM_serial.print("AT\r\n");
  delay(1000);
  GSM_serial.print("ATE1\r\n"); // Turn on echo, makes it easier to debug the SIM800L
  delay(1000);
  GSM_serial.print("AT+CGATT=1\r\n");
  delay(1000);
  GSM_serial.print("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"\r\n");
  delay(1000);
  GSM_serial.print("AT+SAPBR=3,1,\"APN\",\"");
  GSM_serial.print(AccessPointName);
  GSM_serial.print("\"\r\n");
  delay(1000);
  GSM_serial.print("AT+SAPBR=1,1\r\n");
  delay(3000);
}
 
void disconnect()
{
  GSM_serial.print("AT+SAPBR=0,1\r\n");
}
 
void HTTPhead(char *message)
{
  digitalWrite(STATUS, 1);
  connect();
  GSM_serial.print("AT+HTTPINIT\r\n");
  delay(1000);
  GSM_serial.print("AT+HTTPPARA=\"CID\",1\r\n");
  delay(1000);
  GSM_serial.print("AT+HTTPPARA=\"URL\",\"");
  GSM_serial.print(HTTPserver);
  GSM_serial.print(HTTPurl);
  GSM_serial.print(message);
  GSM_serial.print("\"\r\n");
  delay(1000);
  GSM_serial.print("AT+HTTPACTION=2\r\n"); // Request header only, reduces data usage
  delay(3000);
  GSM_serial.print("AT+HTTPTERM\r\n");
  disconnect();
  digitalWrite(STATUS, 0);
  delay(45000);  // To make function last 1 minute
}
 
void reset_GSM()
{
  digitalWrite(STATUS, 1);
  digitalWrite(GSM_RESET, 0);
  delay(100);
  digitalWrite(GSM_RESET, 1);
  digitalWrite(STATUS, 0);
  delay(59000);  // To make function last 1 minute
}
 
void low_power_GSM()
{
  GSM_serial.print("AT+CFUN=0,1\r\n");
  delay(60000);  // To make function last 1 minute
}
 
void full_power_GSM()
{
  GSM_serial.print("AT+CFUN=1,1\r\n");
  delay(60000);  // To make function last 1 minute
}
 
float battery_voltage() // Read the battery voltage
{
  float voltage = 0;
  for (int i=0; i<30; i++)
  {
    int batteryValue = analogRead(BATTERY);
    voltage += batteryValue * (16.128 / 1023.0); // This formula must be adjusted to suit the Vcc voltage
    delay(2000);                                 // and the avlues of the resistors used for measurement
  }                                              // Should be 16.0/1023.0 for Vcc=4v and perfectly equal resistors.
  return voltage/30; // To smooth out any noise, 30 samples are taken and the average is returned.
}
 
void setup()
{
  Serial.begin(9600);
  Serial.println("Reset");
 
  pinMode(GSM_RESET, OUTPUT);
  digitalWrite(GSM_RESET, 1);
 
  pinMode(STATUS, OUTPUT);
  digitalWrite(STATUS, 0);
 
  GSM_serial.begin(9600);
  reset_GSM();
}
 
void delay_minute()
{
  for (int i=0; i<60; i++) delay(1000);
}
 
void loop()  // Battery voltage measurement is reported once per hour.
{
  char buf[20];
 
  float bv = battery_voltage();            // Read battery voltage and convert to string "voltage=nn.n"
  dtostrf(bv, 3, 1, buf);
  String message = String("voltage=");
  message +=buf;
 
  full_power_GSM();                        // Move to full power mode to get ready to send data.
  message.toCharArray(buf, 20);            // Prepare message.
  HTTPhead(buf);                           // Report measurement by sending HEAD message to internet URL.
  reset_GSM();                             // Reset SIM800L to prevent unwanted data usage.
  low_power_GSM();                         // SIM800L uses a lot of power if it is left if full power mode.
  for (int i=0; i<55; i++) delay_minute(); // Wait an hour until the next report.
}


Mi duda es que según esto como se podría combinar el uso de wifi y el de red gsm/gprs para el envío de datos, de tal forma que si la primera no se encuentra disponible se pueda realizar mediante la segunda? Como dije antes, los he estado analizando pero no se me ocurre por donde empezar.
Gracias de antemano.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Leonardo
Val: 9
Ha disminuido su posición en 2 puestos en Arduino (en relación al último mes)
Gráfica de Arduino

Uso de redes WiFi y GSM/GPRS

Publicado por Leonardo (2 intervenciones) el 04/11/2019 19:42:45
Buenas tardes:

Sin entrar en el detalle de si este código te funciona o no (separadamente me refiero), la solución pasa por intentar en primer lugar la conexión con el servidor WIFI. Si la conexión no responde WL_CONNECTED, entonces tratas de usar el código de conexión con GPRS, tal y como tienes en el segundo proyecto.

Lo que no acierto a comprender es que quieres enviar datos al servidor, pero en tu código lo que haces es una consulta como si fuese un WebServer y pones un cliente a la espera de que te responda. Creo que debería ser...conectarte al servidor...enviarle la información del sensor o sensores conectados.

Siento no poder ayudarte más ya que no dispongo de hardware para GPRS y las placas wifi que tengo son ArduinoWifi 2.3 y tengo la impresión que tu lo tienes montado sobre un shield de arduino o un ArduinoYun.

No sé si te reultará útil la respuesta.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar