Simple, tiny minimal library to implement a ModBus slave in mbed.

tinymal_modbus.h

Committer:
fbcosentino
Date:
2019-02-22
Revision:
0:4f5da8a923c4

File content as of revision 0:4f5da8a923c4:

/** @file tinymal_modbus.h
 *  Library to implement a ModBus slave in mbed. 
 *  @note Currently supports 38400 baud rate only.
 * 
 *  @author Fernando Cosentino
 *  os.mbed.com/users/fbcosentino
 *
 *  Example:
 *  @code
 *  #include "mbed.h"
 *  #include "tinymal_modbus.h"
 *
 *  // pins are for LPC11U35
 *  Serial rs485(P0_19, P0_18);  // a serial port object
 *  DigitalOut driver_pin(P0_2); // direction driver pin
 *  DigitalOut coil1(P0_20);     // a coil - this is the application
 *
 *  int main() {
 *      rs485.baud(38400);
 *      tinymod_Init(&rs485, &driver_pin);
 *      tinymod_Address(10);
 *
 *      // tiny_regs is the array containing the modbus registers
 *      tiny_regs[0] = 0; // Sets an initial value to register 0
 *
 *      while(1) {
 *          // call this periodically to process the messages
 *          tinymod_Check();
 *
 *          // make the coil reflect the internal modbus register
 *          if (tiny_regs[0] > 0) {
 *              coil1 = 1;
 *          }
 *          else {
 *              coil1 = 0;
 *          }
 *      } 
 *  }
 *  @endcode
 */

#include "mbed.h"

#define TINYMOD_NUM_REGS    16

#define TINYMOD_MODE_SLAVE   0
#define TINYMOD_MODE_MASTER  1

#define MODBUS_FUNC_READ            3
#define MODBUS_FUNC_WRITE_SINGLE    6
#define MODBUS_FUNC_WRITE_MULT      16


extern uint8_t tinymod_address;
extern int tinymod_mode;


/**
 *  Array storing the register values - your application will work with this.
 */
extern uint16_t tiny_regs[TINYMOD_NUM_REGS];


/**
 *  Initialises the internal Modbus receiver based on the specified serial port
 *  direction driver objects. You must initialise those objects yourself before
 *  instancing the tinymal modbus object.
 *
 *  @param ser_obj Serial instance of the Serial class.
 *  @param driver_obj Digital output pin instance of the DigitalOut class
 */
void tinymod_Init(Serial * ser_obj, DigitalOut * driver_obj);

/**
 *  Sets the listening address for this device. Valid addresses are in the
 *  range of 0 - 247 decimal (0x00 - 0xF7).
 *
 *  @param addr Address this device should respond to (0 - 247)
 */
void tinymod_Address(uint8_t addr);

/**
 *  Internally processes any received messages - you must call this as often
 *  as possible (ideally once per main loop if your main loop is short).
 *  Messages are not automatically processed to keep interrupt handling to the
 *  bare minimum, so you have the freedom to decide when you are going to spend
 *  processor time processing the message via this function call.
 */
void tinymod_Check(void);