Ir al contenido

M-DUINO ETHERNET PLC ARDUINO 19R

El PLC M-Duino 19R basado en ARDUINO es un controlador industrial robusto y flexible con salidas de relé integradas, diseñado para simplificar la automatización en entornos profesionales.

Su arquitectura de código abierto garantiza control total sobre la aplicación, mientras que la compatibilidad con el Arduino IDE permite un desarrollo rápido, mantenimiento sencillo y libertad respecto a licencias de software propietario.

Gracias a su diseño modular y relés integrados, es ideal para el control directo de actuadores industriales, reduciendo la complejidad del cableado y los costes de componentes externos. Una opción inteligente para sistemas de automatización industrial escalables y rentables.

6x Entradas
4x Analógica - Digital
2x Digital aislada con interrupciones

11x Salidas
3x Digital aislada/PWM/Analógica
8x Relé

Comunicaciones: Ethernet, RS485, RS232, x2Serial, SPI, I2C, RTC


219,00 € 219,00 €

  • # CPU Tipo #
  • #CPU Tipo#
  • # Dispositivo #
  • # Entradas #
  • # Relé #
  • # Salidas #
  • Ethernet
  • NO_CPU
  • Opciones de Comunicación
  • Communication board 2
  • Communication board 3
  • Digital Inputs *See technical details
  • Interrupt Input
  • Analog Inputs (Included as a Digitlal Input)
  • Digital Outputs *See technical details
  • Relay Outputs *See technical details
  • Analog Outputs (Included as a Digitlal Output)
  • RS485
  • RS232
  • I2C
  • SPI
  • Serial TTL
  • µSD Card Socket
  • RTC
# CPU Tipo #: Arduino
#CPU Tipo#: Arduino Mega
# Dispositivo #: PLC
# Entradas #: 11-20
# Relé #: 1-10
# Salidas #: 11-20
Ethernet: Yes
NO_CPU: Arduino Mega
Opciones de Comunicación: No Additional Com. Board 1
Communication board 2: No Additional Com. Board 2
Communication board 3: No Additional Com. Board 3
Digital Inputs *See technical details: 6
Interrupt Input: 2
Analog Inputs (Included as a Digitlal Input): 4
Digital Outputs *See technical details: 3
Relay Outputs *See technical details: 8
Analog Outputs (Included as a Digitlal Output): 3
RS485: Yes
RS232: Yes
I2C: Yes
SPI: Yes
Serial TTL: Yes
µSD Card Socket: Yes
RTC: Yes



PLC Arduino M-Duino 19R+: 17 E/S con salidas digitales, analógicas y de relé

El M-Duino 19R+ es un PLC industrial compacto basado en el Arduino Mega 2560. Ofrece 17 puntos de E/S: 4 entradas analógicas/digitales convertibles (0 a 10 Vdc), 2 entradas digitales aisladas con capacidad de interrupción, 3 salidas configurables digital/PWM/analógica (0 a 10 Vdc) y 8 salidas de relé. Con Ethernet (W5500), doble RS-485, RS-232, doble Serial TTL, I2C, SPI y un RTC integrado, está pensado para proyectos de automatización, monitorización y adquisición de datos que necesitan control de relés integrado.

Especificaciones técnicas

EspecificaciónValor
Número de referenciaIS.MDuino.19R+
Total de E/S17
Arquitectura2 layers (CR)
MicrocontroladorArduino Mega 2560
Entradas6
Entradas analógicas/digitales convertibles (0 a 10 Vdc)4
Entradas digitales aisladas (con interrupción)2
Salidas9
Salidas digital/PWM/analógica (0 a 10 Vdc)3
Relay Outputs8
EthernetSí (W5500, 10/100 Mbps)
Puertos RS-4852
Puertos RS-2321
Puertos Serial TTL / UART2
SPIYes
I2CYes
RTCYes
Ranura MicroSDYes
Alimentación12 a 24 Vdc
Consumo máximo4.848 W
MontajeCarril DIN
CertificacionesCE, RoHS

Aplicaciones: control de bombas y motores, iluminación y pequeña automatización

El M-Duino 19R+ es adecuado para proyectos de pequeña automatización que necesitan conmutar bombas, motores, iluminación u otras cargas de forma directa, sin añadir módulos de relé externos, además de monitorizar señales analógicas y digitales.

Protocolos: Modbus sobre Ethernet y RS-485, RS-232

La comunicación se realiza mediante Ethernet y RS-485 (2 puertos) para Modbus TCP y Modbus RTU, con RS-232 para dispositivos heredados, además de I2C y SPI para periféricos locales.

Programación: Arduino IDE con librerías de Industrial Shields

Se programa mediante Arduino IDE con el paquete de placas industrialshields. Todas las E/S se referencian por nombre (I0_x, Q0_x, A0_x, R0_x).

PLC Arduino para automatización, monitorización y adquisición de datos

El M-DUINO ETHERNET PLC ARDUINO 19R+ es un controlador compacto y fiable diseñado para aplicaciones industriales como automatización, monitorización y adquisición de datos. Combina la robustez de un PLC industrial con la sencillez de la programación en Arduino IDE, lo que facilita su uso en proyectos de energía, agua, infraestructuras inteligentes y muchos otros.

Entradas, salidas y relés integrados

Este PLC incluye entradas y salidas digitales y analógicas con relés integrados. Esto permite accionar directamente bombas, motores o luminarias sin necesidad de hardware adicional. El beneficio: instalaciones más rápidas, menos cableado y reducción de costes.

Comunicaciones industriales estándar

Ethernet y RS-485 (Modbus) vienen integrados de serie para garantizar una comunicación fluida con redes industriales. Cuando el proyecto requiere mayor conectividad, los módulos de expansión internos amplían las opciones sin necesidad de dispositivos externos.

Programación sencilla con Arduino IDE

Basado en Arduino Mega, el M-DUINO ETHERNET PLC ARDUINO 19R+ se programa mediante Arduino IDE. La puesta en marcha local por USB y la programación remota por Ethernet permiten un despliegue rápido, un mantenimiento sencillo y menos tiempos de parada.

Beneficios para tu aplicación

  • Control directo de cargas con relés integrados que ahorran espacio y reducen componentes externos
  • Integración sencilla en redes existentes con Ethernet y RS-485
  • Menor tiempo de instalación y mantenimiento gracias a la programación intuitiva
  • Solución fiable para automatización, monitorización y adquisición de datos en proyectos de energía, agua e infraestructuras inteligentes
  • Posibilidad de desarrollos a medida a través de nuestro departamento de I+D para necesidades no estándar

Instalació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 bajo la Licencia Pública General de GNU. Arduino IDE admite la estructuración de código en C y C++. Para programar los PLC basados en Arduino Mega en este entorno, Industrial Shields proporciona un paquete de placas con las librerías y herramientas necesarias.

We recommend using the Legacy Arduino IDE (2.3.X) to program M-Duino based PLCs, although other Arduino compatible software could be used. The Arduino 2.3.X IDE can be downloaded from this link.After downloading and installing the Arduino IDE, install the industrialshields boards package inside the IDE. This can be done by following this tutorial and selecting the industrialshields package in step number 6.

Fuente de alimentación

The M-Duino based PLCs need to be powered with an external power supply, providing a voltage between 12 and 24Vdc. Caution! Although at first glance it may seem like the PLC works when powered with the USB port, this is not the case. The usage of an external power supply is mandatory for the PLC to perform properly. 

The consumption of M-Duino based PLCs range between 700 and 1500mA. Therefore, Industrial Shields recommends using a power supply capable of delivering at least 2A.

PSU specifications:

  • Voltage: between 12 and 24Vdc.
  • Intensity: at least 2A.

El diagrama de esta sección ilustra las conexiones necesarias para alimentar correctamente un PLC.


Power Diagram

Interruptores DIP

Los PLCs basados en M-Duino disponen de unos interruptores que permiten configurar ciertas funcionalidades del PLC. Esta sección explica cómo utilizarlos correctamente. Para diferenciar entre las distintas partes del PLC y localizar cada interruptor, se utilizará la siguiente nomenclatura:


In each zone there are one or more switches, used to configure some of the PLC functionalities. The following tables indicate the purpose of each switch and how to configure them. 

Zona A: interruptor superior izquierdo

A zone top switch

Switch

Off

On

1 (top)

TX1

I1.X

2 (top)

RX2

I1.X

3 (top)

SDA

I2.X

4 (top)

SCL

I2.X

1 (bottom)

FD

HD

2 (bottom)

SD

X

3 (bottom)

Pin 2

I0.X

4 (bottom)

Pin 3

I0.X


Top switch:

  1. If this switch is ON, it enables the I1.X input and disables TX1. If this switch is OFF, it enables TX1 and disables I1.X.
  2. If this switch is ON, it enables the I1.X input and disables RX1. If this switch is OFF, it enables RX1 and disables I1.X.
  3. If this switch is ON, it enables the I2.X input and disables SDA. If this switch is OFF, it enables SDA and disables I2.X.
  4. If this switch is ON, it enables the I2.X input and disables SCL. If this switch is OFF, it enables SCL and disables I2.X.

Bottom switch:

  1. If this switch is ON, it enables the Half Duplex (HD) option and disables the FD. If this switch is OFF, it enables Full Duplex (FD) and disables HD.
  2.  If this switch is OFF, it enables the Chip Select of the microSD card. In some M-Duino PLC models, if this switch is ON it enables a digital output.
  3.  If this switch is ON, it enables the I0.X input and disables the Pin 3. If this switch is OFF, it enables Pin 3 and disables I0.X.
  4.  If this switch is ON, it enables the I0.X input and disables the Pin 2. If this switch is OFF, it enables Pin 3 and disables I0.X.

*The X represents different pins for the different M-Duino PLC models.

Zona A: interruptor inferior izquierdo

A zone bottom switch

Switch

Off

On

1

X

RTC

2

X

RTC

3

X

X

4

X

X


Solo se utilizan los interruptores 1 y 2. Ambos interruptores habilitan la comunicación con el RTC mediante I2C. Tener estos interruptores en modo ON activa esta comunicación, mientras que si está en

modo OFF deshabilita el I2C para llegar al RTC.

Zona B, C y D: Interruptor analógico

Analog switch

Switch

Off

On

1

AX.5

QX.5

2

AX.6

QX.6

3

AX.7

QX.7

4

X

X


These switches are used to choose between digital or analog output, according to the previous table. If it is set to OFF, only the corresponding analog output will be available. If it is set to ON, only the corresponding digital output will be available. The switches behave the same way in zones B, C and D, with the "X"  value being different depending on the zone:

  • Zone B: X = 0
  • Zone C: X = 1
  • Zone D: X = 2

Consumo de energía

This report explores how different M-Duino PLC models consume power during idle and high-output scenarios. Understanding these patterns is crucial for optimizing efficiency in industrial applications.

En reposo

In this scenario, the M-Duino PLC is powered on, with all pins and communications turned off and utilizing a 24V power supply. This test measures the baseline power consumption when the device is idle and not actively engaged in any processing or output tasks.

MODEL

CURRENT (mA)

POWER (W)

21+99
2,376
42+92
2,208
58+76
1,824
19R+80
1,92
38R+77
1,848
57R+73
1,752
38AR+72
1,728
53ARR+71
1,704
57AAR+71
1,704
54ARA+76
1,824
50RRA+82
1,968

Todas las salidas a HIGH

For this test, the M-Duino PLC is configured to set all its output pins to a high state, drawing the maximum current for output operations and utilizing a 24V power supply. This provides insights into the power consumption when the device is actively driving output signals.

MODEL

CURRENT (mA)

POWER (W)

21+120
2,88
42+128
3,072
58+126
3,024
19R+202
4,848
38R+313
7,512
57R+425
10,2
38AR+221
5,304
53ARR+323
7,752
57AAR+221
5,304
54ARA+231
5,544
50RRA+322
7,728

Entradas y Salidas

Entradas analógicas

La entrada analógica proporciona una forma de leer niveles de voltaje analógico, codificando el valor con un número de N bits. Las entradas analógicas de los PLCs basados en M-Duino utilizan el GND interno como referencia (el mismo que la fuente de alimentación). Las entradas analógicas de estos PLCs tienen las siguientes especificaciones:

  • Voltage range: from 0 to 10 Vc.
  • Resolution: 10 bits, which means the read values can range between 0 and 1023.

Además, las entradas analógicas también pueden usarse como entradas digitales no aisladas tolerando hasta 24 Vcc. Para ello, consulte la sección de entradas digitales. Las entradas analógicas son las comprendidas entre IX.7 e IX.12, con X siendo 0, 1 o 2 según la zona. Puede identificar las entradas analógicas en su dispositivo con el siguiente símbolo:

0V - 10Vdc Analog input

0V - 10Vdc Analog input

  

 The next diagram illustrates the necessary connections to properly use an analog input (when used as a digital, the input can tolerate up to 24V):

Analog Input Diagram

Configuración de software

In order to use them, the analog inputs must be configured in the set up part of the code, like it is usually done in common Arduino boards. Then they can be read using the "analogRead()" function, with the input name as its parameter. For example, I0.7 is read as I0_7:

void setup() {
  pinMode(I0_7, INPUT);
  Serial.begin(9600);
}

void loop() {
  Serial.println(analogRead(I0_7));
}

The following post might also be of interest: Learning the basics about analog inputs of an industrial PLC.

Entradas digitales

Las entradas digitales se utilizan para capturar señales que existen en uno de dos estados: alto o bajo, verdadero o falso, etc. Las entradas digitales del PLC M-Duino interpretan como alto los valores de 5 Vcc o superior, hasta 24 Vcc, mientras que los valores inferiores a 5 V se interpretan como bajo. Hay 2 tipos de entradas que pueden usarse como entrada digital:

  • Digital isolated inputs (5 - 24 Vdc): these inputs are opto-isolated, which means they have an extra protection and they use an external ground pin for reference.  They are the pins from IX.0 to IX.6, where X is 0,1 or 2 depending on the zone. 
  • Digital non-isolated input (5 - 24 Vdc): these inputs are not opto-isolated, and they use the internal GND of the PLC as reference. They are the same as the analog inputs, going from IX.7 to IX.12, with X being 0, 1 or 2 depending on the zone.

Puede identificarlas con los siguientes símbolos:

Isolated Input Symbol

5V - 24V isolated input

 

Non Isolated Input Symbol

5V - 24V non-isolated input

 

 The next diagrams illustrate the necessary connections to properly use both inputs as digital:

Isolated Input Diagram

Non Isolated Input Diagram

Configuración de software

In order to use them, the digital inputs must be configured in the set up part of the code, like it is usually done in common Arduino boards. Then they can be read using the "digitalRead()" function, with the input name as its parameter. For example, I0.0 is read as I0_0:

void setup() {
  pinMode(I0_0, INPUT);
  Serial.begin(9600);
}

void loop() {
  Serial.println(digitalRead(I0_0));
}

The following posts expand on this topic: Basics about digital inputs of an industrial controller, PNP Digital Inputs on industrial PLC.

Entradas de interrupción

Algunas de las entradas digitales del PLC M-Duino son capaces de interrupciones, lo que significa que pueden usarse con ISRs (rutinas de servicio de interrupción) para activar cierta ejecución de código cuando se detecta un evento (cambio de estado en el pin). Hay dos pines de este tipo en cada zona: IX.5 e IX.6. Se utilizan y conectan como entradas digitales aisladas normales, y las interrupciones se programan por software.

Configuración de hardware

Las entradas de interrupción deben activarse utilizando los interruptores superiores de la zona A:

  • I0.5 and I0.6 also work as Pin3 and Pin2. Enable Interrupts turning ON the switches number 3 and 4 of down communication switches.
  • I1.5 and I1.6 also work as Tx1 and Rx1. Enable Interrupts turning ON the switches number 1 and 2 of up communication switches.
  • I2.0 and I2.1 also work 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.


Check the "Initial installation - Hardware" section in this page for more information.

Configuración de software

This is an example of how to use the interrupt pins. In this case, the function "isrI0_5()" is automatically called every time a change of state occurs on the I0.5 pin.

void setup() {
  // Begin serial port
  Serial.begin(9600);
  // Set input 
  pinMode(I0_5, INPUT);
  // Initialize interrupt
  attachInterrupt(digitalPinToInterrupt(I0_5), isrI0_5, CHANGE);
}

void loop() {
  while(true);
}

void isrI0_5() { 
  Serial.println("Interrupt activated");
}

Salidas analógicas

An analog output provides a voltage determined by a digital value with an N-bit number. The M-Duino PLCs can have between 3 and 9 analog outputs, depending on the model. These are labeled as AX.X,  and need to be selected via DIP switch to be used. Refer to the switch section in this page for more information about the switches. The analog outputs in the M-Duino PLC have the following specifications:

  • Voltage range: from 0 to 10 Vac.
  • Resolution: 8 bits.

The analog outputs have a shared external GND pin, which needs to be connected to set the reference. This symbol identifies the analog outputs, and the following diagram illustrates how to connect:

Analog Output Symbol0 - 10V analog output

Analog Output Diagram

Configuración de software

The procedure to program the analog outputs is the same as regular Arduino: first, the pin mode must be set to "OUTPUT" in the setup of the code, and then the output can be written using "analogWrite()". The analog outputs can be referenced by its name and using a "_" instead of the ".". For example, A0.5 is used as A0_5:

void setup()
{
    pinMode(A0_0, OUTPUT);
}

// Loop function
void loop()
{   
    analogWrite(A0_5, 0);    
    delay(1000);   
    analogWrite(A0_5, 200);
    delay(1000);
}

To know more about analog outputs: Basics about analog outputs of an industrial PLC.

Digital outputs

Las salidas digitales del PLC M-Duino pueden proporcionar un valor bajo (0 Vcc) o alto (hasta 24 Vcc). Estas salidas están etiquetadas como QX.X y pueden identificarse con el siguiente símbolo.

The output high value can range between 5 and 24 Vdc. This voltage needs to be set using two pins located next to the outputs: QVdc and COM(-). For instance, should you wanna set the output to 24V, the QVdc pin should be connected to 24V and the COM(-) pin to GND. The following diagram illustrates an example connection:

Digital output (PWM optional)

Digital output (PWM optional)

Digital Output Diagram

Configuración de software

The digital outputs must be configured in the setup part of the code like it is usually done in common Arduino boards, using the "pinMode()" first to set it as "OUTPUT", and "digitalWrite()" to change the output value. Check the following example:

void setup() {
  pinMode(Q0_0, OUTPUT);
}

void loop() {
  digitalWrite(Q0_0, HIGH);
  delay(1000);
  digitalWrite(Q0_0, LOW);
  delay(1000);
}

You can learn more about digital outputs in this post: Basics about digital outputs of an industrial PLC.

Salida PWM

In the M-Duino based PLCs, some of the digital outputs can be used as PWM outputs.

The output high value can range between 5 and 24 Vdc. As when using them as simple digital outputs, this voltage needs to be set using two pins located next to the outputs: QVdc and COM(-). For instance, if you want to set the output to 24V, the QVdc pin should be connected to 24V and the COM(-) pin to GND. The following diagram illustrates an example connection.

An example tutorial about how to program the PLC to use the PWM outputs can be found in our repository using the avr-Pulses library.

Digital output (PWM)

PWM capable output


PWM Output Diagram

Salida de relé

Un relé es un interruptor electromagnético controlado por una señal eléctrica. En los equipos de Industrial Shields estos dispositivos ya están integrados en las placas. Los relés incluidos en el PLC M-Duino pueden funcionar hasta 24 Vcc o 220 Vca. Cada salida de relé tiene dos terminales y está etiquetada como RX. El siguiente diagrama ilustra las conexiones:

Relay Output Diagram

Configuración de software

The relay output must be configured in the set up part of the code, using Arduino functions, and they are controlled as if they were digital outputs. The outputs can be referenced by the name shown in the serigraphy: R0.1 for instance is used as R0_1. Check the following example. When the output is set to "HIGH", the real i turned on, meaning the switch closes, whereas when it is set to "LOW" the switch is open.

void setup() {
  pinMode(R0_1, OUTPUT);
}

void loop() {
  digitalWrite(R0_1, HIGH);
  delay(1000);
  digitalWrite(R0_1, LOW);
  delay(1000);
}

To know more about the relay outputs, check out this post: Learning the basics about internal relays of an industrial PLC.

Comunicaciones

Ethernet

Ethernet is the most commonly used technology in wired local area networks ( LANs ). 

A LAN is a network of computers and other electronic devices that covers a small area such as a room, office, or building. It is used in contrast to a wide area network (WAN) , which spans much larger geographical areas. Ethernet is a network protocol that controls how data is transmitted over a LAN. Technically it is referred to as the IEEE 802.3 protocol. The protocol has evolved and improved over time to transfer data at the speed of a gigabit per second.

 The M-Duinos PLCs incorporate an Ethernet port, using the W5500 controller, which communicates with the Arduino using SPI. The W5500 is a Hardwired TCP/IP embedded Ethernet controller that provides easier Internet connection to embedded systems. This chip enables users to have Internet connectivity in their applications by using the single chip in which TCP/IP stack, 10/100 Ethernet MAC and PHY are embedded. With this chip users can integrate Ethernet into their applications.  

Configuración de software

The Industrial Shields boards package includes an "Ethernet" library, intended to facilitate the use of this protocol. Various examples are included with the library, you can check them out going to File > Examples > Ethernet inside the Arduino IDE.

Also take a look at the following program. Before running the code, ensure that your PLC is powered correctly, confirm that the Ethernet cable is securely connected to your device and make sure the "industrialshields" board package is properly installed in your Arduino IDE. This code serves as a diagnostic tool to ensure the proper functioning of the Ethernet port. It establishes a connection to "www.google.com" through the W5500 controller using DHCP IP configuration. 

#include "Ethernet.h"

#define REMOTE "www.google.com"

const uint16_t port = 80;
uint8_t mac[] = {0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0x01};

EthernetClient c;

////////////////////////////////////////////////////////////////////////////////////////////////////
void setup() {
  Serial.begin(9600L);
  Serial.println("ethernet started");

  test();
}

////////////////////////////////////////////////////////////////////////////////////////////////////
void loop() {
  if (!c.connected()) {
    Serial.println("Disconnected");
    test();
  }
  delay(1000);
}

////////////////////////////////////////////////////////////////////////////////////////////////////
void test() {
  //if you need a DHCP IP use this configuration:
  Ethernet.begin(mac);
          
  switch (Ethernet.hardwareStatus()) {
    case EthernetW5100:
      Serial.println("W5100 found");
      break;

    case EthernetW5200:
      Serial.println("W5200 found");
      break;

    case EthernetW5500:
      Serial.println("W5500 found");
      break;

    default:
      Serial.println("Unknown hardware");
      break;
  }

  uint8_t MAC[6];
  Ethernet.MACAddress(MAC);
  for (int i = 0; i < 6; ++i) {
    if (i > 0) {
      Serial.print(':');
    }
    Serial.print(MAC[i], HEX);
  }
  Serial.println();

  //use this block with DHCP IP:
  Serial.println(Ethernet.localIP());
  if (Ethernet.localIP() == IPAddress({0,0,0,0})) {
    Serial.println("Local IP FAIL");
  } else {
    Serial.println("Local IP OK");
    if (c.connect(REMOTE, port)) {
      Serial.println("Remote connection OK");
    } else {
      Serial.println("Remote connection FAIL");
    }
   }
}

RS-485

RS485, also known as TIA-485(-A), EIA-485, is a standard defining the electrical characteristics of drivers and receivers for use in serial communications systems.The M-Duino PLCs include half-duplex RS485 capabilites, thanks to the incorporated MAX485 transceiver chip.

El MAX485 es un transceptor de bajo consumo y velocidad de variación limitada utilizado para la comunicación RS-485. Funciona con una fuente de alimentación de +5 V y la corriente nominal es de 300 μA. Adoptando comunicación semidúplex para convertir el nivel TTL en nivel RS-485, puede alcanzar una velocidad de transmisión máxima de 2,5 Mbps. El transceptor MAX485 consume una corriente de alimentación de entre 120 μA y 500 μA en condiciones sin carga o con carga completa cuando el driver está desactivado.

If you want to know more about RS485, check out this post.

Configuración de hardware

Para utilizar el RS485 con los PLCs M-Duino, compruebe el interruptor superior izquierdo de la zona A. El RS485 siempre está activo, pero hay un interruptor (número 1) utilizado para elegir entre semidúplex y dúplex completo. Para más información sobre los interruptores, consulte la sección "Instalación inicial - Hardware" de esta página.

The RS485 pins, A+ and B- need to be properly connected to the device the PLC is communicating with. Attention! Remember to properly power the PLC with a 12-24V power supply.

Configuración de software

Our boards package includes an RS485 library to make programming easier. This library is used as the Arduino Serial library, with methods such as "available()", "read()", etc.

Check out the following code, which establishes half duplex communication and allows the user to read or send messages from the terminal of the PC.

#include "RS485.h"

void setup() {
  // Begin Serial port
  Serial.begin(9600);
  // Begin RS485 port
  RS485.begin(9600, HALFDUPLEX);
}

void loop() {
  //Send one byte for the serial, receive this byte by rs485
  if (Serial.available()){
    read_from_serial();
  }
  if (RS485.available()){
    read_from_rs485();
  }
}

static void read_from_serial(void){
  char tx = Serial.read(); //Read byte
  if (tx != '\n') Serial.println(tx); //Print the byte 
  RS485.write(tx); //Transmit by rs485
}

static void read_from_rs485(void){
  char rx = RS485.read(); //Receive the same byte
  if (rx != '\n') {
    Serial.println(rx); //Print the byte
  } 
}

RS232

RS-232 is a standard for serial communication transmission of data. It formally defines the signals used in communication between DTE (Data Terminal Equipment) such as a computer terminal, and DCE (Data Circuit-terminating Equipment or Data Communication Equipment), such as a modem. The M-Duino PLC includes a MAX232 transceiver chip, allowing full-duplex communication through RS232. The MAX232 is a dual transmitter/dual receiver that is used to convert the RX, TX, CTS, RTS signals, converting signals from Serial TTL to TIA-232 (RS-232) serial port.

If you want to know more about RS232, check this post.

Configuración de hardware 

The RS232 pins, TX and RX need to be properly connected to the device the PLC is communicating with. Attention! Remember to properly power the PLC with a 12-24V power supply.

Configuración de software

Once the hardware configuration is done, it is possible to proceed with the software configuration and its usage. Firstly, it is necessary to include the RS232.h library provided by our boards package. Then, the communication must be initialized with "RS232.begin(<baudrate>);". After this RS232 can already be used with the functions "RS232.read();" and "RS232.write();". 

Check the following read and write examples:

// Include Industrial Shields libraries
#include "RS232.h"

//////////////////////////////////////////////////////////////////////////////////////////////

void setup() {
  // Begin serial port
  Serial.begin(9600);
  // Begin RS232 port
  RS232.begin(38400);
}

///////////////////////////////////////////////////////////////////////////////////////////////

void loop() {
  // Wait bytes in the serial port
  if (Serial.available()) {
    byte tx = Serial.read();

    // Echo the byte to the serial port again
    Serial.write(tx);

    // And send it to the RS-232 port
    RS232.write(tx);
  }   
}
// Include Industrial Shields libraries
#include "RS232.h"

//// IMPORTANT: check switches configuration

//////////////////////////////////////////////////////////////////////////////////////////////

void setup() {
  // Begin serial port
  Serial.begin(9600);
  // Begin RS232 port
  RS232.begin(38400);
}

//////////////////////////////////////////////////////////////////////////////////////////////

void loop() {
  // Print received byte when available
  if (RS232.available()) {
    byte rx = RS232.read();

    // Hexadecimal representation
    Serial.print("HEX: ");
    Serial.print(rx, HEX);

    // Decimal representation
    Serial.print(", DEC: ");
    Serial.println(rx, DEC);
  } 
}

Serial TTL

Serial TTL is a communication Interface between two devices with working at a low level voltage. Two signals are used: Tx (Transmit Data) and Rx (Receive Data), which allow full-duplex communication. The M-Duino PLCs have two external TTL ports, Serial 1 (RX1/TX1) and Serial 0 (RX0/TX0).

To know more about the serial TTL interface, visit this blog.

Configuración de hardware

The M-Duino PLC features two serial ports. One of them, the Serial 1 (TX1, RX1), needs to be activated using the A zone top left switch. For more information about the switches, check the "Initial installation - Hardware" section in this page.

For the Serial communication to work, the following connections between the PLC and the other device need to be made:

  • TX -> RX
  • RX -> TX
  • GND, both devices need to share a common ground.

Attention! The M-Duino PLCs serial ports work at 5V levels. Higher voltage levels might damage the PLC. 

Also, remember to properly power the PLC with a suitable 12-24Vdc power supply.

Configuración de software

In order to use the Serial communication with the PLC, the Arduino "Serial" object can be used. Check the following example, which uses Serial 1, to send and receive byte using the USB serial port and the Serial 1. To use the Serial 2 instead of the 1, the "Serial2" object must be used.

void setup() {
  // Initialize serial connections
  Serial.begin(9600);
  Serial1.begin(9600);
}

void loop() {
  // Read byte from Serial and send it through Serial1
  if (Serial.available()) { // Check if there is an available byte to read
    Serial1.print(Serial.read());
  }

  // Read byte from Serial1 and send it through Serial   
  if (Serial1.available()) {
    Serial.print(Serial1.read());
  }
}

I2C

I2C is a serial communications protocol. It is a master-slave synchronous protocol and 2 cables are used, one for the clock (SCL) and one for the data (SDA). The master controls the bus and creates the clock signal, and uses addressing to communicate with the slaves. It is a very used bus in the industry, mainly to communicate microcontrollers and their peripherals in integrated systems, normally located in the same PCB. The speed is 100 Kbit/s in standard mode.

Configuración de hardware

Los PLCs M-Duino disponen de un puerto I2C con los pines SCL y SDA. Estos pines deben activarse mediante el interruptor superior izquierdo de la zona A (SCL y SDA deben seleccionarse en los interruptores 3 y 4). Para más información sobre los interruptores, consulte la sección "Instalación inicial - Hardware" de esta página.

Otros dispositivos pueden conectarse a este bus como esclavos. Al conectar otros dispositivos, tenga en cuenta las siguientes especificaciones:

  • The I2C port works at 5V. Higher voltage levels might damage the PLC. 
  • The I2C pins, SCL and SDA, are pulled up to 5V.

Also, remember to properly power the PLC with a suitable 12-24Vdc power supply.

Configuración de software

The I2C can be used with the library "Wire". Check the following example which implements an I2C scanner that searches the bus for any connected devices. When a device is detected, it will be reported to the serial monitor. Note that if you connect the I2C pins (SDA and SCL) to an other device, it should appear in the scan.

Antes de ejecutar el código, asegúrese de que el PLC está correctamente alimentado, verifique que el paquete de placas "industrialshields" está correctamente instalado en su IDE de Arduino y que ha seleccionado el modelo de PLC correcto en su IDE.

#include "Wire.h"

void setup() {
  Serial.begin(115200);
  Wire.begin();
}

void loop() {
  byte error, address;
  int nDevices = 0;

  delay(5000);

  Serial.println("Scanning for I2C devices ...");
  
  for(address = 0x01; address < 0x7f; address++){
    Wire.beginTransmission(address);
    error = Wire.endTransmission();
    
    if (error == 0){
      Serial.printf("I2C device found at address 0x%02X\n", address);
      nDevices++;
    } else if(error != 2){
      Serial.printf("Error %d at address 0x%02X\n", error, address);
    }
  }
  
  if (nDevices == 0){
    Serial.println("No I2C devices found");
  }
}

SPI

The Serial Peripheral Interface (SPI) is a synchronous serial communication interface specification used for short-distance communication, primarily in embedded systems. SPI devices communicate in full duplex mode using a master-slave architecture, usually with a single master. 3 pins are used with SPI communication: SCLK, MOSI, MISO. Additionally, one extra pin for each slave, called chip select (CS) or slave select (SS) is used to select the slave that is being talked to in the bus.

The M-Duino PLC features one SPI port.

Configuración de hardware

Para utilizar el SPI, los 3 pines mencionados (SCLK, MISO, MOSI) deben conectarse correctamente:

Function

M-Duino PLC Pin

Arduino Mega Pin

MISO

SO

50

MOSI

SI

51

CLOCK

SCK

52

RST

Reset

Reset

¡Atención! El SPI funciona a niveles de voltaje de 5 V; un voltaje superior podría dañar el PLC.

Also, remember to properly power the PLC with a suitable 12-24Vdc power supply.

Configuración de software

El paquete de placas "industrialshields" incluye una librería SPI, basada en la librería SPI de Arduino. Esta librería permite programar el MDuino como maestro SPI.

This program shows how to set up the MDuino as a master in SPI communication, and send and receive data. In this case the character "0" is sent, and the received data is stored in the corresponding variable (SPI transfer is based on a simultaneous send and receive) and printed through the serial port.

#include "SPI.h"

// Set pin as the slave select:
const int slaveSelectPin = GPIO_0;
volatile byte receivedData;

void setup() {
  Serial.begin(9600);
  // Set the slaveSelectPin as an output:
  pinMode(slaveSelectPin, OUTPUT);
  // Initialize SPI:
  SPI.begin();
}

void loop() {

  SPI.beginTransaction(SPISettings(100000, MSBFIRST, SPI_MODE0));
  digitalWrite(slaveSelectPin, LOW); // Start of transmission: set chip select LOW
  receivedData = SPI.transfer('0');
  digitalWrite(slaveSelectPin, HIGH); // End of transmission: set chip select HIGH
  SPI.endTransaction();
  
  Serial.println((char)receivedData);
 
  delay(100);
}

To know more about SPI check the following post: Bus SPI on PLC Arduino from Industrial Shields

Características adicionales

RTC

RTC stands for Real Time clock, en electronic device that measures the passage of time. Although keeping time can be done without an RTC, using one has benefits such as:

  • Mantaining the time without needing to set ti again after a reboot, shutdown, etc.
  • Low power consumption (important when running from alternate power.
  • Frees the main control system for time-critical tasks.
  • Sometimes more accurate than other methods.

The M-Duino PLC include a DS1307 RTC module, which communicates with the Arduino microcontroller using I2C. The DS1307 serial real-time clock is a lowpower, full binary-coded decimal (BCD) clock/calendar, including 56 bytes of NV SRAM. Iprovides seconds, minutes, hours, day, date, month, and year information. 

In order to power the RTC when the PLC is not connected, the PLC includes a 3,3V lithium coin cell battery which can be used to supply the RTC.

No es necesaria ninguna configuración de hardware para utilizar el RTC; el único requisito es que el PLC esté correctamente alimentado con una fuente de alimentación de 12-24 Vcc y disponer de una batería de litio tipo botón para mantener la hora cuando el PLC no tiene alimentación.

Configuración de software

The RTC library, included with our boards package, can be used to interact with the RTC. Check the following code example where time is read from the RTC and printed to the serial monitor. 

Remember to make sure you have the industrialshields board package properly installed in your Arduino IDE.

// RTC library example
// by Industrial Shields
#include "RTC2.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);
}

SD

Secure Digital (SD) cards are non-volatile memory storage devices that use flash memory technology. Designed for portable electronic devices, SD cards provide a reliable and compact solution for data storage.

El PLC M-Duino incorpora una ranura para tarjeta SD con las siguientes especificaciones:

  • MicroSD slot.
  • Up to 32GB of storage (although higher capacity cards can be used, only the first 32GB will be accessible and usable).
  • FAT32 and FAT16 allowed as file system architectures.

The SD slot communicates with the M-Duino using SPI, and there is no hardware configuration needed. Remember to power the PLC with a proper 12-24Vdc power supply.

Configuración de hardware

In order to use the SD with the M-Duino PLCs, check the A zone top left switch. For more information about the switches, check the "Initial installation - Hardware" section in this page.

Configuración de software

The "industrialshields" boards package includes an SD library to facilitate its usage. Check the following example, which initializes the SD card and prints the contents of it root directory through the serial port.

#include "SD.h"

File root;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);

  // wait for Serial Monitor to connect. Needed for native USB port boards only:
  while (!Serial);

  Serial.print("Initializing SD card...");

  int SS = SD.begin();
  if (!SS) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("1. is a card inserted?");
    Serial.println("2. is your wiring correct?");
    Serial.println("3. did you change the chipSelect pin to match your shield or module?");
    Serial.println("Note: press reset or reopen this serial monitor after fixing your issue!");
    while (true);
  } else {
    Serial.println(SS, DEC);
  }

  Serial.println("initialization done.");
  root = SD.open("/");

  printDirectory(root, 0);
  Serial.println("done!");
}

void loop() {
  // nothing happens after setup finishes.
}

void printDirectory(File dir, int numTabs) {
  while (true) {
    File entry = dir.openNextFile();
    if (!entry) {
      // no more files
      break;
    }

    for (uint8_t i = 0; i < numTabs; i++) {
      Serial.print('\t');
    }
    Serial.print(entry.name());

    if (entry.isDirectory()) {
      Serial.println("/");
      printDirectory(entry, numTabs + 1);
    } else {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.println(entry.size(), DEC);
    }
    entry.close();
  }
}

Pines directos de Arduino

If we want to use another Serial Port using this equipment, we can make use of some digital pins to create a Serial. The SoftwareSerial library has been developed to allow serial communication on other digital pins of the Arduino, using software to replicate the functionality.  It is possible to have multiple software serial ports with speeds up to 115200 bps. A parameter enables inverted signaling for devices which require that protocol.

Only I/O 5V from Ardbox or M-Duino  boards can be used.

M-Duino Pins Ardino Mega Pins
MISO 50
MOSI 51
SCK 52

Señales de 5 Vdc

Estos pines se pueden programar según las funciones de Arduino, como E/S que funcionan a 5V o cualquier función adicional presente en los pines.

  • Pines I2C – SDA/SCL: El protocolo I2C está pensado para funcionar en una configuración pull-up. En este caso, se lee 5V cuando no hay nada conectado.
  • Serial 0 – RX0/TX0: El protocolo Serial0 también puede funcionar como pin de 5V. Si se usan estos pines, la comunicación USB no puede estar activa al mismo tiempo.
  • Serial 1 – RX1/TX1: El protocolo Serial1 también puede funcionar como pin de 5V. Siempre está activo.
  • SPI – MISO/MOSI/SCK: Estos pines solo pueden funcionar como pines de 5V si no se va a usar el protocolo Ethernet. Dado que el protocolo Ethernet usa el SPI para comunicarse con la placa Arduino, ambos comportamientos no pueden darse al mismo tiempo, ya que el Ethernet dejaría de funcionar.
  • Pin2/Pin3: Estos pines solo hacen referencia a las entradas I0.5/I0.6. Si la configuración del interruptor está en posición OFF, los pines Pin 2/Pin 3 estarán disponibles.