Interface via Modbus TCP (C Environment)

J

Thread Starter

Jesus

Hello,

I am trying to develop a C code that would be able to request Modbus registers and when the messages are returned. The code needs to identify the parameter type and convert them into engineering units.

Any suggestions would be greatly appreciated.

Thank you!
 
Hi Michael,

>I suggest you have a look at:
>http://libmodbus.org

I actually did look at those files but since I am using Windows 10 OS that did not really help.

I found a useful tutorial online: http://www.binarytides.com/winsock-socket-programming-tutorial/

However, I am having issues when I try to connect to a Modbus PLC simulator (server). I created the socket to connect to the PLC sim server. It only connects for about a second and then it disconnects. I am trying to figure out why that is happening. Below is the C code I am using in Visual Studio 2015:<pre>
/*
Create a TCP socket
*/
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include<stdio.h>
#include<winsock2.h>

#pragma comment(lib,"ws2_32.lib") //Winsock Library

int main(int argc, char *argv[])
{
WSADATA wsa;
SOCKET s;
struct sockaddr_in server;
char *message, server_reply[2000];
int recv_size;

printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printf("Failed. Error Code : %d", WSAGetLastError());
return 1;
}

printf("Initialised.\n");

//Create a socket
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
printf("Could not create socket : %d", WSAGetLastError());
}

printf("Socket created.\n");


server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons(502);

//Connect to remote server
if (connect(s, (struct sockaddr *)&server, sizeof(server)) < 0)
{
puts("connect error");
return 1;
}

puts("Connected");

//Send some data
message = "GET / HTTP/1.1\r\n\r\n";
if (send(s, message, strlen(message), 0) < 0)
{
puts("Send failed");
return 1;
}
puts("Data Send\n");

//Receive a reply from the server
if ((recv_size = recv(s, server_reply, 2000, 0)) == SOCKET_ERROR)
{
puts("recv failed");
}

puts("Reply received\n");

//Add a NULL terminating character to make it a proper string before printing
server_reply[recv_size] = '\0';
puts(server_reply);

return 0;
}</pre>
Any other help would be greatly appreciated!
 
Top