#5 Enviar datos RS485
Una vez implementadas las acciones básicas, también es posible crear otras más complejas, como las comunicaciones RS-232/RS-485/RS-422. Este capítulo te explica cómo enviar datos RS-485 desde la aplicación web, aunque también es posible mostrar los datos recibidos por RS-485.
Agregar el campo RS-485
El primer paso podría ser agregar un formulario HTML para enviar los datos RS-485 al PLC. En este caso, se agrega un campo de entrada HTML para escribir datos alfanuméricos. Cuando se hace clic en el botón de enviar, se llama a la función sendRS485(). ¡Esta función todavía no existe! Se creará en el siguiente paso.
<form action='javascript:void(0)' onsubmit='sendRS485()'> Data: <input type='text' pattern='[a-zA-Z0-9]+' title='Alphanumeric string' value='' id='rs485Data'> <input type='submit' value='Send'> </form>
<form action='javascript:void(0)' onsubmit='sendRS485()'> Data: <input type='text' pattern='[a-zA-Z0-9]+' title='Alphanumeric string' value='' id='rs485Data'> <input type='submit' value='Send'> </form>
Función de envío JavaScript
function sendRS485() {
var el = document.getElementById('rs485Data');
if (el) {
var xhttp = new XMLHttpRequest();
xhttp.open('GET', '/rs485/' + el.value, true);
xhttp.send();
}
}
function sendRS485() {
var el = document.getElementById('rs485Data');
if (el) {
var xhttp = new XMLHttpRequest();
xhttp.open('GET', '/rs485/' + el.value, true);
xhttp.send();
}
}
Interpretar la solicitud
Los datos RS-485 están contenidos en la URL de la solicitud. El sketch debe analizarla para obtener los datos que hay que enviar. Cuando la URL empieza por la cadena "/rs485/", se considera una solicitud de datos que se deben enviar por RS-485, así que el sketch elimina el comienzo de la URL para obtener los datos RS-485. Como el cliente ignora la respuesta, solo se envía el texto OK.
// ... } else if (path.startsWith("/rs485/")) { // Get data from the request String data = path.substring(7); // Send a response sendText(client, "OK"); // ...
// ... } else if (path.startsWith("/rs485/")) { // Get data from the request String data = path.substring(7); // Send a response sendText(client, "OK"); // ...
Configurar RS-485
Antes de enviar datos a través de RS-485, es obligatorio iniciar el controlador utilizando la función RS485.begin() en setup(). Esta función está disponible después de incluir la librería RS485.h.
<#include rs485.h>
<#include rs485.h>
// ... RS485.begin(9600); // ...
// ... RS485.begin(9600); // ...
Enviar datos a través de RS-485
Se llama a la función RS485.write() para enviar datos a través del RS-485.
// ... } else if (path.startsWith("/rs485/")) { // Get data from the request String data = path.substring(7);
// Send data through RS-485
RS485.write(data.c_str());
// Send a response
sendText(client, "OK");
} else { // ...
// ... } else if (path.startsWith("/rs485/")) { // Get data from the request String data = path.substring(7);
// Send data through RS-485
RS485.write(data.c_str());
// Send a response
sendText(client, "OK");
} else { // ...
Ejemplo final
#include <RS485.h>
#include <Ethernet2.h>
// Server creation
EthernetServer server(80);
void setup() {
Serial.begin(9600UL);
Serial.println("WebServer started");
// RS-485 initialization
RS485.begin(9600);
// Ethernet initialization
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
byte ip[] = {10, 10, 10, 25};
Ethernet.begin(mac, ip);
// Server initialization
server.begin();
}
void loop() {
// Wait for clients
EthernetClient client = server.available();
if (client) {
// Parse request
bool emptyLine = true;
String header;
bool firstLine = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
if (firstLine) {
header += c;
}
// The request is finished when an empty line is received
if (emptyLine && (c == '\n')) {
// Get path from the header line
int pos = header.indexOf(' ');
String path = header.substring(pos + 1, header.indexOf(' ', pos + 1));
// Act depending on path
if (path.compareTo("/") == 0) {
sendMainPage(client);
}
else if (path.compareTo("/setOutput") == 0) {
// Set output
digitalWrite(Q0_0, HIGH);
// Redirect response
redirectToMainPage(client);
} else if (path.compareTo("/clearOutput") == 0) {
// Clear output
digitalWrite(Q0_0, LOW);
// Redirect response
redirectToMainPage(client);
} else if (path.compareTo("/inputValue") == 0) {
// Get the input value
int inputValue = digitalRead(I0_1);
// Send input value
sendText(client, inputValue == HIGH ? "HIGH" : "LOW");
} else if (path.startsWith("/rs485/")) {
// Get data from the request
String data = path.substring(7);
// Send data through RS-485
RS485.write(data.c_str());
// Send a response
sendText(client, "OK");
} else {
// Unrecognized path
sendNotFound(client);
}
client.flush();
// Close connection
client.stop();
break;
}
// The request is finished when a blank line is received
if (c == '\n') {
emptyLine = true;
firstLine = false;
} else if (c != '\r') {
emptyLine = false;
}
}
}
}
}
void sendNotFound(EthernetClient &client) {
// Path not found
client.println("HTTP/1.1 404 Not Found");
client.println("Content-Type: text/plain");
client.println();
client.println("404 Not Found");
}
void redirectToMainPage(EthernetClient &client) {
// Redirect to main page
client.println("HTTP/1.1 303 See Other");
client.println("Location: /");
client.println();
}
void sendMainPage(EthernetClient &client) {
// Send the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
client.println(
"<!doctype html>"
"<html>"
"<head>"
"<title>Hello PLC!</title>"
"</head>"
"<body>"
"<h1>Hello PLC!</h1>"
"<a href='/setOutput'>Set output</a><br>"
"<a href='/clearOutput'>Clear output</a><br>"
"<p>Input value: <span id='input-value'></span></p>"
"<form action='javascript:void(0)' onsubmit='sendRS485()'>"
"Data: <input type='text' pattern='[a-zA-Z0-9]+' title='Alphanumeric string' value='' id='rs485Data'>"
"<input type='submit' value='Send'>"
"</form>"
"<script>"
"function updateInputValue() {"
" var xhttp = new XMLHttpRequest();"
" xhttp.onreadystatechange = function() {"
" if (this.readyState == 4 && this.status == 200) {"
" document.getElementById('input-value').innerHTML = this.responseText;"
" }"
" };"
" xhttp.open('GET', 'inputValue', true);"
" xhttp.send();"
"}"
"setInterval(updateInputValue, 1000);"
"function sendRS485() {"
" var el = document.getElementById('rs485Data');"
" if (el) {"
" var xhttp = new XMLHttpRequest();"
" xhttp.open('GET', '/rs485/' + el.value, true);"
" xhttp.send();"
" }"
"}"
"</script>"
"</body>"
"</html>"
);
}
void sendText(EthernetClient &client, const char *text) {
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/plain");
client.println();
client.println(text);
}
#include <RS485.h>
#include <Ethernet2.h>
// Server creation
EthernetServer server(80);
void setup() {
Serial.begin(9600UL);
Serial.println("WebServer started");
// RS-485 initialization
RS485.begin(9600);
// Ethernet initialization
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
byte ip[] = {10, 10, 10, 25};
Ethernet.begin(mac, ip);
// Server initialization
server.begin();
}
void loop() {
// Wait for clients
EthernetClient client = server.available();
if (client) {
// Parse request
bool emptyLine = true;
String header;
bool firstLine = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
if (firstLine) {
header += c;
}
// The request is finished when an empty line is received
if (emptyLine && (c == '\n')) {
// Get path from the header line
int pos = header.indexOf(' ');
String path = header.substring(pos + 1, header.indexOf(' ', pos + 1));
// Act depending on path
if (path.compareTo("/") == 0) {
sendMainPage(client);
}
else if (path.compareTo("/setOutput") == 0) {
// Set output
digitalWrite(Q0_0, HIGH);
// Redirect response
redirectToMainPage(client);
} else if (path.compareTo("/clearOutput") == 0) {
// Clear output
digitalWrite(Q0_0, LOW);
// Redirect response
redirectToMainPage(client);
} else if (path.compareTo("/inputValue") == 0) {
// Get the input value
int inputValue = digitalRead(I0_1);
// Send input value
sendText(client, inputValue == HIGH ? "HIGH" : "LOW");
} else if (path.startsWith("/rs485/")) {
// Get data from the request
String data = path.substring(7);
// Send data through RS-485
RS485.write(data.c_str());
// Send a response
sendText(client, "OK");
} else {
// Unrecognized path
sendNotFound(client);
}
client.flush();
// Close connection
client.stop();
break;
}
// The request is finished when a blank line is received
if (c == '\n') {
emptyLine = true;
firstLine = false;
} else if (c != '\r') {
emptyLine = false;
}
}
}
}
}
void sendNotFound(EthernetClient &client) {
// Path not found
client.println("HTTP/1.1 404 Not Found");
client.println("Content-Type: text/plain");
client.println();
client.println("404 Not Found");
}
void redirectToMainPage(EthernetClient &client) {
// Redirect to main page
client.println("HTTP/1.1 303 See Other");
client.println("Location: /");
client.println();
}
void sendMainPage(EthernetClient &client) {
// Send the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
client.println(
"<!doctype html>"
"<html>"
"<head>"
"<title>Hello PLC!</title>"
"</head>"
"<body>"
"<h1>Hello PLC!</h1>"
"<a href='/setOutput'>Set output</a><br>"
"<a href='/clearOutput'>Clear output</a><br>"
"<p>Input value: <span id='input-value'></span></p>"
"<form action='javascript:void(0)' onsubmit='sendRS485()'>"
"Data: <input type='text' pattern='[a-zA-Z0-9]+' title='Alphanumeric string' value='' id='rs485Data'>"
"<input type='submit' value='Send'>"
"</form>"
"<script>"
"function updateInputValue() {"
" var xhttp = new XMLHttpRequest();"
" xhttp.onreadystatechange = function() {"
" if (this.readyState == 4 && this.status == 200) {"
" document.getElementById('input-value').innerHTML = this.responseText;"
" }"
" };"
" xhttp.open('GET', 'inputValue', true);"
" xhttp.send();"
"}"
"setInterval(updateInputValue, 1000);"
"function sendRS485() {"
" var el = document.getElementById('rs485Data');"
" if (el) {"
" var xhttp = new XMLHttpRequest();"
" xhttp.open('GET', '/rs485/' + el.value, true);"
" xhttp.send();"
" }"
"}"
"</script>"
"</body>"
"</html>"
);
}
void sendText(EthernetClient &client, const char *text) {
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/plain");
client.println();
client.println(text);
}
No se permite comentar en este curso.