-
-
Save dglover/8182802db8bf248854d138bbbc98f1d1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <modbus.h> | |
#include <errno.h> | |
#include <string.h> | |
int main(int argc, char *argv[]) { | |
modbus_t *ctx; | |
uint16_t tab_reg[64]; | |
int rc; | |
char ip[16] = "192.168.100.102"; | |
int port = 502; | |
if (argc > 1) { | |
if (strlen(argv[1]) < 16) strcpy(ip, argv[1]); | |
} | |
if (argc > 2) { | |
port = atoi(argv[2]); | |
} | |
printf("using %s:%d\n",ip, port); | |
ctx = modbus_new_tcp(ip, port); | |
modbus_set_debug(ctx, 1); | |
modbus_connect(ctx); | |
rc = modbus_read_registers(ctx, 0, 10, tab_reg); | |
if (rc == 10) { | |
printf("Read registers: "); | |
for (int i=0; i<10; i++) { | |
printf("%d ", tab_reg[i]); | |
} | |
printf("\n"); | |
printf("%f\n", *(float*)tab_reg); | |
} else { | |
fprintf(stderr, "Failed to read registers: %s\n", modbus_strerror(errno)); | |
} | |
modbus_close(ctx); | |
modbus_free(ctx); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <modbus/modbus.h> | |
#include <errno.h> | |
int main(int argc, char *argv[]) { | |
modbus_t *ctx; | |
modbus_mapping_t *mb_mapping; | |
int socket; | |
printf("starting modbus server\n"); | |
ctx = modbus_new_tcp(NULL, 502); | |
modbus_set_debug(ctx, 1); | |
mb_mapping = modbus_mapping_new(0, 0, 100, 0); | |
socket = modbus_tcp_listen(ctx, 1); | |
modbus_tcp_accept(ctx, &socket); | |
for (;;) { | |
uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH]; | |
int rc; | |
rc = modbus_receive(ctx, query); | |
if (rc > 0) { | |
modbus_reply(ctx, query, rc, mb_mapping); | |
} else if (rc == -1) { | |
break; | |
} | |
} | |
printf("Quit the loop: %s\n", modbus_strerror(errno)); | |
modbus_mapping_free(mb_mapping); | |
modbus_close(ctx); | |
modbus_free(ctx); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment