Created
July 20, 2016 12:20
-
-
Save fernandoc1/26115c3cebcb8609dc3456e96954ff41 to your computer and use it in GitHub Desktop.
Modbus libmodbus simple test
This file contains hidden or 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 <unistd.h> | |
| #include <string.h> | |
| #include <stdlib.h> | |
| #include <errno.h> | |
| #include <modbus/modbus.h> | |
| #include <iostream> | |
| #include <cstdio> | |
| #include <cstdlib> | |
| int main() | |
| { | |
| int tabRegSize = 32; | |
| uint16_t tabReg[tabRegSize]; | |
| uint8_t inputReg[tabRegSize]; | |
| memset(tabReg, 0, sizeof(tabReg)); | |
| memset(inputReg, 0, sizeof(inputReg)); | |
| modbus_t* ctx = modbus_new_tcp("127.0.0.1", 1502); | |
| //modbus_t* ctx = modbus_new_tcp("192.168.0.221", 502); | |
| if(modbus_connect(ctx) == -1) | |
| { | |
| std::cout << "Error while connecting to ModBus" << std::endl; | |
| } | |
| modbus_set_debug(ctx, TRUE); | |
| modbus_set_slave(ctx, 0); | |
| // Read 5 registers from the address 0 | |
| int numOfRegistersRead = modbus_read_registers(ctx, 0, 5, tabReg); | |
| //int numOfRegistersRead = modbus_read_input_bits(ctx, 0, 5, inputReg); | |
| if(numOfRegistersRead < 0) | |
| { | |
| std::cout << "Error on read: " << modbus_strerror(errno) << std::endl; | |
| } | |
| for(int i = 0; i < numOfRegistersRead; i++) | |
| { | |
| //std::cout << "[" << (int)i << "] " << (int)inputReg[i] << std::endl; | |
| std::cout << "[" << (int)i << "] " << (int)tabReg[i] << std::endl; | |
| } | |
| modbus_write_registers(ctx, 5, 10, tabReg); | |
| modbus_close(ctx); | |
| modbus_free(ctx); | |
| } |
This file contains hidden or 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
| all: | |
| g++ main.cpp -lmodbus |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment