modbus在工业仪表领域应用十分广泛,利用串口实现十分方便。移植modbus主要是按照规则实现串口数据收发及定时管理,本测试使用软件定时,方便实现多通道MODBUS。
文件列表如下:
modbus测试应用程序:
void modbus_task(const void *argv)
{
mb_cmd_buff_type mcmd;
mb_obj_init(&mb.obj01);
//slave config
mb01_Init(MB_RTU_SLAVE, mb_baud_tab[MB_BAUD_115200], MB_PAR_NONE);
mb.obj01.slave_id = 1;
mb.obj01.os_event_send = mb_os_send;
mb.obj01.os_event_base = 1 << 4;
mb.obj01.rtu_length_cut = 1;
mb_obj_init(&mb.obj02);
//slave config
mb02_Init(MB_RTU_SLAVE, mb_baud_tab[MB_BAUD_115200], MB_PAR_NONE);
mb.obj02.slave_id = 1;
mb.obj02.os_event_send = mb_os_send;
mb.obj02.os_event_base = 1 << 4;
mb.obj02.rtu_length_cut = 1;
mb_obj_init(&mb.obj06);
//master config
mb06_Init(MB_RTU_MASTER, mb_baud_tab[MB_BAUD_115200], MB_PAR_NONE);
mb.obj06.slave_id = 1;
mb.obj06.rtu_master_delay_set = 3;
mb.obj06.rcv_end_handle_comp = rcv_end_handle_comp;
mb.obj06.os_event_send = mb_os_send;
mb.obj06.os_event_base = 2 << 4;
mb.obj06.rtu_length_cut = 1;
//cmd config
mcmd.device_id = 0;
mcmd.cmd = FUN_CODE_READ_COILS;
mcmd.dat = mb_tst.pv_w;
mcmd.dat_addr = 0;
mcmd.amount = 48;
mcmd.call_back = 0;
mb.obj06.api->stc_cmd_req(0, &mcmd);
mcmd.cmd = FUN_CODE_READ_DISCRETE;
mb.obj06.api->stc_cmd_req(1, &mcmd);
mcmd.cmd = FUN_CODE_W_R_MULTIPLE_REG;
mb.obj06.api->stc_cmd_req(2, &mcmd);
mcmd.cmd = FUN_CODE_W_R_MULTIPLE_REG;
mb.obj06.api->stc_cmd_req(3, &mcmd);
mcmd.cmd = FUN_CODE_WRITE_MULTIPLE_REG;
mb.obj06.api->stc_cmd_req(4, &mcmd);
mcmd.cmd = FUN_CODE_WRITE_MULTIPLE_COIL;
mb_tst.pv_w[0] = 0;
mb.obj06.api->stc_cmd_req(5, &mcmd);
//task handle
for (;;)
{
rt_err_t os_err;
rt_uint32_t event;
// wait modbus event
os_err = rt_event_recv(os_obj.eid_modbus, 0xFFFF, RT_EVENT_FLAG_OR, 1000, &event);
(void)event;
(void)os_err;
mb_poll(&mb.obj01);
mb_poll(&mb.obj02);
mb_poll(&mb.obj06);
mb_tst.obj_size = sizeof(mb.obj06);
}
}
熟悉STM32的小伙伴使用NATION MCU比较容易上手,虽然NATION的库风格和STM的HAL库差别巨大,但寄存器结构基本一致,不会有太大障碍。
对于串口来说就是收发中断,收发状态,收发数据三项,具体可参见附件port文件,此处不再赘述。
板载UART1配置为从机,可以直接连接电脑测试:
附上测试工程:
software.rar
(3.14 MB)
|