Detalles Técnicos
M-DUINO PLC Arduino Ethernet 57R I/Os Relay/Analog/Digital PLUS WIFI
VOLVER AL PRODUCTOInstalación Inicial
ARDUINO IDE
Arduino IDE es la plataforma original para programar placas Arduino. Esta aplicación multiplataforma está disponible en Windows, macOS y Linux y bajo la Licencia Pública General GNU. Arduino IDE admite la estructuración de código C y C ++.
Industrial Shields recomienda usar Arduino IDE para programar PLC basados en Arduino, pero cualquier software compatible con Arduino es compatible con los controladores Industrial Shields.
Aparte de eso, Industrial Shields brinda la posibilidad de seleccionar su PLC basado en Arduino en su IDE de Arduino y compilar sus bocetos para los diferentes PLC.
Descargue el IDE de Arduino 1.8.6:
Entradas y Salidas
ENTRADAS ANALÒGICAS
La variación de voltaje entre –Vcc (o GND) y + Vcc, puede tomar cualquier valor. Una entrada analógica proporciona una medición codificada en forma de valor digital con un número de N bits. En las E / S digitales y analógicas hay autoaislamiento, por lo que es posible conectarlas a una fuente de alimentación diferente a la de 24 V.
Entradas: (12x) Analógica (0-10Vdc) / Digital (5-24Vdc) configurable por software.
Know more about Analog Inputs.
TYPICAL CONNECTION
ENTRADAS DIGITALES
Variación de tensión de –Vcc (o GND) a + Vcc, sin valores intermedios. Dos estados: 0 (-Vcc o GND) y 1 (+ Vcc). En las E / S digitales y analógicas hay autoaislamiento, por lo que es posible conectarlas a una fuente de alimentación diferente a la de 24 V.
Entradas digitales nos proporciona entrada PNP.
Entradas: (6x) Digital Aislado (5-24Vdc) que puede funcionar como interrupción INT (7-24Vdc).
Know more about Digital Inputs.
TYPICAL CONNECTION
- Entrada digital aislada
- Entrada digital sin aislamiento
ENTRADAS DE INTERRUPCIÓN
Interrumpir la rutina del servicio. Mecanismo que permite asociar una función con la ocurrencia de un evento en particular. Cuando ocurre el evento, el procesador sale inmediatamente del flujo normal del programa y ejecuta la función ISR asociada ignorando cualquier otra tarea.
Entradas: (6x) Entradas de interrupción (5-24Vdc). “Puede funcionar como entrada digital (24Vdc)”.
Interruptor | Arduino Mega Pin | M-Duino Pin |
INT0 | 2 | I0.0 |
INT1 | 3 | I0.1 |
INT4 | 19 | I1.1 |
INT5 | 18 | I1.0 |
INT2 | 21 | I2.1 |
INT3 | 20 | I2.0 |
- I0.0 e I0.1 también como Pin3 y Pin2. Habilite las interrupciones encendiendo los interruptores número 3 y 4 de los interruptores de comunicación descendente.
- I1.0 e I1.0 también como Tx1 y Rx1. Habilitar interrupciones encendiendo los interruptores número 1 y 2 de los interruptores de comunicación.
- I2.0 and I2.1 also as SCA and SCL. Enable Interrupts turning ON the switches number 3 and 4 of up communication switches. In this case you won’t be able to use I2C.
TYPICAL CONNECTION
En este ejemplo activamos INT0 usando el pin I0_0 de la placa M-duino. Cuando hay un cambio
#define INTERRUPT I0_0 //other pins: I0_1, I0_6, I2_6, I2_5, I1_6, I1_5 (M-Duino) I0_0, I0_3, I0_2, I0_1 (Ardbox) volatile bool state = false; void setup() { pinMode(INTERRUPT, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(INTERRUPT), function_call_back, CHANGE); } void loop() { if (state == true){ Serial.println("Interrupt activated"); state = false; } } void function_call_back(){ //Change led state state = true; }
Communications
Ethernet
Ethernet is the technology that is most commonly used in wired local area networks ( LANs ).
Ethernet es la tecnología que se utiliza con mayor frecuencia en las redes de área local (LAN) cableadas. Una LAN es una red de computadoras y otros dispositivos electrónicos que cubre un área pequeña como una habitación, una oficina o un edificio. Se utiliza en contraste con una red de área amplia (WAN), que abarca áreas geográficas mucho más grandes.
Ethernet es un protocolo de red que controla cómo se transmiten los datos a través de una LAN. Técnicamente, se le conoce como protocolo IEEE 802.3. El protocolo ha evolucionado y mejorado con el tiempo para transferir datos a la velocidad de un gigabit por segundo.
Nuestra familia M-Duino incorpora el W5500 IC integrado.
El WX5500 es un controlador Ethernet integrado TCP / IP cableado que proporciona una conexión a Internet más sencilla para los sistemas integrados. Este chip permite a los usuarios tener conectividad a Internet en sus aplicaciones mediante el uso de un solo chip en el que están integrados la pila TCP / IP, 10/100 Ethernet MAC y PHY. El chip W5500 incorpora el búfer de memoria interna de 32 Kb para el procesamiento de paquetes Ethernet. Con este chip, los usuarios pueden implementar la aplicación Ethernet agregando el programa de conexión simple. Se proporciona SPI para una fácil integración con el microcontrolador externo.
Hardware
Configuración de hardware
*IMPORTANTE: Asegúrese de que su PLC Ethernet esté alimentado (12-24 V CC). Solo con USB no hay energía suficiente para encender el Comunicación Ethernet.
Configuración del interruptor
Para el protocolo de comunicación Ethernet no hay ningún conmutador que lo afecte. Por tanto, no importa la configuración del
conmutadores para implementar la comunicación Ethernet.
Pines usados
Para el protocolo de comunicación Ethernet, el pin Arduino Mega definido es el pin 10, que está conectado y ya internamente
ensamblado al controlador Ethernet WX5500. W5500 IC se comunica con la placa Mega a través del bus SPI ya ensamblado también.
Puede acceder fácilmente al puerto Ethernet en nuestros PLC Ethernet, que se encuentra en la parte superior de la capa de comunicaciones.
La configuración del hardware Ethernet debe ser plug and play.
Software
*IMPORTANTE: Asegúrate de descargar el Arduino based PLC boards para Arduino IDE.
Configuración de software:
Una vez realizada la configuración del hardware, es posible continuar con la configuración del software y también su uso. Primero es necesario incluir la librería Ethernet2.h proporcionada por Industrial Shields (tiene la misma funcionalidad que Ethernet.hy además
el mismo uso).
#include <Ethernet2.h>* Recuerde que para la versión V7 o versiones anteriores debe utilizar la biblioteca <Ethernet.h>.
Biblioteca Ethernet2 - funciones.
* La biblioteca Ethernet2.h tiene las mismas funciones que Ethernet.h.
Para la comunicación Ethernet hay 3 protocolos disponibles:
- Ethernet con HTTP. to know more.
- Ethernet con MQTT, to know more.
- Ethernet con Modbus TCP/IP.
- Master, know more.
- Slave, know more.
Códigos de ejemplo:
Echo TCP Server:
Una vez que el servidor se está ejecutando, cualquier cliente puede conectarse al servidor. En este ejemplo se utiliza un M-Duino para generar el servidor. El ejemplo de cliente TCP mostrado anteriormente podría ser uno de los clientes.
A continuación se muestra el código IDE de Arduino:
// use Ethernet.h if you have a M-Duino V7 version
#include <Ethernet2.h>
// mac address for M-Duino
byte mac[] = { 0xBE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// Ip address for M-Duino
byte ip[] = { 192, 168, 1, 100 };
int tcp_port = 5566;
EthernetServer server = EthernetServer(5566);
void setup()
{
// initialize the ethernet device
Ethernet.begin(mac, ip);
// start server for listenign for clients
server.begin();
}
void loop()
{
// if an incoming client connects, there will be bytes available to read:
EthernetClient client = server.available();
if (client.available()) {
// read bytes from the incoming client and write them back
// to the same client connected to the server
client.write(client.read());
}
}
Echo TCP Client:
Una vez que el servidor se está ejecutando, M-Duino puede conectarse al servidor. En este ejemplo, se usa un M-Duino para conectarse con el servidor Node.js llamado server.js, el mismo que se usó en el enlace del ejemplo anterior.
Para configurar el M-Duino, esta publicación solo sigue el ejemplo de TCP del sitio web de Arduino con algunos cambios. Para poder conectarnos al servidor debemos conocer la IP del servidor TCP y el puerto donde este servidor está escuchando.
A continuación se muestra el código Arduino:
#include <Ethernet2.h>
#include <SPI.h>
byte mac[] = { 0xBE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 100 };
byte server[] = { 192, 168, 1, 105 }; // Touchberry Pi Server
int tcp_port = 5566;
EthernetClient client;
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println("Connecting...");
if (client.connect(server, tcp_port)) { // Connection to server.js
Serial.println("Connected to server.js");
client.println();
} else {
Serial.println("connection failed");
}
}
void loop()
{
if (client.available()) {
if(Serial.available()){
char s = Serial.read();
client.write(s); // Send what is reed on serial monitor
char c = client.read();
Serial.print(c); // Print on serial monitor the data from server
}
}
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
for(;;) ;
}
}
Serial TTL
Interfaz de comunicación entre dos dispositivos con bajo nivel de voltaje. Un puerto serial envía datos por una secuencia de bits.
Dos señales: Tx (transmisión de datos) y Rx (recepción de datos).
M-Duino tiene dos puertos TTL, RX0 / TX0, RX1 / TX1. Se accede a TTL0 con la función Serial (pines 0 y 1 del Arduino Mega). Se accede a TTL1 con la función Serial1 (pines 18 y 19 del Arduino Mega).
IMPORTANTE: Serial1 se utiliza para la comunicación Wi-Fi modular.
Hardware
IMPORTANTE: Asegúrese de que su PLC Ethernet esté alimentado (12-24 V CC).
Configuración del interruptor
Para lograr la comunicación Serial TTL no hay ningún interruptor que lo afecte, siempre está habilitado. Por lo que no importa la configuración de los switches para implementar la comunicación Serial TTL.
Pines usados
MDuino Ethernet PLC Pinout | Arduino Mega Pinout |
Tx 0 | 0 |
Rx 0 | 1 |
Tx 1 | 18 |
Rx 1 | 19 |
Software
IMPORTANTE: Asegúrate de descargar el Arduino based PLC boards para Arduino IDE.
Configuración de software
Una vez que se realiza la configuración del hardware, es posible continuar con la configuración del software y también su uso. Primero es necesario incluir la librería RS232.h proporcionada en nuestras placas. Entonces, no olvide implementar la inicialización adecuada de su comunicación en la función setup():
Serial.begin(9600);
Ejemplo de escritura de TTL serial básico
Lee una entrada analógica en Tx0 (pin 0), imprime el resultado en el monitor serial.
La representación gráfica está disponible usando el trazador en serie (menú Herramientas> Trazador en serie) en el monitor en serie Arduino IDE.
// the setup routine runs once when you press reset:
void setup() {
pinMode(I0_2, INPUT);
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(I0_2);
// print out the value you read:
Serial.println(sensorValue);
delay(1); // delay in between reads for stability
}
I2C
I2C es un protocolo sincrónico. Solo utiliza 2 cables, uno para el reloj (SCL) y otro para los datos (SDA). Esto significa que el maestro y el esclavo envían datos a través del mismo cable, que es controlado por el maestro, quien crea la señal de reloj. I2C no utiliza la selección de esclavos, sino el direccionamiento.
I2C es un bus de comunicaciones en serie. La velocidad es de 100 kbit / s en modo estándar, pero también permite velocidades de 3,4 Mbit / s. Es un bus muy utilizado en la industria, principalmente para comunicar microcontroladores y sus periféricos en sistemas integrados y generalizando más para comunicar circuitos integrados entre sí que normalmente residen en un mismo circuito impreso.
Hardware
IMPORTANTE: Asegúrese de que su PLC Ethernet esté alimentado (12-24 V CC).
Configuración del interruptor
Para lograr la comunicación I2C no hay ningún interruptor que lo afecte, siempre está habilitado. Por tanto, no importa la configuración de los conmutadores para implementar la comunicación I2C.
Pines usados
MDuino Ethernet PLC Pinout | Arduino Mega Pinout |
SDA | 20 |
SCL | 21 |
Software
IMPORTANTE: Asegúrate de descargar el Arduino based PLC boards para Arduino IDE.
#include <Wire.h> void setup() { Wire.begin(); // join i2c bus (address optional for master) } byte x = 0; void loop() { Wire.beginTransmission(8); // transmit to device #8 Wire.write("x is "); // sends five bytes Wire.write(x); // sends one byte Wire.endTransmission(); // stop transmitting x++; delay(500); }
#include <Wire.h> void setup() { Wire.begin(8); // join i2c bus with address #8 Wire.onReceive(receiveEvent); // register event Serial.begin(9600); // start serial for output } void loop() { delay(100); } // function that executes whenever data is received from master // this function is registered as an event, see setup() void receiveEvent(int howMany) { while (1 < Wire.available()) { // loop through all but the last char c = Wire.read(); // receive byte as a character Serial.print(c); // print the character } int x = Wire.read(); // receive byte as an integer Serial.println(x); // print the integer }
Know more about I2C.
Wi-Fi/Bluetooth
Wi-Fi es uno de los desarrollos tecnológicos más importantes de la era moderna. Al igual que otros tipos de conexión inalámbrica, como Bluetooth, es una tecnología de transmisión de radio que se basa en un conjunto de estándares para permitir comunicaciones seguras y de alta velocidad entre una amplia variedad de dispositivos digitales, puntos de acceso y hardware. Hace posible que los dispositivos con capacidad Wi-Fi accedan a Internet sin la necesidad de cables restrictivos. Puede operar en distancias cortas y largas, estar bloqueado y asegurado, o abierto y libre. Es increíblemente versátil y fácil de usar.
Bluetooth es otro estándar de tecnología inalámbrica. Bluetooth se desarrolló como una forma de intercambiar datos en un rango corto. Opera en el rango de 2400-2483,5 MHz dentro de la banda de frecuencia ISM de 2,4 GHz. Los datos se dividen en paquetes y se intercambian a través de uno de los 79 canales Bluetooth diseñados (cada uno de los cuales tiene 1 MHz de ancho de banda).
Nuestra familia M-Duino incorpora el módulo ESP32 WiFi / Bluetooth.
En el next bloc it's explained how it works
SPI
These pins can only work as a 5V pins if the Ethernet protocol is not going to be used. As the Ethernet protocol uses the SPI to communicate with the Arduino board, both behaviours cannot happen at the same time as the Ethernet would not work.
These pins are not stablished with a pull-up or a pull-down configuration. The state of thesepins is unknown. If these pins must be used, they require a pull-up or a pull-downconfiguration. The Arduino board allows the pins to be set in a pull-up configuration. If not itmust be stablished an external pull-up or pull-down circuit in order to correctly work with these pins.
Hardware
IMPORTANTE: Asegúrese de que su PLC Ethernet esté alimentado (12-24 V CC).
Configuración del interruptor
To achieve SPI communication there isn't any switch that affects it, it is always enabled. So it does not matter the configuration of the switches to implement SPI communication.
Used pins
For Serial communication protocol the defined Arduino Mega pins are showed in the chart below. For SPI bus MISO, MOSI and CLOCK pins are
common to all the connected devices to the M-Duino, conversely, each of the connected devices will have a single and dedicated SS pin.
Function | M-Duino connection | Arduino Mega Pinout |
MISO | SO | 50 |
MOSI | SI | 51 |
CLOCK | SCK | 52 |
RST | Reset | Reset |
IMPORTANTE: Asegúrate de descargar el Arduino based PLC boards para Arduino IDE.
// inslude the SPI library: #include <SPI.h> // set pin 10 as the slave select for the digital pot: const int slaveSelectPin = 10; void setup() { // set the slaveSelectPin as an output: pinMode(slaveSelectPin, OUTPUT); // initialize SPI: SPI.begin(); } void loop() { // go through the six channels of the digital pot: for (int channel = 0; channel < 6; channel++) { // change the resistance on this channel from min to max: for (int level = 0; level < 255; level++) { digitalPotWrite(channel, level); delay(10); } // wait a second at the top: delay(100); // change the resistance on this channel from max to min: for (int level = 0; level < 255; level++) { digitalPotWrite(channel, 255 - level); delay(10); } } } void digitalPotWrite(int address, int value) { // take the SS pin low to select the chip: digitalWrite(slaveSelectPin, LOW); // send in the address and value via SPI: SPI.transfer(address); SPI.transfer(value); // take the SS pin high to de-select the chip: digitalWrite(slaveSelectPin, HIGH); }Know more about SPI.
Special Functions
RTC
The term real-time clock is used to avoid confusion with ordinary hardware clocks which are only signals that govern digital electronics, and do not count time in human units. RTC should not be confused with real-time computing, which shares the acronym but does not directly relate to time of day.
Although keeping time can be done without an RTC, using one has benefits:
- Low power consumption (important when running from alternate power
- Frees the main system for time-critical tasks
- Sometimes more accurate than other methods
There is a 3,3V lithium coin cell battery supplying the RTC. M-Duinos RTC Module is based on the DS1307 Chip . The DS1307 serial real-time clock (RTC) is a lowpower, full binary-coded decimal (BCD) clock/calendar plus 56 bytes of NV SRAM. Address and data are transferred serially through an I2C , bidirectional bus. The clock/calendar provides seconds, minutes, hours, day, date, month, and year information. The end of the month date is automatically adjusted for months with fewer than 31 days, including corrections for leap year. The clock operates in either the 24-hour or 12-hour format with AM/PM indicator. The DS1307 has a built-in power-sense circuit that detects power failures and automatically switches to the backup supply. Timekeeping operation continues while the part operates from the backup supply.
Hardware Configuration
IMPORTANT: Make sure that your Ethernet PLC is powered (12-24Vdc) .
Switch configuration
RTC works with the I2C protocol communication, so it is required to have enabled the I2C protocol.
4 switches have to be configured in order to enable the RTC features and I2C communication:
SWITCH | ON | OFF |
4 | NC |
NC |
3 | NC |
NC |
2 | RTC | - |
1 | RTC | - |
RTC SCL & RTC SDA must be set to ON mode to enable the I2C wires to the RTC. If they are in OFF mode, the Arduino won’t communicate with the RTC.
Software Configuration
Once the hardware configuration is done, it's possible to proceed with the software configuration and also its usage. Firstable it's necessary to include the RTC.h library provided in our boards (RTC.h includes I2C.h initialitzation, so it will not be necessary to initialize the I2C.h library):
#include <RTC.h>
To check if the RTC port is working it is easy to use the serial monitor from the Arduino IDE using the right sentence inside the setup() function:
#Serial.begin(9600L)
Example Code
Basic RTC Test
// RTC library example // by Industrial Shields #include <RTC.h> //////////////////////////////////////////////////////////////////////////////////////////////////// void setup() { Serial.begin(9600L); } /////////////////////////////////////////////////////////////////////////////////////////////////// void loop() { if (!RTC.read()) { Serial.println("Read date error: is time set?"); } else { Serial.print("Time: "); Serial.print(RTC.getYear()); Serial.print("-"); Serial.print(RTC.getMonth()); Serial.print("-"); Serial.print(RTC.getMonthDay()); Serial.print(" "); Serial.print(RTC.getHour()); Serial.print(":"); Serial.print(RTC.getMinute()); Serial.print(":"); Serial.print(RTC.getSecond()); Serial.print(" ("); Serial.print(RTC.getTime()); Serial.println(")"); } delay(1000); }