modbus-arduino  1.0.0
Modbus library for Arduino
Modbus.h
1 /*
2  Modbus.h - Header for Modbus Base Library
3  Copyright (C) 2014 AndrĂ© Sarmento Barbosa
4 */
5 #include "Arduino.h"
6 
7 #ifndef MODBUS_H
8 #define MODBUS_H
9 
10 #define MAX_REGS 32
11 #define MAX_FRAME 128
12 //#define USE_HOLDING_REGISTERS_ONLY
13 
14 // Function Codes
15 enum {
16  MB_FC_READ_COILS = 0x01,
17  MB_FC_READ_INPUT_STAT = 0x02,
18  MB_FC_READ_REGS = 0x03,
19  MB_FC_READ_INPUT_REGS = 0x04,
20  MB_FC_WRITE_COIL = 0x05,
21  MB_FC_WRITE_REG = 0x06,
22  MB_FC_WRITE_COILS = 0x0F,
23  MB_FC_WRITE_REGS = 0x10,
24 };
25 
26 // Exception Codes
27 enum {
28  MB_EX_ILLEGAL_FUNCTION = 0x01,
29  MB_EX_ILLEGAL_ADDRESS = 0x02,
30  MB_EX_ILLEGAL_VALUE = 0x03,
31  MB_EX_SLAVE_FAILURE = 0x04,
32 };
33 
34 // Reply Types
35 enum {
36  MB_REPLY_OFF = 0x01,
37  MB_REPLY_ECHO = 0x02,
38  MB_REPLY_NORMAL = 0x03,
39 };
40 
41 #ifndef __DOXYGEN__
42 typedef struct TRegister {
43  word address;
44  word value;
45  struct TRegister* next;
46 } TRegister;
47 #endif
48 
53 class Modbus {
54 #ifndef __DOXYGEN__
55  private:
56  TRegister *_regs_head;
57  TRegister *_regs_last;
58 
59  void readRegisters(word startreg, word numregs);
60  void writeSingleRegister(word reg, word value);
61  void writeMultipleRegisters(byte* frame,word startreg, word numoutputs, byte bytecount);
62  void exceptionResponse(byte fcode, byte excode);
63  #ifndef USE_HOLDING_REGISTERS_ONLY
64  void readCoils(word startreg, word numregs);
65  void readInputStatus(word startreg, word numregs);
66  void readInputRegisters(word startreg, word numregs);
67  void writeSingleCoil(word reg, word status);
68  void writeMultipleCoils(byte* frame,word startreg, word numoutputs, byte bytecount);
69  #endif
70 
71  TRegister* searchRegister(word addr);
72 
73  void addReg(word address, word value = 0);
74  bool Reg(word address, word value);
75  word Reg(word address);
76 
77  protected:
78  byte *_frame;
79  byte _len;
80  byte _reply;
81  void receivePDU(byte* frame);
82 #endif
83 
84  public:
88  Modbus();
89 
95  void addHreg(word offset, word value = 0);
103  bool Hreg(word offset, word value);
109  word Hreg(word offset);
110 
111  #ifndef USE_HOLDING_REGISTERS_ONLY
112 
117  void addCoil(word offset, bool value = false);
123  void addIsts(word offset, bool value = false);
129  void addIreg(word offset, word value = 0);
137  bool Coil(word offset, bool value);
145  bool Ists(word offset, bool value);
153  bool Ireg(word offset, word value);
159  bool Coil(word offset);
165  bool Ists(word offset);
171  word Ireg(word offset);
172  #endif
173 };
174 
175 #endif //MODBUS_H
Modbus base class.
Definition: Modbus.h:53