modbus
uart波特率为9600,modbus帧间隔3.5个字符即3.5ms,开启一个4ms的定时器,在uart接收中断中刷新4ms定时器,定时器超时则表示连续4ms没有接收到数据,认为一帧结束,
mb_frame_end_flag
= 1;
- modbus.h
/* 寄存器映射表 */
struct reg_map_table {
u16 start_addr;
u16 count;
u16 *p_reg_struct;
};
typedef struct {
u16 cell_vol1;
u16 cell_vol2;
u16 cell_vol3;
u16 cell_vol4;
s16 current;
s16 temp1;
s16 temp2;
......
}bms_info_st;
typedef struct {
u16 over_vol;
s16 over_cur;
s16 over_temp;
......
}protect_para_st;
typedef struct {
u16 hw_ver[10];
u16 sw_ver[10];
u16 sys_sn[10];
......
}sys_para_st;
typedef struct {
u16 vol_gain;
s16 cur_offset;
s16 cur_gain;
u16 temp_offset;
......
}cali_para_st;
/* 4组寄存器 */
extern bms_info_st g_bms_info; //采集的数据,只读
extern protect_para_st g_protect_para; //设置的保护参数,可读可写入flash
extern sys_para_st g_sys_para;
extern cali_para_st g_cali_para;
extern u8 mb_buf[256];
extern u16 mb_cnt;
extern u8 mb_frame_end_flag;
extern void modbus_task(void);
- modbus.c
#include "modbus.h"
const u8 mb_salve_addr = 0x01; //modbus从机地址
u16* p_reg; //寄存器映射指针
u8 mb_buf[256] = {
0}; //uart接收缓冲
u16 mb_cnt = 0; //uart接收一帧的长度
u8 mb_frame_end_flag = 0; //帧结束标志
bms_info_st g_bms_info; //运行数据
protect_para_st g_protect_para; //保护参数
sys_para_st g_sys_para; //系统参数
cali_para_st g_cali_para; //校准参数
struct reg_map_table mb_reg_map_table[4] = {
{
0, sizeof(g_bms_info)/2, &g_bms_info},
{
256, sizeof(g_protect_para)/2, &g_protect_para},
{
512, sizeof(g_sys_para)/2, &g_sys_para},
{
768, sizeof(g_sys_para)/2, &g_cali_para},
};
/* modbus CRC16 */
u16 mb_crc16(u8 *buf, u16 len