g0b1vetx-board/middleware/modbus/modbus-m.c
2023-05-19 18:02:00 +08:00

46 lines
1.0 KiB
C

/* modbus 主机实现*/
#include<stdint.h>
#include "crc.h"
// 读取保持寄存器的值
// addr 寄存器地址
// id 丛机地址
// length 读取丛机数据长度
int modbus_m_read_regist(uint8_t id,uint16_t addr,uint16_t length,uint8_t * data)
{
uint16_t index = 0,crc;
data[index++] = id;
data[index++] = 0x03;
data[index++] = (addr >> 8) & 0x00FF;
data[index++] = addr & 0x00FF;
data[index++] = (length >> 8) & 0x00FF;
data[index++] = length & 0x00FF;
crc = MX_CRC_CALC(data,index);
data[index++] = crc & 0x00FF;
data[index++] = (crc >> 8) & 0x00FF;
return index;
}
// 写入寄存器
// addr 寄存器地址
// id 丛机地址
// length 读取丛机数据长度
int modbus_m_write_regist(uint8_t id,uint16_t addr,uint16_t key,uint8_t * data)
{
uint16_t index = 0,crc;
data[index++] = id;
data[index++] = 0x06;
data[index++] = (addr >> 8) & 0x00FF;
data[index++] = addr & 0x00FF;
data[index++] = (key >> 8) & 0x00FF;
data[index++] = key & 0x00FF;
crc = MX_CRC_CALC(data,index);
data[index++] = crc & 0x00FF;
data[index++] = (crc >> 8) & 0x00FF;
return index;
}