Problema libreria SimpleModbus master

Buenos dias, estoy incursionando en arduino un poco mas avanzado y me encuentro en un problema de comunicacion con un arduino nano como maestro y dos variadores de frecuencia marca eura como esclavos, conexion rs485.

Arduino ejecuta el control de una confeccionadora de bolsas plasticas. solamente por ahora enciende los variadores y controla la frecuencia de funcionamiento de los mismos.

Si cuando inicia arduino mantengo apretado el boton de ON la maquina funciona y se comunican los variadores, pero si pasa la cantidad de intentos de "#define retry_count 5" y doy al boton de ON solo marca el primer parametro (que en este caso es frecuencia del variador 1) y no encienden ninguno ni cambia la frecuencia del otro variador.

En la libreria dice que cuando se excede el retry count se corta la comunicacion y para volverla a restablecer hay que poner la variable connection a true. cosa que a mi entender hago, pero no hace mas que solo enviar el primer parametro (frecuencia).

#include "SimpleModbusMaster.h"

bool m0=0, m_ON=0;


//////////////////// Port information ///////////////////
#define baud 9600
#define timeout 1000
#define polling 200 // the scan rate
#define retry_count 5

// used to toggle the receive/transmit pin on the driver
#define TxEnablePin 10 

// The total amount of available memory on the master to store data
#define TOTAL_NO_OF_REGISTERS 5
// This is the easiest way to create new packets
// Add as many as you want. TOTAL_NO_OF_PACKETS
// is automatically updated.
enum
{
  FREQ_CONFECC,
  ARR_CONFECC,
  FREQ_BOB,
  ARR_BOB,
  TOTAL_NO_OF_PACKETS // leave this last entry
};

// Create an array of Packets to be configured
Packet packets[TOTAL_NO_OF_PACKETS];

// Masters register array
unsigned int regs[TOTAL_NO_OF_REGISTERS];


void setup()
{
  delay(2500);
 // Initialize each packet
modbus_construct(&packets[FREQ_CONFECC], 2, PRESET_SINGLE_REGISTER, 269, 0, 0);
modbus_construct(&packets[ARR_CONFECC], 2, PRESET_SINGLE_REGISTER, 8192, 0, 1);
  
modbus_construct(&packets[FREQ_BOB], 3, PRESET_SINGLE_REGISTER, 269, 0, 2);
modbus_construct(&packets[ARR_BOB], 3, PRESET_SINGLE_REGISTER, 8192, 0, 3);

// Initialize the Modbus Finite State Machine
modbus_configure(&Serial, baud, SERIAL_8N2, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS, regs);

}

void loop(){
plc1.actualizacion(); //Actualizar las entradas y salidas
modbus_update();//actualizar comunicacion modbus



if (i7 == 1){ //i7 es marca de la lectura del pulsador

  if (m0==0){ //se ejecuta una sola vez al comienzo
    m0=1;
    packets->connection=1;
    modbus_update();//actualizar comunicacion modbus    
    m_ON=1;
  }

}

if (m_ON == 1){ //ejecutar si esta en ciclo de encendido
    
    regs[0]=2244;   
    regs[1]=1;
    regs[2]=2244;
    regs[3]=1;
}


}

esta en fase desarrollo y desprolijo por partes, el codigo es para explicar lo que quiero hacer, que al inicio anda pero despues no puedo abrir la comunicacion de nuevo.

Muchas gracias!

EDITO:

void loop(){

modbus_update();

regs[0]=2000;
if(i7==0){
  regs[1]=1;
}

 
if (i7==1){
  regs[1]=0;
}

}

Este Codigo no funciona como esperaria, ejecuta el inicio al tener el pulsador en pull down, arranca el variador, pero al pulsar i7 no hace nada, no vuelve a escribir el registro con el valor 0, creeria estarme equivocando en como escribir los regs.
(i7 funciona, es una marca de un pulsador en el pin 7 que ya vine usando)

si tienen una idea estaria agradecido!

saludos

En el código que muestras (más allá de que no comparta el estilo) no veo ningún problema pero tampoco veo el código del pulsador que cambia i7 ni la definición del array regs, o sea, lo que podría estar fallando no lo vemos. El código en trozos no sirve.
Así es muy difícil darte alguna ayuda.

Saludos

Hola si disculpame, el codigo en general son banderas que se activan con if dependiendo de las entradas, lo actualiza una funcion.
Tengo mas pruebas con codigo completo.

El primer codigo no funciona. cuando excede los intentos de comunicacion sin apretar el boton, y uno apreta el boton de la freq (pin8) la frecuencia se actualiza. si apretas el pin 9 no sucede nada.

#include "SimpleModbusMaster.h"

/*
   The example will use packet1 to read a register from address 0 (the adc ch0 value)
   from the arduino slave (id=1). It will then use this value to adjust the brightness
   of an led on pin 9 using PWM.
   It will then use packet2 to write a register (its own adc ch0 value) to address 1 
   on the arduino slave (id=1) adjusting the brightness of an led on pin 9 using PWM.
*/

//////////////////// Port information ///////////////////
#define baud 9600
#define timeout 1000
#define polling 900 // the scan rate
#define retry_count 5

// used to toggle the receive/transmit pin on the driver
#define TxEnablePin 10



// The total amount of available memory on the master to store data
#define TOTAL_NO_OF_REGISTERS 5

// This is the easiest way to create new packets
// Add as many as you want. TOTAL_NO_OF_PACKETS
// is automatically updated.
enum
{
  PACKET1,
  PACKET2,
  TOTAL_NO_OF_PACKETS // leave this last entry
};

// Create an array of Packets to be configured
Packet packets[TOTAL_NO_OF_PACKETS];

// Masters register array
unsigned int regs[TOTAL_NO_OF_REGISTERS];

void setup()
{
  // Initialize each packet
  modbus_construct(&packets[PACKET1], 2, PRESET_SINGLE_REGISTER, 269, 0, 0);
  modbus_construct(&packets[PACKET2], 2, PRESET_SINGLE_REGISTER, 8192, 0, 1);
  
  // Initialize the Modbus Finite State Machine
  modbus_configure(&Serial, baud, SERIAL_8N2, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS, regs);
  pinMode(9,INPUT_PULLUP);
  pinMode(8,INPUT_PULLUP);
  pinMode(10, OUTPUT);
}

void loop()
{
  modbus_update();

if (digitalRead(8)==0) {
  packets->connection=1;
 regs[0]=2000; //PACKET1, direccion del variador 269, establecer frecuencia a 20.00Hz
}


if(digitalRead(9)==0){
  packets->connection=1;
  regs[1]=1;  //PACKET2, direccion del variador 8192, RUN
}
  
}

El siguiente codigo si funciona independientemente del tiempo, pero en este intento arduino esta siempre escribiendo el regs[0], por lo que entiendo que no llega nunca a no haber conexion y no cae a cero la variable connection de la libreria.. no se si me explico bien..

#include "SimpleModbusMaster.h"

/*
   The example will use packet1 to read a register from address 0 (the adc ch0 value)
   from the arduino slave (id=1). It will then use this value to adjust the brightness
   of an led on pin 9 using PWM.
   It will then use packet2 to write a register (its own adc ch0 value) to address 1 
   on the arduino slave (id=1) adjusting the brightness of an led on pin 9 using PWM.
*/

//////////////////// Port information ///////////////////
#define baud 9600
#define timeout 1000
#define polling 900 // the scan rate
#define retry_count 5

// used to toggle the receive/transmit pin on the driver
#define TxEnablePin 10



// The total amount of available memory on the master to store data
#define TOTAL_NO_OF_REGISTERS 5

// This is the easiest way to create new packets
// Add as many as you want. TOTAL_NO_OF_PACKETS
// is automatically updated.
enum
{
  PACKET1,
  PACKET2,
  TOTAL_NO_OF_PACKETS // leave this last entry
};

// Create an array of Packets to be configured
Packet packets[TOTAL_NO_OF_PACKETS];

// Masters register array
unsigned int regs[TOTAL_NO_OF_REGISTERS];

void setup()
{
  // Initialize each packet
  modbus_construct(&packets[PACKET1], 2, PRESET_SINGLE_REGISTER, 269, 0, 0);
  modbus_construct(&packets[PACKET2], 2, PRESET_SINGLE_REGISTER, 8192, 0, 1);
  
  // Initialize the Modbus Finite State Machine
  modbus_configure(&Serial, baud, SERIAL_8N2, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS, regs);
  pinMode(9,INPUT_PULLUP);
  pinMode(10, OUTPUT);
}

void loop()
{
  modbus_update();
  
 regs[0]=2000; //PACKET1, direccion del variador 269, establecer frecuencia a 20.00Hz

if(digitalRead(9)==0){
  regs[1]=1;//PACKET2, direccion del variador 8192, RUN
}

 
if (digitalRead(9)==1){
  regs[1]=4; //PACKET2, direccion del variador 8192, valor 4, STOP
}
  
  }

La definicion de la matriz no la tengo del todo clara, estoy investigando en la libreria pero empieza en : "// Masters register array
unsigned int regs[TOTAL_NO_OF_REGISTERS];"

gracias!

Y si, si le asignas 2000 sin ninguna condición es lógico que lo asigne en cada reinicio del loop()

Ah, ok, está definida en la librería, deberías aclarar esas cosas.

Saludos

¿De donde descargaste la librería? Si estas intentando comunicarte con dos esclavos (supongo que ambos tiene diferente direcciones ) no veo donde los direccionas.

en los ultimos dos codigos simplifique a un solo variador, dos direcciones distintas de registro, la 269 que es frecuencia y la 8192 que es el registro de on off etc..

la libreria me la paso compartiendo la carpeta el que la escribio, y esos dos codigos ultimos son modificaciones al ejemplo que viene con la libreria.

la libreria es esta https://github.com/jecrespo/simple-modbus

Gracias

Ésta que adjuntas es la tercera librería que veo, por eso se pide que junto al include se ponga el link a la librería, asi no se pierde tiempo buscando y revisando las librerías equivocadas.

Saludos

Cuando postees un programa como este que tiene problemas de librería sigue el consejo de @anon90500195 y haz esto

#include "SimpleModbusMaster.h"  //https://github.com/pepsilla/Arduino/tree/master/MODBUS/ASCII/libraries/SimpleModbusMaster

Y algo asi no da lugar a dudas, ni para ti mismo que luego de unos meses no recordarás de donde la descargado.

Muchas gracias por las correcciones y me disculpo.
También hay un manual en PDF de la librería en el link.

Sigo haciendo pruebas y leyendo, el problema principal que encuentro es cuando hay que restablecer la comunicación ( packets->connection=1; ) que es cuando solo actualiza el regs[0], si no hace falta restablecer la comunicación, escribe en todos los regs al parecer.

Me gusta esta librería por sobre ModbusMaster ( https://github.com/4-20ma/ModbusMaster )por que encuentro que modbusMaster hace un while mientras envía los mensajes (corrijanme si me equívoco) y eso me genera problemas al leer entradas en el programa.

Si tienen alguna idea que podría estar fallando o que librería pudiera usar, se los agradecería!

muchas gracias!

Hay 3 ejemplos en ModbusMaster, dime donde esta el while al que refieres?

Claramente mis dudas se deben en grandisima parte a que no es mi fuerte la programación pero siguiendo la libreria encuentro esto:

// flush receive buffer before transmitting request
  while (_serial->read() != -1);

  // transmit request
  if (_preTransmission)
  {
    _preTransmission();
  }
  for (i = 0; i < u8ModbusADUSize; i++)
  {
    _serial->write(u8ModbusADU[i]);
  }
  
  u8ModbusADUSize = 0;
  _serial->flush();    // flush transmit buffer
  if (_postTransmission)
  {
    _postTransmission();
  }
  
  // loop until we run out of time or bytes, or an error occurs
  u32StartTime = millis();

A partir de linea Nº 600 de https://github.com/4-20ma/ModbusMaster/blob/master/src/ModbusMaster.cpp

por lo que entiendo la funcion "ModbusMasterTransaction" es la que genera la trama y la envia..

Pero eso es para leer la trama de bytes y como mucho son supongamos 32 bytes, dices que eso te genera problemas al leer tus entradas?

Sigo leyendo ahora ModbusMaster..

 // transmit request
  if (_preTransmission)
  {
    _preTransmission();
  }
  for (i = 0; i < u8ModbusADUSize; i++)
  {
    _serial->write(u8ModbusADU[i]);
  }
  
  u8ModbusADUSize = 0;
  _serial->flush();    // flush transmit buffer
  if (_postTransmission)
  {
    _postTransmission();
  }
  

el "_serial->flush()" no se entiende como el serial.flush(); que espera a que se envien los datos?

si fuera así una trama de 8 bytes (son las comunes que estoy usando en esta aplicación) me costarían @ 9600 baudios= 8*8 / 9600 = 0.00666
0.0666 + espera del inicio mas espera del final 3.5 tiempos = 0.0066+ 0.003+0.003 aprox 10 ms. estaría bien la cuenta así?
eso mas la espera de recibida del esclavo serian aproximadamente 20ms, por 3 variadores (las fallas suelen ser cada tanto..)son 60 ms mas los delay de pretransmision y postransmision diría que redondeo los 90ms.

Los pulsadores se actualizan en cada ciclo de programa, el programa en si trabaja con marcadores de esos pulsadores, el pin 9 es la marca i7, si i7=1 pin 9 high. sospecho que esa tabla no se actualiza bien por las paradas de la comunicación, por que sin comunicación funcionan, y cuando fallan puedo ver que quizas no se envia el dato de parada de algun variador, o el dato de arranque de un variador, por ejemplo (me doy cuenta que un motor no paro cuando deberia o no arranco cuando deberia)

PD: cuestion que razono todavía, si se tarda tan poco en enviar el mensaje como puedo ver el tx y rx parpadear?

muchas gracias

Porque estas intentando actualizar cada ciclo de loop, dependiendo quien haya sido el programador de la libreria eso puede ser un problema. Prueba colocar un delay en el loop

Hola gracias por responder, ese codigo es el que anda, si actualizo regs en todo momento durante el inicio, es decir que no dejo que pase sin actualizar un tiempo.. no cae la variable connection y por ende me anda el resto.. el asunto esta cuando cae connection, que ya cuando la vuelvo a poner en "1" solo actualiza el regs[0]

Estaba compilando con Visual Studio Code, fui al ide de arduino al 1.8.13 y me salen muchos errores de compilador. algunos creo yo que razonables. ejemplo

unsigned char construct_F15()

{
	// function 15 coil information is packed LSB first until the first 16 bits are completed
  // It is received the same way..
  unsigned char no_of_registers = packet->data / 16;
  unsigned char no_of_bytes = no_of_registers * 2; 
	
  // if the number of points dont fit in even 2byte amounts (one register) then use another register and pad 
  if (packet->data % 16 > 0) 
  {
    no_of_registers++;
    no_of_bytes++;
  }


  frame[6] = no_of_bytes;
  unsigned char bytes_processed = 0;
  unsigned char index = 7; // user data starts at index 7
	unsigned int temp;
	
  for (unsigned char i = 0; i < no_of_registers; i++)
  {
    temp = register_array[packet->local_start_address + i]; // get the data
    frame[index] = temp & 0xFF; 
    bytes_processed++;
     
    if (bytes_processed < no_of_bytes)
    {
      frame[index + 1] = temp >> 8;
      bytes_processed++;
      index += 2;
    }
  }
	unsigned char frameSize = (9 + no_of_bytes); // first 7 bytes of the array + 2 bytes CRC + noOfBytes 
	return frameSize;
}

me sale por ejemplo, redefinido construct_F15() y es cierto por que se redefine en linea 36, comento y me salen otros errores.. estoy rastreandolo.

despues del construct_F15() hay unos corchetes que se abren sin ser ni funcion ni nada y engloban lo que seria una posible funcion construct_F15(), pero sin definir.. que significa eso? Tambien me sale en error de compilacion..

pongo la libreria completa que tengo y que me compartió quien la escribio:

#include "SimpleModbusMaster.h"
#include "HardwareSerial.h"

// SimpleModbusMasterV2rev2

// state machine states
#define IDLE 1
#define WAITING_FOR_REPLY 2
#define WAITING_FOR_TURNAROUND 3

#define BUFFER_SIZE 64

unsigned char state;
unsigned char retry_count;
unsigned char TxEnablePin;

// frame[] is used to receive and transmit packages. 
// The maximum number of bytes in a modbus packet is 256 bytes
// This is limited to the serial buffer of 64 bytes
unsigned char frame[BUFFER_SIZE]; 
unsigned char buffer;
long timeout; // timeout interval
long polling; // turnaround delay interval
unsigned int T1_5; // inter character time out in microseconds
unsigned int frameDelay; // frame time out in microseconds
long delayStart; // init variable for turnaround and timeout delay
unsigned int total_no_of_packets; 
Packet* packetArray; // packet starting address
Packet* packet; // current packet
unsigned int* register_array; // pointer to masters register array
HardwareSerial* ModbusPort;

// function definitions
void idle();
void constructPacket();
unsigned char construct_F15();
unsigned char construct_F16();
void waiting_for_reply();
void processReply();
void waiting_for_turnaround();
void process_F1_F2();
void process_F3_F4();
void process_F5_F6_F15_F16();
void processError();
void processSuccess();
unsigned int calculateCRC(unsigned char bufferSize);
void sendPacket(unsigned char bufferSize);

// Modbus Master State Machine
void modbus_update() 
{
	switch (state)
	{
		case IDLE:
		idle();
		break;
		case WAITING_FOR_REPLY:
		waiting_for_reply();
		break;
		case WAITING_FOR_TURNAROUND:
		waiting_for_turnaround();
		break;
	}
}

void idle()
{
  static unsigned int packet_index;	
	
	unsigned int failed_connections = 0;
	
	unsigned char current_connection;
	
	do
	{		
		if (packet_index == total_no_of_packets) // wrap around to the beginning
			packet_index = 0;
				
		// proceed to the next packet
		packet = &packetArray[packet_index];
		
		// get the current connection status
		current_connection = packet->connection;
		
		if (!current_connection)
		{			
			// If all the connection attributes are false return
			// immediately to the main sketch
			if (++failed_connections == total_no_of_packets)
				return;
		}
		packet_index++;     
    
	// if a packet has no connection get the next one		
	}while (!current_connection); 
		
	constructPacket();
}
  
void constructPacket()
{	 
  packet->requests++;
  frame[0] = packet->id;
  frame[1] = packet->function;
  frame[2] = packet->address >> 8; // address Hi
  frame[3] = packet->address & 0xFF; // address Lo
	
	// For functions 1 & 2 data is the number of points
	// For function 5 data is either ON (0xFF00) or OFF (0x0000)
	// For function 6 data is exactly that, one register's data
  // For functions 3, 4 & 16 data is the number of registers
  // For function 15 data is the number of coils
	
	// The data attribute needs to be intercepted by F5 & F6 because these requests
	// include their data in the data register and not in the masters array
	if (packet->function == FORCE_SINGLE_COIL || packet->function == PRESET_SINGLE_REGISTER) 
		packet->data = register_array[packet->local_start_address]; // get the data
	
	
	frame[4] = packet->data >> 8; // MSB
	frame[5] = packet->data & 0xFF; // LSB
	
	unsigned char frameSize;    
	
  // construct the frame according to the modbus function  
  if (packet->function == PRESET_MULTIPLE_REGISTERS) 
		frameSize = construct_F16();
	else if (packet->function == FORCE_MULTIPLE_COILS)
		frameSize = construct_F15();
	else // else functions 1,2,3,4,5 & 6 is assumed. They all share the exact same request format.
    frameSize = 8; // the request is always 8 bytes in size for the above mentioned functions.
		
	unsigned int crc16 = calculateCRC(frameSize - 2);	
  frame[frameSize - 2] = crc16 >> 8; // split crc into 2 bytes
  frame[frameSize - 1] = crc16 & 0xFF;
  sendPacket(frameSize);

	state = WAITING_FOR_REPLY; // state change
	
	// if broadcast is requested (id == 0) for function 5,6,15 and 16 then override 
  // the previous state and force a success since the slave wont respond
	if (packet->id == 0)
			processSuccess();
}

unsigned char construct_F15()
{
	// function 15 coil information is packed LSB first until the first 16 bits are completed
  // It is received the same way..
  unsigned char no_of_registers = packet->data / 16;
  unsigned char no_of_bytes = no_of_registers * 2; 
	
  // if the number of points dont fit in even 2byte amounts (one register) then use another register and pad 
  if (packet->data % 16 > 0) 
  {
    no_of_registers++;
    no_of_bytes++;
  }
	
  frame[6] = no_of_bytes;
  unsigned char bytes_processed = 0;
  unsigned char index = 7; // user data starts at index 7
	unsigned int temp;
	
  for (unsigned char i = 0; i < no_of_registers; i++)
  {
    temp = register_array[packet->local_start_address + i]; // get the data
    frame[index] = temp & 0xFF; 
    bytes_processed++;
     
    if (bytes_processed < no_of_bytes)
    {
      frame[index + 1] = temp >> 8;
      bytes_processed++;
      index += 2;
    }
  }
	unsigned char frameSize = (9 + no_of_bytes); // first 7 bytes of the array + 2 bytes CRC + noOfBytes 
	return frameSize;
}

unsigned char construct_F16()
{
	unsigned char no_of_bytes = packet->data * 2; 
    
  // first 6 bytes of the array + no_of_bytes + 2 bytes CRC 
  frame[6] = no_of_bytes; // number of bytes
  unsigned char index = 7; // user data starts at index 7
	unsigned char no_of_registers = packet->data;
	unsigned int temp;
		
  for (unsigned char i = 0; i < no_of_registers; i++)
  {
    temp = register_array[packet->local_start_address + i]; // get the data
    frame[index] = temp >> 8;
    index++;
    frame[index] = temp & 0xFF;
    index++;
  }
	unsigned char frameSize = (9 + no_of_bytes); // first 7 bytes of the array + 2 bytes CRC + noOfBytes 
	return frameSize;
}

void waiting_for_turnaround()
{
  if ((millis() - delayStart) > polling)
		state = IDLE;
}

// get the serial data from the buffer
void waiting_for_reply()
{
	if ((*ModbusPort).available()) // is there something to check?
	{
		unsigned char overflowFlag = 0;
		buffer = 0;
		while ((*ModbusPort).available())
		{
			// The maximum number of bytes is limited to the serial buffer size 
      // of BUFFER_SIZE. If more bytes is received than the BUFFER_SIZE the 
      // overflow flag will be set and the serial buffer will be read until
      // all the data is cleared from the receive buffer, while the slave is 
      // still responding.
			if (overflowFlag) 
				(*ModbusPort).read();
			else
			{
				if (buffer == BUFFER_SIZE)
					overflowFlag = 1;
			
				frame[buffer] = (*ModbusPort).read();
				buffer++;

			}
			// This is not 100% correct but it will suffice.
			// worst case scenario is if more than one character time expires
			// while reading from the buffer then the buffer is most likely empty
			// If there are more bytes after such a delay it is not supposed to
			// be received and thus will force a frame_error.
			delayMicroseconds(T1_5); // inter character time out
		}
			
		// The minimum buffer size from a slave can be an exception response of
    // 5 bytes. If the buffer was partially filled set a frame_error.
		// The maximum number of bytes in a modbus packet is 256 bytes.
		// The serial buffer limits this to 64 bytes.
	
		if ((buffer < 5) || overflowFlag)
			processError();       
      
		// Modbus over serial line datasheet states that if an unexpected slave 
    // responded the master must do nothing and continue with the time out.
		// This seems silly cause if an incorrect slave responded you would want to
    // have a quick turnaround and poll the right one again. If an unexpected 
    // slave responded it will most likely be a frame error in any event
		else if (frame[0] != packet->id) // check id returned
			processError();
		else
			processReply();
	}
	else if ((millis() - delayStart) > timeout) // check timeout
	{
		processError();
		state = IDLE; //state change, override processError() state
	}
}

void processReply()
{
	// combine the crc Low & High bytes
  unsigned int received_crc = ((frame[buffer - 2] << 8) | frame[buffer - 1]); 
  unsigned int calculated_crc = calculateCRC(buffer - 2);
	
	if (calculated_crc == received_crc) // verify checksum
	{
		// To indicate an exception response a slave will 'OR' 
		// the requested function with 0x80 
		if ((frame[1] & 0x80) == 0x80) // extract 0x80
		{
			packet->exception_errors++;
			processError();
		}
		else
		{
			switch (frame[1]) // check function returned
      {
        case READ_COIL_STATUS:
        case READ_INPUT_STATUS:
        process_F1_F2();
        break;
        case READ_INPUT_REGISTERS:
        case READ_HOLDING_REGISTERS:
        process_F3_F4();
        break;
				case FORCE_SINGLE_COIL:
				case PRESET_SINGLE_REGISTER:
        case FORCE_MULTIPLE_COILS:
        case PRESET_MULTIPLE_REGISTERS:
        process_F5_F6_F15_F16();
        break;
        default: // illegal function returned
        processError();
        break;
      }
		}
	} 
	else // checksum failed
	{
		processError();
	}
}

void process_F1_F2()
{
	// packet->data for function 1 & 2 is actually the number of boolean points
  unsigned char no_of_registers = packet->data / 16;
  unsigned char number_of_bytes = no_of_registers * 2; 
       
  // if the number of points dont fit in even 2byte amounts (one register) then use another register and pad 
  if (packet->data % 16 > 0) 
  {
    no_of_registers++;
    number_of_bytes++;
  }
             
  if (frame[2] == number_of_bytes) // check number of bytes returned
  { 
    unsigned char bytes_processed = 0;
    unsigned char index = 3; // start at the 4th element in the frame and combine the Lo byte  
    unsigned int temp;
    for (unsigned char i = 0; i < no_of_registers; i++)
    {
      temp = frame[index]; 
      bytes_processed++;
      if (bytes_processed < number_of_bytes)
      {
				temp = (frame[index + 1] << 8) | temp;
        bytes_processed++;
        index += 2;
      }
      register_array[packet->local_start_address + i] = temp;
    }
    processSuccess(); 
  }
  else // incorrect number of bytes returned 
    processError();
}

void process_F3_F4()
{
	// check number of bytes returned - unsigned int == 2 bytes
  // data for function 3 & 4 is the number of registers
  if (frame[2] == (packet->data * 2)) 
  {
    unsigned char index = 3;
    for (unsigned char i = 0; i < packet->data; i++)
    {
      // start at the 4th element in the frame and combine the Lo byte 
      register_array[packet->local_start_address + i] = (frame[index] << 8) | frame[index + 1]; 
      index += 2;
    }
    processSuccess(); 
  }
  else // incorrect number of bytes returned  
    processError();  
}

void process_F5_F6_F15_F16()
{
	// The repsonse of functions 5,6,15 & 16 are just an echo of the query
  unsigned int recieved_address = ((frame[2] << 8) | frame[3]);
  unsigned int recieved_data = ((frame[4] << 8) | frame[5]);
		
  if ((recieved_address == packet->address) && (recieved_data == packet->data))
    processSuccess();
  else
    processError();
}

void processError()
{
	packet->retries++;
	packet->failed_requests++;
	
	// if the number of retries have reached the max number of retries 
  // allowable, stop requesting the specific packet
  if (packet->retries == retry_count)
	{
    packet->connection = 0;
	packet->retries = 0;
	}
	state = WAITING_FOR_TURNAROUND;
	delayStart = millis(); // start the turnaround delay
}

void processSuccess()
{
	packet->successful_requests++; // transaction sent successfully
	packet->retries = 0; // if a request was successful reset the retry counter
	state = WAITING_FOR_TURNAROUND;
	delayStart = millis(); // start the turnaround delay
}
  
void modbus_configure(HardwareSerial* SerialPort,
											long baud,
											unsigned char byteFormat,
											long _timeout, 
											long _polling, 
											unsigned char _retry_count, 
											unsigned char _TxEnablePin, 
											Packet* _packets, 
											unsigned int _total_no_of_packets,
											unsigned int* _register_array)
{ 
	// Modbus states that a baud rate higher than 19200 must use a fixed 750 us 
  // for inter character time out and 1.75 ms for a frame delay for baud rates
  // below 19200 the timing is more critical and has to be calculated.
  // E.g. 9600 baud in a 11 bit packet is 9600/11 = 872 characters per second
  // In milliseconds this will be 872 characters per 1000ms. So for 1 character
  // 1000ms/872 characters is 1.14583ms per character and finally modbus states
  // an inter-character must be 1.5T or 1.5 times longer than a character. Thus
  // 1.5T = 1.14583ms * 1.5 = 1.71875ms. A frame delay is 3.5T.
	// Thus the formula is T1.5(us) = (1000ms * 1000(us) * 1.5 * 11bits)/baud
	// 1000ms * 1000(us) * 1.5 * 11bits = 16500000 can be calculated as a constant
	
	if (baud > 19200)
		T1_5 = 750; 
	else 
		T1_5 = 16500000/baud; // 1T * 1.5 = T1.5
		
	/* The modbus definition of a frame delay is a waiting period of 3.5 character times
		 between packets. This is not quite the same as the frameDelay implemented in
		 this library but does benifit from it.
		 The frameDelay variable is mainly used to ensure that the last character is 
		 transmitted without truncation. A value of 2 character times is chosen which
		 should suffice without holding the bus line high for too long.*/
		 
	frameDelay = T1_5 * 2; 
	
	// initialize
	state = IDLE;
  timeout = _timeout;
  polling = _polling;
	retry_count = _retry_count;
	TxEnablePin = _TxEnablePin;
	total_no_of_packets = _total_no_of_packets;
	packetArray = _packets;
	register_array = _register_array;
	
	ModbusPort = SerialPort;
	(*ModbusPort).begin(baud, byteFormat);
	
	pinMode(TxEnablePin, OUTPUT);
  digitalWrite(TxEnablePin, LOW);
	
} 

void modbus_construct(Packet *_packet, 
											unsigned char id, 
											unsigned char function, 
											unsigned int address, 
											unsigned int data,
											unsigned int local_start_address)
{
	_packet->id = id;
  _packet->function = function;
  _packet->address = address;
  _packet->data = data;
	_packet->local_start_address = local_start_address;
	_packet->connection = 1;
}

unsigned int calculateCRC(unsigned char bufferSize) 
{
  unsigned int temp, temp2, flag;
  temp = 0xFFFF;
  for (unsigned char i = 0; i < bufferSize; i++)
  {
    temp = temp ^ frame[i];
    for (unsigned char j = 1; j <= 8; j++)
    {
      flag = temp & 0x0001;
      temp >>= 1;
      if (flag)
        temp ^= 0xA001;
    }
  }
  // Reverse byte order. 
  temp2 = temp >> 8;
  temp = (temp << 8) | temp2;
  temp &= 0xFFFF;
  // the returned value is already swapped
  // crcLo byte is first & crcHi byte is last
  return temp; 
}

void sendPacket(unsigned char bufferSize)
{
	digitalWrite(TxEnablePin, HIGH);
		
	for (unsigned char i = 0; i < bufferSize; i++)
		(*ModbusPort).write(frame[i]);
		
	(*ModbusPort).flush();
	
	delayMicroseconds(frameDelay);
	
	digitalWrite(TxEnablePin, LOW);
		
	delayStart = millis(); // start the timeout delay	
}

Saludos

Moderador
Este tema es similar al de SimpleModbusMaster y constituye una falta a las normas.
Te voy a pedir que no vuelvas a hacerlo y ahora viene el problema, porque se van a entremezclar los temas si los unifico y no se va a entender nada.
Tienes 1 primer advertencia por haberlo hecho, asi que no reiteres temas similares, puedes plantearlos dentro de un mismo hilo.
Cerré el hilo de ModbusMaster temporalmente.

Dos librerias distintas con dos problemas distintos. uno no compila y el otro con otra libreria ralentiza y hace erronea (aparentemente) la ejecucion del codigo lo unico similar es quien postea y que son dos temas sobre MODBUS y rs485.

Si hubo un error en mi concepto de similitud con respecto al del foro pido disculpas.

saludos

Lo que yo veo...

Partiendo del código del primer post:

#include "SimpleModbusMaster.h"

bool m0=0, m_ON=0;


//////////////////// Port information ///////////////////
#define baud 9600
#define timeout 1000
#define polling 200 // the scan rate
#define retry_count 5

// used to toggle the receive/transmit pin on the driver
#define TxEnablePin 10 


#define TOTAL_NO_OF_REGISTERS 5

enum
{
  FREQ_CONFECC,
  ARR_CONFECC,
  FREQ_BOB,
  ARR_BOB,
  TOTAL_NO_OF_PACKETS 
};


Packet packets[TOTAL_NO_OF_PACKETS];
unsigned int regs[TOTAL_NO_OF_REGISTERS];


void setup()
{
  delay(2500);
                  // Packet,              id,               function,  addr, data, local
  modbus_construct(&packets[FREQ_CONFECC], 2, PRESET_SINGLE_REGISTER,   269,    0,     0);
  modbus_construct(&packets[ARR_CONFECC],  2, PRESET_SINGLE_REGISTER, 8192,     0,     1);
  modbus_construct(&packets[FREQ_BOB],     3, PRESET_SINGLE_REGISTER,  269,     0,     2);
  modbus_construct(&packets[ARR_BOB],      3, PRESET_SINGLE_REGISTER, 8192,     0,     3);

  // Initialize the Modbus Finite State Machine
  modbus_configure(&Serial, baud, SERIAL_8N2, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS, regs);

}

void loop(){

  plc1.actualizacion(); //Actualizar las entradas y salidas
  modbus_update();//actualizar comunicacion modbus



  if (i7 == 1){ 
	  //i7 es marca de la lectura del pulsador
    if (m0==0){ //se ejecuta una sola vez al comienzo
      m0=1;
      packets->connection=1;
      modbus_update();//actualizar comunicacion modbus    
      m_ON=1;
    }
   }

if (m_ON == 1){ //ejecutar si esta en ciclo de encendido
    
    regs[0]=2244;   
    regs[1]=1;
    regs[2]=2244;
    regs[3]=1;
}


}

Independientemente de lo que pretendas hacer te aviso de que la libreria no funciona como tu crees.

ModBus es un protocolo orientado a registros y la libreria SimpleModbusMaster funciona de esta manera.

Por un lado se definen las consultas, creando un array de Packet. En cada packet indicamos la dirección del esclavo, el tipo de consulta, la dirección y los datos y la dirección local

La dirección local es la posición dentro de un array donde se especifican los registros internos del maestro.

Cuando la consulta es una escritura, la libreria busca el dato que se quiere escribir dentro de los registros locales. Por ejemplo: para encender el variador tienes que ir hacer que el registro en el array regs tenga un valor o no.

Si la consulta es una lectura, la libreria guardará el dato que reciba dentro del array regs

Creo que hasta ahí mas o menos lo tienes entendido dentro del código. Pero veo que cometes varios errores.

El primero de ellos es que llamas a la función modbus_update si la entrada está activa. Eso es redundante y puede provocar fallos. Por lo tanto debes eliminar esa llamada y dejar solo una llamada a la función al inicio del loop.

Otro fallo, que no es tuyo si no del compilador es la siguiente linea:

packets->connection = 1;

Aunque el compilador no da error, eso es un error garrafal. Packets es un array que apunta a objetos Packet y no debería colar el apuntador sin direccionar el array.

Veamos lo que te quiero decir. Tu tienes cuatro paquetes, y quiere habilitar o deshabilitar la conexión. Por lo tanto debes acceder a cada paquete de manera independiente:

// Pongo 1, pero también puede ser cero.
packets[FREQ_CONFECC].connection = 1;
packets[ARR_CONFECC].connection = 1;,
packets[FREQ_BOB].connection = 1;
packets[ARR_BOB].conecction = 1;

La variable connection puede usarse de manera que una consulta se ejecute o no, por ejemplo para evitar escrituras todo el rato.

En tu código general, ese error del compilador, puede provocar que no se ejecuten ninguna de las otras consultas.

En lo personal, la libreria SimpleModbusSlave es buena, pero mejorable, de hecho lo hice en su momento y tengo una libreria personalizada que uso en mis proyectos. La libreria SimpleModbusMaster tiene sus defectos y no he llegado a utilizarla. Uno de ellos es la escritura. Con el método polling, no existe manera de que podamos controlar bien que solo queremos escribir un registro una sola vez. Por ejemplo si quieres encender el variador, con que escribas una vez el registro una sola vez el valor 1 sobra, pero cuantas veces se escribirá hasta que puedas controlar que la escritura se ha hecho???.

Espero te sirva de ayuda.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.