summaryrefslogtreecommitdiff
path: root/examples/stm32/main.c
blob: 958e4d73f7c8c929152f457db895fe322f36e193 (plain)
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
#include <modbus.h>

/*
 * Note that this example is not self-contained. User will need to handle UART 
 * device initialization and relevant HAL/LL library includes. These steps are 
 * skipped in this example to ensure simplicity - illustrated here is the 
 * minimum code a user will need to use the modbus library AFTER the these 
 * steps.
 * 
*/

/* 
 * If using CubeMX, the HAL library files will be automatically placed in the 
 * correct location. The examples were tested with the Makefile option in 
 * CubeMX. 
 * 
 * If not using CubeMX to initialize the project, refer to the HAL/LL user 
 * manual for instructions on UART initialization.
 * 
 * In order to run the example, the device initialization and superloop code 
 * will need to be copied from this file into the CubeMX-generated files.
 * 
*/


/* Function initialization for the STM32 HAL Library */
/* 
 * Since this library was orignally written to work with the STM32 HAL/LL API, 
 * the UART functions match perfectly and can be directly mapped to the Modbus 
 * library functions.
*/
MB_StatusTypeDef (*MB_UART_Tx)(void*, uint16_t*, uint8_t*, uint8_t*) =
    &HAL_UART_Transmit;
MB_StatusTypeDef (*MB_UART_Rx)(void*, uint16_t*, uint8_t*, uint8_t*) =
    &HAL_UART_Receive;

int main()
{
    /* Single modbus device node */
    modbus_slave_device modbus_dev_single;
    /* Multiple modbus device nodes.. after all, what is the point of using 
     * Modbus in a single point-to-point connection? */
    /* Not illustrated beyond the definition, but should be clear enough */
    modbus_slave_device modbus_dev_multiple[10];

    /* Set the slave ID to 1 */
    modbus_dev_single.slave_id = 1;
    /* Attach the UART device on the STM32 to this node */
    /* Note that initialization of UART1 is not included in this example */
    modbus_dev_single.modbus_uart = &huart1;
    /* Continuously read the 30001 input register */
    uint16_t register = 30001;
    
    while (1) {
	MB_StatusTypeDef status = ReadInputRegisters(modbus_dev_single, register, 1);
	if (status == MB_OK) {
	    /* Do something with data in the response buffer */
	    /* ... */
	    ClearResponseBuffer(&modbus_dev_single);
	}
    }
    return 1;
}