Arduino UNO + AutoGRAPH по RS 485 Modbus или LLS

Обсуждаем Arduino, Raspberry Pi и другие электронные компоненты и проекты DIY
Ответить
stapmoff
Сообщения: 18
Зарегистрирован: 16 май 2016, 18:04

Arduino UNO + AutoGRAPH по RS 485 Modbus или LLS

Сообщение stapmoff »

Простите и сильно не ругайте, если есть подобные темы, но я не силен в программировании на С. Дело в следующем, есть контроллер АвтоГРАФ имеющий интерфейс RS485 c протаколом Modbus и LLS. Моя задача прикрутить к ардутно датчик влажности и передовать данные в виде АЦП от 0 до 4095 по 485 -му. Я датчик то прикрутил и он работает, выводит показания на LCD, Modbus я тоже организовал, но ардуино просто непрерывно шлет в Автограф, а тот не понимает, так как не организован формат 8-N-1 или использовать протокол LLS. Подскажите как наладить общение этих девайсов???????
Прикладываю свой скетч (использовал FLProg)

Код: Выделить всё

#include <LiquidCrystal.h>
#include <ModbusRtu.h>

LiquidCrystal _lcd1(12, 11, 5, 4, 3, 2);

int 		_dispTempLength1=0;
boolean 	_isNeedClearDisp1;
Modbus 	_modbusSlave(10, 0, 7);
uint16_t 	_ModbusReg[1];
int 		_gtv1;
int 		_disp1oldLength = 0;

void setup()
{
	_modbusSlave.begin(19200);
	_lcd1.begin(16, 2);
}

void loop()
{
	_modbusSlave.poll(_ModbusReg, 1);
	
	if (_isNeedClearDisp1) {
		_lcd1.clear(); _isNeedClearDisp1= 0;
	}

	if (1) {
		_dispTempLength1 = ((((String("H = ")) + ((String(( (analogRead (5)))/(11)))) + (String("%"))))).length();
		if (_disp1oldLength > _dispTempLength1) {_isNeedClearDisp1 = 1;} 
		_disp1oldLength = _dispTempLength1;
		_lcd1.setCursor(0, 0);
		_lcd1.print((((String("H = ")) + ((String(( (analogRead (5)))/(11)))) + (String("%")))));
	} else {
		if (_disp1oldLength > 0) {
			_isNeedClearDisp1 = 1;
			_disp1oldLength = 0;
		} 
	}
	
	_gtv1 =  (analogRead (5));
	_ModbusReg[0] = _gtv1;
}
Аватара пользователя
Mr.Kubikus
Сотрудник ПАКПАК
Сообщения: 1018
Зарегистрирован: 22 окт 2010, 23:57

Re: Arduino UNO + AutoGRAPH по RS 485 Modbus или LLS

Сообщение Mr.Kubikus »

Привет!

Хорошо бы понять, что за зверь такой скрывается за ModbusRtu.h. Есть описание этой библиотеки?
С уважением, Григорий
GitHub FB ВК
stapmoff
Сообщения: 18
Зарегистрирован: 16 май 2016, 18:04

Re: Arduino UNO + AutoGRAPH по RS 485 Modbus или LLS

Сообщение stapmoff »

Вот ссылка на библиотеку https://cloud.mail.ru/public/21w9/5aRzzwQNq
stapmoff
Сообщения: 18
Зарегистрирован: 16 май 2016, 18:04

Re: Arduino UNO + AutoGRAPH по RS 485 Modbus или LLS

Сообщение stapmoff »

Я понимаю, что может проблема в библиотеке и немного в коде, я пытался менять библиотеку, находил на форумах, но результат один - это ошибка компиляции(( Уже месяц мучаюсь и не могу ни как понять в чем дело? А изучачь язык Си, времени совсем нет
stapmoff
Сообщения: 18
Зарегистрирован: 16 май 2016, 18:04

Re: Arduino UNO + AutoGRAPH по RS 485 Modbus или LLS

Сообщение stapmoff »

Я так понимаю мне нужен вот этот скетч? Но как его, так сказать скрестить с моим????

Код: Выделить всё

#include <SimpleModbusSlave.h>

/* 
   SimpleModbusSlaveV10 supports function 3, 6 & 16.
   
   This example code will receive the adc ch0 value from the arduino master. 
   It will then use this value to adjust the brightness of the led on pin 9.
   The value received from the master will be stored in address 1 in its own
   address space namely holdingRegs[].
   
   In addition to this the slaves own adc ch0 value will be stored in 
   address 0 in its own address space holdingRegs[] for the master to
   be read. The master will use this value to alter the brightness of its
   own led connected to pin 9.
   
   The modbus_update() method updates the holdingRegs register array and checks
   communication.

   Note:  
   The Arduino serial ring buffer is 64 bytes or 32 registers.
   Most of the time you will connect the arduino to a master via serial
   using a MAX485 or similar.
 
   In a function 3 request the master will attempt to read from your
   slave and since 5 bytes is already used for ID, FUNCTION, NO OF BYTES
   and two BYTES CRC the master can only request 58 bytes or 29 registers.
 
   In a function 16 request the master will attempt to write to your 
   slave and since a 9 bytes is already used for ID, FUNCTION, ADDRESS, 
   NO OF REGISTERS, NO OF BYTES and two BYTES CRC the master can only write
   54 bytes or 27 registers.
 
   Using a USB to Serial converter the maximum bytes you can send is 
   limited to its internal buffer which differs between manufactures. 
*/

#define  LED 9  

// Using the enum instruction allows for an easy method for adding and 
// removing registers. Doing it this way saves you #defining the size 
// of your slaves register array each time you want to add more registers
// and at a glimpse informs you of your slaves register layout.

//////////////// registers of your slave ///////////////////
enum 
{     
  // just add or remove registers and your good to go...
  // The first register starts at address 0
  ADC_VAL,     
  PWM_VAL,        
  HOLDING_REGS_SIZE // leave this one
  // total number of registers for function 3 and 16 share the same register array
  // i.e. the same address space
};

unsigned int holdingRegs[HOLDING_REGS_SIZE]; // function 3 and 16 register array
////////////////////////////////////////////////////////////

void setup()
{
  /* parameters(HardwareSerial* SerialPort,
                long baudrate, 
		unsigned char byteFormat,
                unsigned char ID, 
                unsigned char transmit enable pin, 
                unsigned int holding registers size,
                unsigned int* holding register array)
  */
  
  /* Valid modbus byte formats are:
     SERIAL_8N2: 1 start bit, 8 data bits, 2 stop bits
     SERIAL_8E1: 1 start bit, 8 data bits, 1 Even parity bit, 1 stop bit
     SERIAL_8O1: 1 start bit, 8 data bits, 1 Odd parity bit, 1 stop bit
     
     You can obviously use SERIAL_8N1 but this does not adhere to the
     Modbus specifications. That said, I have tested the SERIAL_8N1 option 
     on various commercial masters and slaves that were suppose to adhere
     to this specification and was always able to communicate... Go figure.
     
     These byte formats are already defined in the Arduino global name space. 
  */
	
  modbus_configure(&Serial, 9600, SERIAL_8N2, 1, 2, HOLDING_REGS_SIZE, holdingRegs);

  // modbus_update_comms(baud, byteFormat, id) is not needed but allows for easy update of the
  // port variables and slave id dynamically in any function.
  modbus_update_comms(9600, SERIAL_8N2, 1);
  
  pinMode(LED, OUTPUT);
}

void loop()
{
  // modbus_update() is the only method used in loop(). It returns the total error
  // count since the slave started. You don't have to use it but it's useful
  // for fault finding by the modbus master.
  
  modbus_update();
  
  holdingRegs[ADC_VAL] = analogRead(A0); // update data to be read by the master to adjust the PWM
  
  analogWrite(LED, holdingRegs[PWM_VAL]>>2); // constrain adc value from the arduino master to 255
  
  /* Note:
     The use of the enum instruction is not needed. You could set a maximum allowable
     size for holdinRegs[] by defining HOLDING_REGS_SIZE using a constant and then access 
     holdingRegs[] by "Index" addressing. 
     I.e.
     holdingRegs[0] = analogRead(A0);
     analogWrite(LED, holdingRegs[1]/4);
  */
  
}
stapmoff
Сообщения: 18
Зарегистрирован: 16 май 2016, 18:04

Re: Arduino UNO + AutoGRAPH по RS 485 Modbus или LLS

Сообщение stapmoff »

Ну помогите пожалуйста, я уже мучаюсь долго и не знаю к кому обратиться
Аватара пользователя
Mr.Kubikus
Сотрудник ПАКПАК
Сообщения: 1018
Зарегистрирован: 22 окт 2010, 23:57

Re: Arduino UNO + AutoGRAPH по RS 485 Modbus или LLS

Сообщение Mr.Kubikus »

Буду рад помочь, но сейчас загружен на 100%. Как только появится свободное время сразу напишу.
С уважением, Григорий
GitHub FB ВК
stapmoff
Сообщения: 18
Зарегистрирован: 16 май 2016, 18:04

Re: Arduino UNO + AutoGRAPH по RS 485 Modbus или LLS

Сообщение stapmoff »

Хорошо
stapmoff
Сообщения: 18
Зарегистрирован: 16 май 2016, 18:04

Re: Arduino UNO + AutoGRAPH по RS 485 Modbus или LLS

Сообщение stapmoff »

И еще, в конфигураторе к прибору АвтоГРАФ есть некая таблица с произвольными значениями Modbus, кроме первого столбца (адрес slave устройства) и Уровень адаптива, более мне ни чего не ясно, от куда брать значение регистр и кол-во байт????? Я уже запутался((
Изображение
stapmoff
Сообщения: 18
Зарегистрирован: 16 май 2016, 18:04

Re: Arduino UNO + AutoGRAPH по RS 485 Modbus или LLS

Сообщение stapmoff »

Все заработало, всем спасибо!
Ответить