Introducción
Con la Librería SimpleComm, puedes enviar datos a través de cualquier flujo de Arduino: RS-485, RS-232, Ethernet... Es lo suficientemente flexible como para soportar diferentes tipos de tipologías de comunicación: Ad-hoc, Maestro-Esclavo, Cliente-Servidor... Utilizando una API fácil de usar. La Librería SimpleComm está incluida enSimpleComm library.
Uso de SimpleComm
SimplePacket encapsula los datos en un paquete y proporciona estas funciones:
setData(data)
Rellenar el paquete con los datos enviados deseados o los datos recibidos de un dispositivo remoto. Es posible rellenar el paquete con diferentes tipos de datos: bool, char, unsigned char, int, unsigned int, long, unsigned long, double, const, const char, const void (la longitud máxima de los datos es de 128 bytes).
getBool()
getChar()
getUChar()
getInt()
getUInt()
getLong()
getLong()
getDouble()
getString()
getData(len)
Devuelve los datos contenidos en el paquete, según el tipo de datos. Si se especifica la longitud, devuelve la longitud de los datos en bytes.
SimpleComm es la interfaz para enviar y recibir paquetes a través de la corriente deseada de Arduino:
begin(address)
Habilita el sistema de comunicación y configura el identificador/dirección del dispositivo. La dirección se utiliza para identificar cada dispositivo. El dispositivo recibe los paquetes que se le envían, pero no a los demás.
send(stream, packet, destination)
send(stream, packet, destination, type)
Enviar un paquete a un dispositivo de destino, utilizando el flujo. También es posible definir el tipo de paquete.
receive(stream, packet)
Recibe un paquete enviado desde otro dispositivo, utilizando el flujo. Devuelve true si se recibe un paquete.
Léeme
#include <SimpleComm.h>
El módulo SimpleComm envía y recibe datos a través de cualquier flujo de Arduino: RS-485, RS-232, Ethernet... Es lo suficientemente flexible como para soportar diferentes tipos de comunicación: Ad-hoc, Maestro-Esclavo, Cliente-Servidor, etc., utilizando una API fácil de usar.
La clase SimplePacket encapsula los datos en un paquete.
La función setData
rellena el paquete con los datos deseados para enviarlo a un dispositivo remoto. Es posible rellenar el paquete con diferentes tipos de datos: bool, char, unsigned char, int, unsigned int, long, unsigned long, double, string e incluso tipos de datos personalizados.
int num = 1234;
SimplePacket packet1;
packet1.setData(num);
SimplePacket packet2;
packet2.setData("text data");
typedef struct {
int a;
char b;
} customType;
customType customVar;
customVar.a = 1234;
customVar.b = 'B';
SimplePacket packet3;
packet3.setData(customVar, sizeof(customVar));
Sus funciones anteriores devuelven los datos contenidos en el paquete, dependiendo del tipo de datos. Si se especifica la longitud, se devuelve la longitud de los datos en bytes.
int num = packet1.getInt();
const char *str = packet2.getString();
const customType *var = (const customType*) packet3.getData();
La clase SimpleComm es la interfaz para enviar y recibir paquetes a través de la corriente deseada de Arduino.
La función .begin(byte)
habilita el sistema de comunicación y establece el identificador/dirección de los dispositivos. Cada dispositivo tiene su propia dirección que lo identifica. Los dispositivos reciben paquetes enviados a ellos, utilizando su dirección, pero no a otros.
byte address = 1234;SimpleComm.begin(address);
Es posible enviar paquetes a un dispositivo con una dirección, y opcionalmente definir el tipo de paquete.
byte destination = 87;
SimpleComm.send(RS485, packet, destination);
SimpleComm.send(RS485, packet, destination, 0x33);
Para enviar paquetes a todos sus dispositivos, es posible enviar un paquete de difusión con el campo de destino establecido en 0 (cero).
byte destination = 0;
SimpleComm.send(RS485, packet, destination);
La función receive the recibe un paquete desde otro dispositivo, utilizando el stream. Devuelve true si realmente se recibe un paquete.
SimplePacket rxPacket;
if (SimpleComm.receive(RS485, rxPacket)) {
// A packet is received
}
También es posible recibir todos los paquetes (modo sniffer) poniendo la dirección de SimpleComm a 0 (cero). Este modo es útil cuando se implementa un nodo pasarela entre Ethernet y RS-485.
byte address = 0;
SimpleComm.begin(address);
Ejemplo
En este ejemplo, estamos intentando conectarnos a través de un puerto Ethernet a un servidor TCP utilizando la Librería SimpleComm y diferentes tipos de mensajes (Puedes ver más ejemplos en github).
/* | |
Copyright (c) 2017 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/>. | |
*/ | |
#if defined(MDUINO_PLUS) | |
#include <Ethernet2.h> | |
#else | |
#include <Ethernet.h> | |
#endif | |
#include <SimpleComm.h> | |
// You can define different types of messages. | |
// Here is an example: | |
#define PRINT_TEXT_TYPE 0x01 // Used for receiving text and print it | |
#define DIGITAL_OUTPUT_TYPE 0x02 // Used for setting the digital output Q0.0 | |
#define DIGITAL_INPUT_TYPE 0x03 // Used for printing the value of the digital input I0.0 | |
// Create SimplePacket for receiving data | |
SimplePacket packet; | |
// Define Ethernet values | |
byte mac[] = {0xDE, 0xAD, 0xBE, 0x75, 0x24, 0x01}; | |
// TCP server for receiving messages | |
EthernetServer server(64321); | |
// Define my SimpleComm address | |
uint8_t myAddress = 1; | |
//////////////////////////////////////////////////////////////////////////////////////////////////// | |
void setup() { | |
Serial.begin(9600L); | |
// Set IOs configuration | |
pinMode(Q0_0, OUTPUT); | |
pinMode(I0_0, INPUT); | |
// Start SimpleComm | |
SimpleComm.begin(myAddress); | |
// Start Ethernet interface using DCHP for getting an IP address | |
Ethernet.begin(mac); | |
Serial.print("IP address: "); | |
Serial.println(Ethernet.localIP()); | |
// Start TCP server | |
server.begin(); | |
} | |
//////////////////////////////////////////////////////////////////////////////////////////////////// | |
void loop() { | |
// Wait for TCP connections | |
EthernetClient client = server.available(); | |
if (client) { | |
// Receive packets from the connected client | |
if (SimpleComm.receive(client, packet)) { | |
Serial.print("Received packet from: "); | |
Serial.println(packet.getSource(), HEX); | |
// Depending on the received packet type, do one of the actions below | |
switch (packet.getType()) { | |
case PRINT_TEXT_TYPE: | |
// Print the received data as a text value | |
Serial.print("Text: "); | |
Serial.println(packet.getString()); | |
break; | |
case DIGITAL_OUTPUT_TYPE: | |
// Set Q0.0 value depending on the received data (as a boolean value) | |
// true: HIGH, false: LOW | |
Serial.print("Set Q0.0 to "); | |
Serial.println(packet.getBool() ? "HIGH" : "LOW"); | |
digitalWrite(Q0_0, packet.getBool() ? HIGH : LOW); | |
break; | |
case DIGITAL_INPUT_TYPE: | |
// Print I0.0 value: HIGH or LOW | |
Serial.print("I0.0 value: "); | |
Serial.println(digitalRead(I0_0) == HIGH ? "HIGH" : "LOW"); | |
break; | |
default: | |
// Treat unknown packet type too | |
Serial.print("Received unknown packet type: "); | |
Serial.println(packet.getType()); | |
break; | |
} | |
} | |
} | |
} |
Librería Simplecomm para el envío de datos a través de un flujo de PLCs en Arduino