Selasa, 13 November 2018

membuat modbus serial/RTU RS485 yang sangat mudah dan simple



berikut langsung saja saya share koding modbus serial/RTU RS485, semoga bermanfaat.
 koding ini mohon tidak diperjual belikan.


/*
Author : Fuad Hasan (CEO SIMOR)
website : puaks.blogspot.com
*/


#include <ModbusRtu.h>
#define ID  1 //slave ID
#define TXEN  2 //pin tx enable RS485
#define PS 0 //port serial 0,1,2,3 (1-3 for mega 2560, uno 0 only)
Modbus slave(ID, PS, TXEN);
uint16_t au16data[9]; // jumlah address yang dibuat

/**
 saat uji protocol via modscan setting
 baudrate 9600
 parity none
 slave ID 1
 lengt 9
 address 1
 Holding register
 */
void setup() {
  io_setup(); // I/O settings
  slave.begin( 9600 ); // baudrate

}

void loop() {
  slave.poll( au16data, 9 );
   io_poll();
}

/**
 * pin maping:
 * 2 - digital input
 * 3 - digital input
 * 4 - digital input
 * 5 - digital input
 * 6 - digital output
 * 7 - digital output
 * 8 - digital output
 * 9 - digital output
 * 13 - digital output
 * 10 - analog output PWM 0-255
 * 11 - analog output PWM 0-255


 */
void io_setup() {
  // define i/o
  //DIGITAL INPUT
  pinMode(3, INPUT_PULLUP);
  pinMode(4, INPUT_PULLUP);
  pinMode(5, INPUT_PULLUP);
  pinMode(6, INPUT_PULLUP);
  //DIGITAL OUTPUT
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(13, OUTPUT);


  digitalWrite(7, LOW );
  digitalWrite(8, LOW );
  digitalWrite(9, LOW );
  digitalWrite(13, LOW );
 
  //ANALOG OUTPUT
  analogWrite(10, 0 );
  analogWrite(11, 0 );
}

/**
 *  Link between the Arduino pins and the Modbus array
 */
void io_poll() {
  // get digital inputs -> au16data[0] HOLDING REGISTER 40001 di modscan, display options BINARY
  bitWrite( au16data[0], 0, digitalRead( 3 ));
  bitWrite( au16data[0], 1, digitalRead( 4 ));
  bitWrite( au16data[0], 2, digitalRead( 5 ));
  bitWrite( au16data[0], 3, digitalRead( 6 ));

  // set digital outputs -> au16data[1] HOLDING REGISTER 40002 di modscan, display options BINARY
  digitalWrite( 7, bitRead( au16data[1], 0 ));
  digitalWrite( 8, bitRead( au16data[1], 1 ));
  digitalWrite( 9, bitRead( au16data[1], 2 ));
  digitalWrite( 13, bitRead( au16data[1], 3 ));
 
  // set analog outputs, HOLDING REGISTER 40003 dan 40004 di modscan, display options unsign desimal
  analogWrite( 10, au16data[2] );
  analogWrite( 11, au16data[3] );

  // read analog inputs, HOLDING REGISTER 40005 dan 40006 di modscan, display options unsign desimal
  au16data[4] = analogRead( 0 );
  au16data[5] = analogRead( 1 );

  // diagnose communication
  au16data[6] = slave.getInCnt();
  au16data[7] = slave.getOutCnt();
  au16data[8] = slave.getErrCnt();
}



library bisa download dibawah ini:
modbus

Tidak ada komentar:

Posting Komentar

Frekwensi LoRa yang legal di Indonesia

 menurut kepmen 2024-05 standar teknis perangkat LPWAN berikut frekwensi LoRa : link KEPMEN: download