-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmaster.c
More file actions
64 lines (57 loc) · 1.38 KB
/
Copy pathmaster.c
File metadata and controls
64 lines (57 loc) · 1.38 KB
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
/*
* master.c - a very small MODBUS master example
*/
#include <stdio.h>
#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <modbus.h>
int main(void) {
int i, j;
modbus_t *ctx;
int rc;
int addr = 1;
int16_t regs[10] = {101, 102 };
int16_t regs2[10];
int nb = sizeof(regs)/sizeof(int16_t);
// connect to server
ctx = modbus_new_tcp("127.0.0.1", 1502);
if (modbus_connect(ctx) == -1) {
fprintf(stderr,"Connection failed: %s\n",modbus_strerror(errno));
modbus_free(ctx);
exit(101);
}
modbus_set_debug(ctx, FALSE);
// write regs
for(i = 0; i != 10; i++) {
for(j = 0; j != nb; j++) {
regs[j] = rand() % 100;
}
rc = modbus_write_registers(ctx, 1, nb, regs);
if (rc != nb) {
printf("ERROR modbus_write_registers (%d)\n", rc);
printf("Address = %d, nb = %d\n", 1, nb);
exit(102);
}
rc = modbus_read_registers(ctx, 1, nb, regs2);
if (rc != nb) {
printf("ERROR modbus_read_registers (%d)\n", rc);
printf("Address = %d, nb = %d\n", addr, nb);
exit(102);
}
// print and check the response
printf("regs2[] =\t");
for(j = 0; j != nb; j++) {
if(regs[j] != regs2[j]) {
printf("FAILED to read back what we wrote at %d\n", j);
exit(103);
}
printf("%d ", regs2[j] );
}
printf("\n");
}
exit(0);
}