Busca en nuestro Blog. Encontrarás múltiples aplicaciones, soluciones, ejemplos de código. Navega utilizando la nube de etiquetas o busca utilizando criterios específicos

Solicitudes HTTP a un servidor utilizando un PLC basado en Arduino

Trabajar con servidores externos usando Industrial Arduino Solutions

Introducción

In this post we will show you how to perform HTTP requests with the POST method to send information to an external server.

The information is received from analog data of a potentiometer filtered by software. 
If you want to know more about analog data filtering do not hesitate to seguir este post!

Requisitos

Ethernet PLC or 20 I/Os PLC:
Ethernet PLC >>     20 I/Os PLC >>

ArduinoHTTPClient library:
Download ArduinoHTTPClient library on Github >>

Industrial Shields Power supply:
Industrial Shields Accessories >>

Industrial Shields boards:
Install Industrial Shields boards >>


Connections
Para conocer la parte relacionada con la conexión del potenciómetro,  el filtrado de datos analógicos y también el registro de datos de la tarjeta SD,  siga esta entrada de blog. this blog post.

The Ethernet PLC will act as a client making write requests to the server to send the analog data received periodically. This will be connected via Ethernet to a Router with access to the server where the received data is written.


So that, at the Hardware level we will only require an ethernet connection between the Arduino-based PLC and the server.


Software

Este còdigo crea un cliente en nuestro PLC basado en Arduino responsable de hacer solicitudes POST a la ruta URL compuesta de servidor IP + "/ analog-value": 192.168.1.209:1880/analog-value.

Los valores que mostraremos en el servidor serán los resultados analógicos filtrados recibidos de un potenciómetro conectado a un PLC basado en Arduino para poder probar el funcionamiento global de esta prueba.  

The post requests that the server waits follows this structure: {"value": data}.
 

/*

 Copyright (c) 2018 Boot&Work Corp., S.L. All rights reserved


   This program is free software: you can redistribute it and/or modify

   it under the terms of the GNU Lesser General Public License as published by

   the Free Software Foundation, either version 3 of the License, or

   (at your option) any later version.


   This program is distributed in the hope that it will be useful,

   but WITHOUT ANY WARRANTY; without even the implied warranty of

   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

   GNU Lesser General Public License for more details.


   You should have received a copy of the GNU Lesser General Public License

   along with this program.  If not, see <http://www.gnu.org/licenses/>.

 */

#include <ArduinoHttpClient.h>
#include <Ethernet.h>
#include <SD.h>
#include <Filter.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; 
IPAddress server(192,168,1,209); 

int port = 1880;

Sd2Card card;
SdVolume volume;

AnalogFilter<5, 2> aFilter;

EthernetClient ether;
HttpClient client = HttpClient(ether,server,port);
String response;


void setup() {
  Serial.begin(9600);
  // Ethernet.begin(mac,ip,dnsServer,gateway,subnet);
  Ethernet.begin(mac);
  Serial.print("IP: ");
  Serial.println(Ethernet.localIP());
  if (!SD.begin(53)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    while (1);
  }
  Serial.println("card initialized.");
}


void loop() {
  int data = analogRead(I0_12);
   int filtered = aFilter.update(data);
  static uint32_t lastPrint = millis();
  if (millis() - lastPrint > 3000) {
    Serial.println(filtered);
    lastPrint = millis();
    logToSd(filtered);
    String postData = "{\"value\":" + String(filtered) + "}";

    client.beginRequest();
    client.post("/analog-value");
    client.sendHeader("Content-Type", "application/json");
    client.sendHeader("Content-Length", postData.length());
    client.beginBody();
    client.print(postData);
    client.endRequest();

    int statusCode = client.responseStatusCode();
    client.stop();

    Serial.println(statusCode);   //Prints the HTTP status response - 200 if OK
    Serial.println("Data to the Server");
    Serial.println("Wait one seconds");
   }
}

void logToSd(int value){
  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("datalog.txt", FILE_WRITE);
 

  // if the file is available, write to it:
  if (dataFile) {
    dataFile.println(value);
    dataFile.close();
  }
  
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening datalog.txt");
  }
}

Solicitudes HTTP a un servidor utilizando un PLC basado en Arduino 


 
 


¿Quieres más información?

Con la tecnología Open Source, puedes ejecutar tus propias instalaciones.

Rellena el formulario y contactaremos contigo lo más pronto posible.

Enviar  Por favor, completa el formulario correctamente.