Detalles Técnicos

M-DUINO PLC Arduino Ethernet  & GPRS  38AR I/Os Analog/Digital/Relay PLUS GPRS

 VOLVER AL PRODUCTO

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 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: 

Windows Installer

MAC OSX

Instale unidades de Industrial Shields en Arduino IDE:

Industrialshields boards

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:  (10x) Analógico (0-10Vdc) / Digital (5-24Vdc) configurables 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: (8x) Aisladas digitales (5-24Vdc), (3x) pueden funcionar como interrupción INT (7-24Vdc).

Know more about Digital Inputs.

Know more about PNP 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: (3x) Entradas de interrupción (7-24Vdc). "Puede funcionar como una entrada digital (24 V CC)" 

Interruptor Pin Arduino Mega Pin MDuino
INT1 3 I0.6/INT1
INT2 18 I1.0/INT2
INT3 19 I1.1/INT3

  
    - I0.6 también como Pin3, habilita las interrupciones encendiendo los interruptores número 4 del interruptor de comunicación descendente.
    - I1.0 e I1.1 también como Tx1 y Rx1. Habilite las interrupciones activando los interruptores número 1 y 2 de los interruptores de comunicación.


TYPICAL CONNECTION



EJEMPLO

En este ejemplo activamos INT1 usando el pin I0_6 de la placa M-duino. Cuando hay un cambio   

#define INTERRUPT I0_6 //other pins: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 ). 

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. Our M-Duino family incorporate the integrated W5500 IC. WX5500 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. The W5500 chip embeds the 32Kb internal memory buffer for the Ethernet packet processing. With this chip users can implement the Ethernet application by adding the simple socket program. SPI is provided for easy integration with the external microcontroller.


Hardware  

Hardware configuration

*IMPORTANT: Make sure that your Ethernet PLC is powered (12-24Vdc). Just with USB is insufficient power to power up the
Ethernet communication.

 

Switch configuration

For the Ethernet communication protocol there isn’t any switch that affects it. So it does not matter the configuration of the
switches to implement Ethernet communication.

Used pins

For Ethernet communication protocol, the defined Arduino Mega pin is pin 10 , which is connected and already internally
assembled to the WX5500 Ethernet controller. W5500 IC communicates to the Mega board via SPI bus already assembled too.
You can
access easily to Ethernet port in our Ethernet PLCs, it is located at the top of the communications layer.

Ethernet hardware configuration must be plug and play.

Software

 

*IMPORTANT: Make sure to download the Arduino based PLC boards for Arduino IDE.

Software Configuration:

Once the hardware configuration is done, it is possible to proceed with the software configuration and also its usage. Firstable it is necessary to include
the Ethernet2.h library provided by Industrial Shields (has the same functionallity as Ethernet.h and also
the same usage).

#include <Ethernet2.h> 
* Remember that for the V7 version or earlier versions you must use the <Ethernet.h> library.

Ethernet2 Library - functions.

* Ethernet2.h library has the same functions as Ethernet.h.

    For Ethernet communication there is 3 protocols available:

Sample example Codes:

Echo TCP Server:

Once the server is running, any client can connect to the server. On this example it is used an M-Duino to generate the server. The
example of TCP client showed before could be one of the clients.

Next it is showed the Arduino IDE code:

// 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:

Once the server is running, M-Duino can connect to the server. On this example it is used an M-Duino to connect with the Node.js
server called server.js, the same as used on previous example link.

To configure the M-Duino, this post just follows the TCP example from Arduino web site with a few changes. To be able to connect to the server we must know the TCP
server IP and the port where this server is listening.

Next it is showed the Arduino code:

#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

Communication Interface between two devices with a low level voltage. A Serial port sends data by a bit sequence.

Two signals: Tx (Transmit Data) and Rx (Receive Data).

M-Duino has two TTL ports, RX0/TX0, RX1/TX1. TTL0 is accessed with the function Serial (pins 0 and 1 of the Arduino Mega). TTL1 is accessed with the function Serial1 (pins 18 and 19 of the Arduino Mega).

Hardware

IMPORTANT:  Make sure that your Ethernet PLC is powered (12-24Vdc). 

Switch configuration


To achieve Serial TTL 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 Serial TTL
communication.  

Used pins 

For Serial communication protocol the defined Arduino Mega pins are showed in the chart below: 


MDuino Ethernet & GPRS PLC PinoutArduino Mega Pinout
Tx 0
0
Rx 01
Tx 118
Rx 1
19

Software

IMPORTANT:  Make sure to download the  Arduino based PLC boards  for Arduino IDE.

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 RS232.h library provided in 
our boards. Then don’t forget to implement the proper initialization of your communication on the setup() function:

Serial.begin(9600);

Basic Serial TTL write example 

  Reads an analog input on Tx0 (pin 0), prints the result to the serial monitor.

  Graphical representation is available using serial plotter (Tools > Serial Plotter menu) on Arduino IDE serial monitor.

// 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
}

Know more about Serial TTL.

I2C

I2C is a synchronous protocol. Only uses 2 cables, one for the clock (SCL) and one for the data (SDA). This means that the master and the slave send data through the same

cable, which is controlled by the master, who creates the clock signal. I2C does not use slave selection, but addressing.

I2C is a serial communications bus. The speed is 100 kbit/s in standard mode, but also allows speeds of 3.4 Mbit/s. It is a bus very used in the industry, mainly to

communicate microcontrollers and their peripherals in integrated systems and generalizing more to communicate integrated circuits among themselves that normally reside

in a same printed circuit.


Hardware

IMPORTANT:  Make sure that your Ethernet PLC is powered (12-24Vdc). 

Switch configuration

To achieve I2C 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 I2C communication.

Used pins 

For Serial communication protocol the defined Arduino Mega pins are showed in the chart below: 


MDuino Ethernet PLC Pinout
Arduino Mega Pinout
SDA20
SCL21

Software


IMPORTANT:  Make sure to download the  Arduino based PLC boards  for Arduino IDE.

Example of Master Writer.

#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);
}
Example of Slave Receiver.

#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.

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-down

configuration. 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

IMPORTANT:  Make sure that your Ethernet PLC is powered (12-24Vdc). 

Switch configuration

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



Software

IMPORTANT:  Make sure to download the  Arduino based PLC boards  for Arduino IDE.

Example sketch - Digital Pot Control

  This example controls an Analog Devices AD5206 digital potentiometer.
  The AD5206 has 6 potentiometer channels. Each channel's pins are labeled
  A - connect this to voltage
  W - this is the pot's wiper, which changes when you set it
  B - connect this to ground.

 The AD5206 is SPI-compatible,and to command it, you send two bytes,
 one with the channel number (0 - 5) and one with the resistance value for the
 channel (0 - 255).

 The circuit:
  * All A pins  of AD5206 connected to +5V
  * All B pins of AD5206 connected to ground
  * An LED and a 220-ohm resisor in series connected from each W pin to ground
  * CS - to digital pin (SS pin)
  * SDI - to digital pin (MOSI pin)
  * CLK - to digital pin (SCK pin)


// 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

El término reloj en tiempo real se utiliza para evitar confusiones con los relojes de hardware ordinarios, que son solo señales que gobiernan la electrónica digital y no cuentan el tiempo en unidades humanas. RTC no debe confundirse con la computación en tiempo real, que comparte el acrónimo pero no se relaciona directamente con la hora del día.

Aunque el control del tiempo se puede hacer sin un RTC, usar uno tiene beneficios: - Bajo consumo de energía (importante cuando se ejecuta con energía alternativa - Libera el sistema principal para tareas de tiempo crítico - A veces más preciso que otros métodos

Hay una batería de celda de moneda de litio de 3,3 V que alimenta el RTC. El módulo RTC de M-Duinos se basa en el chip DS1307. El reloj serial en tiempo real (RTC) DS1307 es un reloj / calendario decimal codificado en binario completo (BCD) de baja potencia más 56 bytes de SRAM NV. La dirección y los datos se transfieren en serie a través de un bus bidireccional I2C. El reloj / calendario proporciona información sobre segundos, minutos, horas, día, fecha, mes y año. La fecha de fin de mes se ajusta automáticamente para los meses con menos de 31 días, incluidas las correcciones por año bisiesto. El reloj funciona en formato de 24 horas o de 12 horas con indicador AM / PM. El DS1307 tiene un circuito de detección de energía incorporado que detecta fallas de energía y cambia automáticamente a la fuente de respaldo. La operación de cronometraje continúa mientras la pieza opera desde el suministro de respaldo.


Configuración de hardware


IMPORTANTE:  Asegúrese de que su PLC Ethernet esté alimentado  (12-24Vdc) .

Configuración del interruptor

RTC trabaja con el protocolo de comunicación I2C, por lo que se requiere tener habilitado el protocolo I2C.

Se deben configurar 4 interruptores para habilitar las funciones de RTC y la comunicación I2C: 


INTERRUPTOR ON OFF
4 NC NC
3 NC
NC
2 RTC -
1 RTC -


RTC SCL  y  RTC SDA  debe configurarse en modo ON para habilitar los cables I2C al RTC. Si están en modo APAGADO, el Arduino no se comunicará con el RTC. 

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 RTC.h proporcionada en nuestras placas (RTC.h incluye inicialización I2C.h, por lo que no será necesario inicializar la librería I2C.h):

#include <RTC.h> 

Para verificar si el puerto RS-485 está funcionando, es fácil usar el monitor serial del IDE de Arduino usando la oración correcta dentro de la función setup ():

#Serial.begin(9600L) 

Example Code   

Prueba básica de RTC

// 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);
}

Know more about I2C.