首先,本人需要聲明一下,本文所移植FreeModbus的過程僅能用作參考,雖然FreeModbus的庫已經用在工程很多年,但是由於移植的代碼,本人經驗等問題,所以本人不建議您直接用在工程中,但是可以作為工程測試、調試和個人DIY所用。
一、準備移植程序和工具
我在此次移植過程中,主要用到以下幾個程序與工具:
在移植過程中,主要用到芯片的外設有USART1(PB6、PB7)和TIMER11,請您根據實際情況進行設置。其中TIMER的設置,您需要設置時鐘的信號基準為50uS,時鐘產生中斷的時間為1750uS(串口波特率大於19200時,在mbrtu.c中有具體的描述),也就是35個基準時間。
二、拷貝需要的文件到工程目錄下
1、解壓縮通過下載得到的freemodbus-v1.5.zip。
2、按照下列的文件列表拷貝相應的文件到對應的目錄(沒有路徑,需要自己建),並在 keil中設置好相應的頭文件引用路徑和源碼文件的引用。
拷貝文件到工程文件夾示例:
工程文件夹
│ .mxproject
│ <工程名>.ioc
│
├─Drivers //底层驱动文件夹
├─Inc //头文件存放位置
│ │ gpio.h
│ │ stm32f4xx_hal_conf.h
│ │ stm32f4xx_it.h
│ │ tim.h
│ │ usart.h
│ │
│ └─Modbus //Modbus需要用到的头文件
│ ├─modbus_driver //Modbus函数等头文件
│ │ ├─include //Modbus通用函数头文件
│ │ │ mb.h
│ │ │ mbconfig.h
│ │ │ mbframe.h
│ │ │ mbfunc.h
│ │ │ mbport.h
│ │ │ mbproto.h
│ │ │ mbutils.h
│ │ │
│ │ └─rtu //Modbus RTU函数头文件
│ │ mbcrc.h
│ │ mbrtu.h
│ │
│ └─modbus_user //Modbus用户配置头文件
│ port.h
│
├─MDK-ARM
│ BPEER_USART_TEST.uvprojx
│
└─Src
│ gpio.c
│ main.c
│ stm32f4xx_hal_msp.c
│ stm32f4xx_it.c
│ tim.c
│ usart.c
│
└─Modbus //Modbus需要用到的源码文件
├─modbus_driver
│ │ mb.c //Modbus基本函数和设置源码文件
│ │
│ ├─functions //Modbus通用函数源码文件
│ │ mbfunccoils.c
│ │ mbfuncdiag.c
│ │ mbfuncdisc.c
│ │ mbfuncholding.c
│ │ mbfuncinput.c
│ │ mbfuncother.c
│ │ mbutils.c
│ │
│ └─rtu //Modbus RTU函数源码文件
│ mbcrc.c
│ mbrtu.c
│
└─modbus_user //Modbus用户配置源码文件
portevent.c
portserial.c
porttimer.c
三、搞定Timer
Timer的移植過程中,應該算是比較簡單的了,需要簡單的設置一下初始化的返回值,完整寫出開啟Timer的函數,停止Timer的函數,並對Timer回掉函數進行設置下,就OK了。
porttimer.c移植後的代碼如下:
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
49 | /* ----------------------- Platform includes ----------------------------*/
#include "port.h"
#include "stm32f4xx_hal.h"
#include "tim.h"
/* ----------------------- Modbus includes ------------------------------*/
#include "mb.h"
#include "mbport.h"
/* ----------------------- static functions -----------------------------*/
/* ----------------------- Private define -------------------------------*/
#ifndef Modbus_TimHandle
#define Modbus_TimHandle htim11
#endif
/* ----------------------- Start implementation -------------------------*/
BOOL
xMBPortTimersInit( USHORT usTim1Timerout50us )
{
/*系统初始化已经完成定时器的初始化,故在此不在进行初始化*/
return TRUE;
}
inline void
vMBPortTimersEnable( )
{
/* Enable the timer with the timeout passed to xMBPortTimersInit( ) */
/*Disable Timer and Reset Counter*/
HAL_TIM_Base_Stop_IT(&Modbus_TimHandle);
__HAL_TIM_SET_COUNTER(&Modbus_TimHandle, 0x0000);
/*Enable Timer*/
HAL_TIM_Base_Start_IT(&Modbus_TimHandle);
}
inline void
vMBPortTimersDisable( )
{
/* Disable any pending timers. */
HAL_TIM_Base_Stop_IT(&Modbus_TimHandle);
}
/* Create an ISR which is called whenever the timer has expired. This function
* must then call pxMBPortCBTimerExpired( ) to notify the protocol stack that
* the timer has expired.
*/
void prvvTIMERExpiredISR( void )
{
( void )pxMBPortCBTimerExpired();
}
|
stm32f4xx_it.c移植後的部分代碼如下所示:
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 | /* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
#include "stm32f4xx.h"
#include "stm32f4xx_it.h"
/* USER CODE BEGIN 0 */
#include "mb.h"
#include "mbport.h"
extern void prvvUARTTxReadyISR(void);
extern void prvvUARTRxISR(void);
extern void prvvTIMERExpiredISR( void );
/* USER CODE END 0 */
…… …… ……
/* USER CODE BEGIN 1 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
/* NOTE : This function Should not be modified, when the callback is needed,
the __HAL_TIM_PeriodElapsedCallback could be implemented in the user file
*/
prvvTIMERExpiredISR( );
}
/* USER CODE END 1 */
|
四、搞定串口
串口比較難搞一些了,需要設置中斷處理函數、串口初始化函數、串口輸入輸出函數、串口中斷服務函數。
portserial.c移植後的代碼如下所示:
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111 | #include "port.h"
#include "usart.h"
#include "stm32f4xx_hal.h"
#include "stm32f4xx_it.h"
/* ----------------------- Modbus includes ------------------------------*/
#include "mb.h"
#include "mbport.h"
/* ----------------------- static functions -----------------------------*/
void prvvUARTTxReadyISR( void );
void prvvUARTRxISR( void );
/* ----------------------- Private define -------------------------------*/
#ifndef Modbus_UartHandle
#define Modbus_UartHandle huart1
#endif
/* ----------------------- Start implementation -------------------------*/
void
vMBPortSerialEnable( BOOL xRxEnable, BOOL xTxEnable )
{
/* If xRXEnable enable serial receive interrupts. If xTxENable enable
* transmitter empty interrupts.
*/
if( xRxEnable )
{
/* Enable the UART Data Register not empty Interrupt */
__HAL_UART_ENABLE_IT(&Modbus_UartHandle, UART_IT_RXNE);
}
else
{
/* Disable the UART Data Register not empty Interrupt */
__HAL_UART_DISABLE_IT(&Modbus_UartHandle, UART_IT_RXNE);
}
if( xTxEnable )
{
/* Enable the UART Transmit data register empty Interrupt */
__HAL_UART_ENABLE_IT(&Modbus_UartHandle, UART_IT_TXE);
prvvUARTTxReadyISR();
}
else
{
/* Disable the UART Transmit data register empty Interrupt */
__HAL_UART_DISABLE_IT(&Modbus_UartHandle, UART_IT_TXE);
/* Enable the UART Transmit Complete Interrupt */
__HAL_UART_ENABLE_IT(&Modbus_UartHandle, UART_IT_TC);
}
}
BOOL
xMBPortSerialInit( UCHAR ucPORT, ULONG ulBaudRate, UCHAR ucDataBits, eMBParity eParity )
{
/*由于已经在系统初始化中已经完成串口初始化,故在此不需要再一次进行初始化*/
return TRUE;
}
BOOL
xMBPortSerialPutByte( CHAR ucByte )
{
/* Put a byte in the UARTs transmit buffer. This function is called
* by the protocol stack if pxMBFrameCBTransmitterEmpty( ) has been
* called. */
if(HAL_UART_Transmit (&Modbus_UartHandle ,(uint8_t *)&ucByte,1,0x01) != HAL_OK )
{
return FALSE ;
}
else
{
return TRUE;
}
}
BOOL
xMBPortSerialGetByte( CHAR * pucByte )
{
/* Return the byte in the UARTs receive buffer. This function is called
* by the protocol stack after pxMBFrameCBByteReceived( ) has been called.
*/
if(HAL_UART_Receive (&Modbus_UartHandle ,(uint8_t *)pucByte,1,0x01) != HAL_OK )
{
return FALSE ;
}
else
{
return TRUE;
}
}
/* Create an interrupt handler for the transmit buffer empty interrupt
* (or an equivalent) for your target processor. This function should then
* call pxMBFrameCBTransmitterEmpty( ) which tells the protocol stack that
* a new character can be sent. The protocol stack will then call
* xMBPortSerialPutByte( ) to send the character.
*/
void prvvUARTTxReadyISR( void )
{
pxMBFrameCBTransmitterEmpty( );
}
/* Create an interrupt handler for the receive interrupt for your target
* processor. This function should then call pxMBFrameCBByteReceived( ). The
* protocol stack will then call xMBPortSerialGetByte( ) to retrieve the
* character.
*/
void prvvUARTRxISR( void )
{
pxMBFrameCBByteReceived( );
}
|
stm32f4xx_it.c移植後的部分代碼如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 | /**
* @brief This function handles USART1 global interrupt.
*/
void USART1_IRQHandler(void)
{
/* USER CODE BEGIN USART1_IRQn 0 */
if(__HAL_UART_GET_IT_SOURCE(&huart1, UART_IT_RXNE)!= RESET)
{
prvvUARTRxISR();//接收中断处理函数
}
if(__HAL_UART_GET_IT_SOURCE(&huart1, UART_IT_TXE)!= RESET)
{
prvvUARTTxReadyISR();//发送完成终端处理函数
}
HAL_NVIC_ClearPendingIRQ(USART1_IRQn);
/* USER CODE END USART1_IRQn 0 */
HAL_UART_IRQHandler(&huart1);
/* USER CODE BEGIN USART1_IRQn 1 */
/* USER CODE END USART1_IRQn 1 */
}
|
五、搞定其他配置
1、搞定開關中斷操作
port.h移植後的部分代碼如下所示:
| /*禁用全部中断*/
#define ENTER_CRITICAL_SECTION( ) __disable_irq()
/*开启全部中断*/
#define EXIT_CRITICAL_SECTION( ) __enable_irq()
|
2、搞定系統配置
mb.c移植後的部分代碼如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | /*设置启用Modbus RTU 模式,减少编译后的代码量*/
#if MB_RTU_ENABLED == 1
#include "mbrtu.h"
#endif
/*减少编译后代码错误以及修改,将判定值由1改为0,并修改MB_ASCII_ENABLED的定义为0,
想要了解原因,请自行修改编译查看*/
#if MB_ASCII_ENABLED == 1
#include "mbascii.h"
#endif
/*减少编译后代码大小,将判定值由0改为1,并修改MB_TCP_ENABLED的定义为0,想要了解
原因,请自行修改编译查看*/
#if MB_TCP_ENABLED == 1
#include "mbtcp.h"
#endif
|
3、搞定寄存器地址差一的問題
需要在源碼中註釋掉所有的usRegAddress++;。
4、搞定keil編譯過程中出現的各種警告
mb.h移植後的部分代碼如下所示:
| extern void
xMBUtilSetBits( UCHAR * ucByteBuf, USHORT usBitOffset, UCHAR ucNBits, \
UCHAR ucValue );
extern UCHAR
xMBUtilGetBits( UCHAR * ucByteBuf, USHORT usBitOffset, UCHAR ucNBits );
|
mbrtu.c移植後的部分代碼如下所示:
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 | eMBErrorCode
eMBRTUReceive( UCHAR * pucRcvAddress, UCHAR ** pucFrame, USHORT * pusLength )
{
/*处女座心理,必须要求无错误、无警告、可过PC-Lint,目前也没有发现这个定义的用处*/
// BOOL xFrameReceived = FALSE;
eMBErrorCode eStatus = MB_ENOERR;
ENTER_CRITICAL_SECTION( );
assert( usRcvBufferPos < MB_SER_PDU_SIZE_MAX );
/* Length and CRC check */
if( ( usRcvBufferPos >= MB_SER_PDU_SIZE_MIN )
&& ( usMBCRC16( ( UCHAR * ) ucRTUBuf, usRcvBufferPos ) == 0 ) )
{
/* Save the address field. All frames are passed to the upper layed
* and the decision if a frame is used is done there.
*/
*pucRcvAddress = ucRTUBuf[MB_SER_PDU_ADDR_OFF];
/* Total length of Modbus-PDU is Modbus-Serial-Line-PDU minus
* size of address field and CRC checksum.
*/
*pusLength = ( USHORT )( usRcvBufferPos - MB_SER_PDU_PDU_OFF - MB_SER_PDU_SIZE_CRC );
/* Return the start of the Modbus PDU to the caller. */
*pucFrame = ( UCHAR * ) & ucRTUBuf[MB_SER_PDU_PDU_OFF];
// xFrameReceived = TRUE;
}
else
{
eStatus = MB_EIO;
}
EXIT_CRITICAL_SECTION( );
return eStatus;
}
|
5、未知原因的添加代碼
這部分代碼沒有明白,為什麼需要添加,有些沒有研究透,希望有大神可以指點。
mbrtu.c移植後的部分代碼如下所示:
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 | eMBErrorCode
eMBRTUSend( UCHAR ucSlaveAddress, const UCHAR * pucFrame, USHORT usLength )
{
eMBErrorCode eStatus = MB_ENOERR;
USHORT usCRC16;
ENTER_CRITICAL_SECTION( );
/* Check if the receiver is still in idle state. If not we where to
* slow with processing the received frame and the master sent another
* frame on the network. We have to abort sending the frame.
*/
if( eRcvState == STATE_RX_IDLE )
{
/* First byte before the Modbus-PDU is the slave address. */
pucSndBufferCur = ( UCHAR * ) pucFrame - 1;
usSndBufferCount = 1;
/* Now copy the Modbus-PDU into the Modbus-Serial-Line-PDU. */
pucSndBufferCur[MB_SER_PDU_ADDR_OFF] = ucSlaveAddress;
usSndBufferCount += usLength;
/* Calculate CRC16 checksum for Modbus-Serial-Line-PDU. */
usCRC16 = usMBCRC16( ( UCHAR * ) pucSndBufferCur, usSndBufferCount );
ucRTUBuf[usSndBufferCount++] = ( UCHAR )( usCRC16 & 0xFF );
ucRTUBuf[usSndBufferCount++] = ( UCHAR )( usCRC16 >> 8 );
/* Activate the transmitter. */
eSndState = STATE_TX_XMIT;
/*插入代码 启动第一次发送,这样才可以进入发送完成中断*/
xMBPortSerialPutByte( ( CHAR )*pucSndBufferCur );
pucSndBufferCur++;
usSndBufferCount--;
vMBPortSerialEnable( FALSE, TRUE );
}
else
{
eStatus = MB_EIO;
}
EXIT_CRITICAL_SECTION( );
return eStatus;
}
|
六、搞定主函數
主函數需要設置數組和處理函數,無其他設置,我放上我移植的代碼以供參考。
main.c移植後的代碼如下所示:
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392 | /* Includes -------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
#include "adc.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"
/* USER CODE BEGIN Includes */
#include "mb.h"
#include "mbport.h"
/* USER CODE END Includes */
/* Private variables ----------------------------------------------------*/
/* USER CODE BEGIN PV */
/*线圈状态寄存器*/
#define REG_COILS_START 0x0000
#define REG_COILS_SIZE 8
/*线圈状态输入寄存器*/
#define REG_DISCRETE_START 0x0000
#define REG_DISCRETE_SIZE 8
/*保持寄存器*/
#define REG_HOLDING_START 0x0000
#define REG_HOLDING_NREGS 10
/*输入寄存器*/
#define REG_INPUT_START 0x0000
#define REG_INPUT_NREGS 1
/* USER CODE END PV */
/* Private function prototypes ------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* USER CODE BEGIN 0 */
/*定义线圈状态寄存器的地址起始值和存储数组*/
uint8_t ucRegCoilsStart = REG_HOLDING_START;
uint8_t ucRegCoilsBuf[REG_COILS_SIZE / 8];
/*定义线圈输入状态寄存器的地址起始值和存储数组*/
uint8_t ucRegDiscreteStart = REG_HOLDING_START;
uint8_t ucRegDiscreteBuf[REG_DISCRETE_SIZE / 8];
/*定义保持寄存器的地址起始值和存储数组*/
uint16_t usRegHoldingStart = REG_HOLDING_START;
uint16_t usRegHoldingBuf[REG_HOLDING_NREGS] = {1,2,3,4,5,6,7,8,9,0};
/*定义输入寄存器的地址起始值和存储数组*/
uint16_t usRegInputStart = REG_INPUT_START;
uint16_t usRegInputBuf[REG_INPUT_NREGS];
/* USER CODE END 0 */
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration-------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* Configure the system clock */
SystemClock_Config();
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_ADC1_Init();
MX_TIM1_Init();
MX_TIM4_Init();
MX_TIM11_Init();
MX_USART1_UART_Init();
/* USER CODE BEGIN 2 */
/*设置Modnbus以RTU模式运行,从机ID为0x01,串口为默认串口,串口波特率为115200,无奇偶校验*/
eMBInit(MB_RTU, 0x01, 1, 115200, MB_PAR_NONE);
/* Enable the Modbus Protocol Stack. */
eMBEnable();
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
( void )eMBPoll();
__HAL_TIM_SetCompare(&htim4,TIM_CHANNEL_1,usRegHoldingBuf[0]);
__HAL_TIM_SetCompare(&htim4,TIM_CHANNEL_2,usRegHoldingBuf[1]);
__HAL_TIM_SetCompare(&htim4,TIM_CHANNEL_3,usRegHoldingBuf[2]);
__HAL_TIM_SetCompare(&htim4,TIM_CHANNEL_4,usRegHoldingBuf[3]);
HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_1);
HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_2);
HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_3);
HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_4);
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/** System Clock Configuration
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_ClkInitTypeDef RCC_ClkInitStruct;
__PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2);
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = 16;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 200;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4;
RCC_OscInitStruct.PLL.PLLQ = 4;
HAL_RCC_OscConfig(&RCC_OscInitStruct);
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK|RCC_CLOCKTYPE_PCLK1;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3);
HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);
HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
}
/* USER CODE BEGIN 4 */
/**
* @brief 输入寄存器处理函数,输入寄存器可读,但不可写。
* @param pucRegBuffer 返回数据指针
* usAddress 寄存器起始地址
* usNRegs 寄存器长度
* @retval eStatus 寄存器状态
*/
eMBErrorCode
eMBRegInputCB( UCHAR * pucRegBuffer, USHORT usAddress, USHORT usNRegs )
{
eMBErrorCode eStatus = MB_ENOERR;
int16_t iRegIndex;
// 用作例子
usRegInputBuf[0] = 0x11;
// 例子结束
//查询是否在寄存器范围内
//为了避免警告,修改为有符号整数
if( ((int16_t) usAddress >= REG_INPUT_START ) \
&& ( usAddress + usNRegs <= REG_INPUT_START + REG_INPUT_NREGS ) )
{
//获得操作偏移量,本次操作起始地址-输入寄存器的初始地址
iRegIndex = ( int16_t )( usAddress - usRegInputStart );
//逐个赋值
while( usNRegs > 0 )
{
//赋值高字节
*pucRegBuffer++ = ( uint8_t )( usRegInputBuf[iRegIndex] >> 8 );
//赋值低字节
*pucRegBuffer++ = ( uint8_t )( usRegInputBuf[iRegIndex] & 0xFF );
//偏移量增加
iRegIndex++;
//被操作寄存器数量递减
usNRegs--;
}
}
else
{
//返回错误状态,寄存器数量不对
eStatus = MB_ENOREG;
}
return eStatus;
}
/**
* @brief 保持寄存器处理函数,保持寄存器可读,可读可写
* @param pucRegBuffer 读操作时--返回数据指针,写操作时--输入数据指针
* usAddress 寄存器起始地址
* usNRegs 寄存器长度
* eMode 操作方式,读或者写
* @retval eStatus 寄存器状态
*/
eMBErrorCode
eMBRegHoldingCB( UCHAR * pucRegBuffer, USHORT usAddress, USHORT usNRegs,
eMBRegisterMode eMode )
{
//错误状态
eMBErrorCode eStatus = MB_ENOERR;
//偏移量
int16_t iRegIndex;
//判断寄存器是不是在范围内
if( ( (int16_t)usAddress >= REG_HOLDING_START ) \
&& ( usAddress + usNRegs <= REG_HOLDING_START + REG_HOLDING_NREGS ) )
{
//计算偏移量
iRegIndex = ( int16_t )( usAddress - REG_HOLDING_START );
switch ( eMode )
{
//读处理函数
case MB_REG_READ:
while( usNRegs > 0 )
{
*pucRegBuffer++ = ( uint8_t )( usRegHoldingBuf[iRegIndex] >> 8 );
*pucRegBuffer++ = ( uint8_t )( usRegHoldingBuf[iRegIndex] & 0xFF );
iRegIndex++;
usNRegs--;
}
break;
//写处理函数
case MB_REG_WRITE:
while( usNRegs > 0 )
{
usRegHoldingBuf[iRegIndex] = *pucRegBuffer++ << 8;
usRegHoldingBuf[iRegIndex] |= *pucRegBuffer++;
iRegIndex++;
usNRegs--;
}
break;
}
}
else
{
//返回错误状态
eStatus = MB_ENOREG;
}
return eStatus;
}
/**
* @brief 线圈寄存器处理函数,线圈寄存器可读,可读可写
* @param pucRegBuffer 读操作---返回数据指针,写操作--返回数据指针
* usAddress 寄存器起始地址
* usNRegs 寄存器长度
* eMode 操作方式,读或者写
* @retval eStatus 寄存器状态
*/
eMBErrorCode
eMBRegCoilsCB( UCHAR * pucRegBuffer, USHORT usAddress, USHORT usNCoils,
eMBRegisterMode eMode )
{
//错误状态
eMBErrorCode eStatus = MB_ENOERR;
//寄存器个数
int16_t iNCoils = ( int16_t )usNCoils;
//寄存器偏移量
int16_t usBitOffset;
//检查寄存器是否在指定范围内
if( ( (int16_t)usAddress >= REG_COILS_START ) &&
( usAddress + usNCoils <= REG_COILS_START + REG_COILS_SIZE ) )
{
//计算寄存器偏移量
usBitOffset = ( int16_t )( usAddress - REG_COILS_START );
switch ( eMode )
{
//读操作
case MB_REG_READ:
while( iNCoils > 0 )
{
*pucRegBuffer++ = xMBUtilGetBits( ucRegCoilsBuf, usBitOffset,
( uint8_t )( iNCoils > 8 ? 8 : iNCoils ) );
iNCoils -= 8;
usBitOffset += 8;
}
break;
//写操作
case MB_REG_WRITE:
while( iNCoils > 0 )
{
xMBUtilSetBits( ucRegCoilsBuf, usBitOffset,
( uint8_t )( iNCoils > 8 ? 8 : iNCoils ),
*pucRegBuffer++ );
iNCoils -= 8;
}
break;
}
}
else
{
eStatus = MB_ENOREG;
}
return eStatus;
}
/**
* @brief 开关输入寄存器处理函数,开关输入寄存器,可读
* @param pucRegBuffer 读操作---返回数据指针,写操作--返回数据指针
* usAddress 寄存器起始地址
* usNRegs 寄存器长度
* eMode 操作方式,读或者写
* @retval eStatus 寄存器状态
*/
eMBErrorCode
eMBRegDiscreteCB( UCHAR * pucRegBuffer, USHORT usAddress, USHORT usNDiscrete )
{
//错误状态
eMBErrorCode eStatus = MB_ENOERR;
//操作寄存器个数
int16_t iNDiscrete = ( int16_t )usNDiscrete;
//偏移量
uint16_t usBitOffset;
//判断寄存器时候再制定范围内
if( ( (int16_t)usAddress >= REG_DISCRETE_START ) &&
( usAddress + usNDiscrete <= REG_DISCRETE_START + REG_DISCRETE_SIZE ) )
{
//获得偏移量
usBitOffset = ( uint16_t )( usAddress - REG_DISCRETE_START );
while( iNDiscrete > 0 )
{
*pucRegBuffer++ = xMBUtilGetBits( ucRegDiscreteBuf, usBitOffset,
( uint8_t)( iNDiscrete > 8 ? 8 : iNDiscrete ) );
iNDiscrete -= 8;
usBitOffset += 8;
}
}
else
{
eStatus = MB_ENOREG;
}
return eStatus;
}
/* USER CODE END 4 */
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t* file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif
/**
* @}
*/
/**
* @}
*/
/*************** (C) COPYRIGHT STMicroelectronics *****END OF FILE********/
|
七、結語
本次移植過程也是個人摸索得出的,如果有不盡完善的地方,歡迎您提出,我進行驗證更正。
Like this post? Share on:
Email