summaryrefslogtreecommitdiff
path: root/src/modbus.h
blob: 32ca5961fcbe5e8b974729ad5a678b2c73723522 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#ifndef _MODBUS_H
#define _MODBUS_H

#include "stm32f1xx_hal.h"
#include "string.h"

#define read_holding_regs  0x03
#define read_input_regs    0x04
#define write_single_reg   0x06

#define lowByte(w) ((uint8_t) ((w) & 0xff))
#define highByte(w) ((uint8_t) ((w) >> 8))
#define word(h, l) ((h << 8) | l)

#define MODBUS_TIMEOUT 50
#define MAX_BUFSIZE    64

typedef struct {
    uint8_t              slave_id;
    uint16_t             response_buffer[MAX_BUFSIZE];
    uint8_t              rbuf_len;
    UART_HandleTypeDef   modbus_uart;    
} modbus_slave_device;

typedef enum {
    MB_OK             =  0x0,
    MB_SLAVE_ID_ERR   =  0x1,
    MB_FUNC_ERR       =  0x2,
    MB_CRC_ERR        =  0x3,
    MB_UART_ERR       =  0x4,
    MB_BUSY_ERR       =  0x5,
    MB_TIMEOUT_ERR    =  0x6
} MB_StatusTypeDef;


uint16_t crc16_update(uint16_t crc, uint8_t a);
MB_StatusTypeDef modbus_transaction (uint8_t func, modbus_slave_device *device,
				     uint16_t rw_addr, int read_num,
				     uint16_t write_value);
MB_StatusTypeDef ReadHoldingRegisters(modbus_slave_device *device, uint16_t reg_addr,
				      int read_num);
MB_StatusTypeDef ReadInputRegisters(modbus_slave_device *device, uint16_t reg_addr,
				    int read_num);
MB_StatusTypeDef WriteSingleRegister(modbus_slave_device *device, uint16_t reg_addr,
				     uint16_t write_val);
void ClearResponseBuffer(modbus_slave_device *device);

#endif