1.5xiaoban/User/STM32MB/user_app/sample_mb_master.c

115 lines
2.9 KiB
C
Raw Permalink Normal View History

/*
* Copyright (c) 2006-2018, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2019-06-21 flybreak first version
*/
#include <rtthread.h>
#include "mb.h"
#include "mb_m.h"
#ifdef PKG_MODBUS_MASTER_SAMPLE
#define SLAVE_ADDR MB_SAMPLE_TEST_SLAVE_ADDR //<2F><EFBFBD><E8B1B8>ַ 1
#define PORT_NUM MB_MASTER_USING_PORT_NUM //<2F><><EFBFBD><EFBFBD> 2
#define PORT_BAUDRATE MB_MASTER_USING_PORT_BAUDRATE //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 115200
#else
#define SLAVE_ADDR 0x01
#define PORT_NUM 3
#define PORT_BAUDRATE 115200
#endif
#define PORT_PARITY MB_PAR_EVEN
#define MB_POLL_THREAD_PRIORITY 10
#define MB_SEND_THREAD_PRIORITY RT_THREAD_PRIORITY_MAX - 1
#define MB_SEND_REG_START 2
#define MB_SEND_REG_NUM 2
#define MB_POLL_CYCLE_MS 500
static void send_thread_entry(void *parameter) //<2F><><EFBFBD>ݴ<EFBFBD><DDB4><EFBFBD><EFBFBD>߳<EFBFBD>
{
eMBMasterReqErrCode error_code = MB_MRE_NO_ERR;
rt_uint16_t error_count = 0;
USHORT data[2] = {0};
while (1)
{
/* Test Modbus Master */
data[0] = (USHORT)(rt_tick_get() / 10);
data[1] = (USHORT)(rt_tick_get() % 10);
error_code = eMBMasterReqWriteMultipleHoldingRegister(SLAVE_ADDR, /* salve address */
MB_SEND_REG_START, /* register start address */
MB_SEND_REG_NUM, /* register total number */
data, /* data to be written */
RT_WAITING_FOREVER); /* timeout */
/* Record the number of errors */
if (error_code != MB_MRE_NO_ERR)
{
error_count++;
}
}
}
static void mb_master_poll(void *parameter) //<2F>ӻ<EFBFBD><D3BB>߳<EFBFBD>
{
eMBMasterInit(MB_RTU, PORT_NUM, PORT_BAUDRATE, PORT_PARITY);
eMBMasterEnable();
while (1)
{
eMBMasterPoll();
rt_thread_mdelay(MB_POLL_CYCLE_MS);
}
}
static int mb_master_samlpe(int argc, char **argv)
{
static rt_uint8_t is_init = 0;
rt_thread_t tid1 = RT_NULL, tid2 = RT_NULL;
if (is_init > 0)
{
rt_kprintf("sample is running\n");
return -RT_ERROR;
}
tid1 = rt_thread_create("md_m_poll", mb_master_poll, RT_NULL, 512, MB_POLL_THREAD_PRIORITY, 10);
if (tid1 != RT_NULL)
{
rt_thread_startup(tid1);
}
else
{
goto __exit;
}
tid2 = rt_thread_create("md_m_send", send_thread_entry, RT_NULL, 512, MB_SEND_THREAD_PRIORITY, 10);
if (tid2 != RT_NULL)
{
rt_thread_startup(tid2);
}
else
{
goto __exit;
}
is_init = 1;
return RT_EOK;
__exit:
if (tid1)
rt_thread_delete(tid1);
if (tid2)
rt_thread_delete(tid2);
return -RT_ERROR;
}
MSH_CMD_EXPORT(mb_master_samlpe, run a modbus master sample);