11// Writes floating point holding registers to SolarPi humidity meter
22
3- // The humidity sensor calibration is composed of 4 decimal values.
4- // The first 2 are the minimum and maximum humidity calibration values in %RH.
5- // The following 2 are the output values of the analog-to-digital converter
3+ // The humidity sensor calibration is composed of 4 decimal values.
4+ // The first 2 are the minimum and maximum humidity calibration values in %RH.
5+ // The following 2 are the output values of the analog-to-digital converter
66// (in LSB) corresponding to the calibration values.
77
88// This example code is in the public domain.
@@ -14,7 +14,12 @@ using namespace std;
1414using namespace Modbus ;
1515
1616int main (int argc, char **argv) {
17- string port (" /dev/ttyUSB2" );
17+ string port (" /dev/ttyUSB0" );
18+
19+ if (argc > 1 ) {
20+
21+ port = argv[1 ]; // the serial port can be provided as a parameter on the command line.
22+ }
1823
1924 Master mb (Rtu, port , " 38400E1" ); // new master on RTU
2025 // if you have to handle the DE signal of the line driver with RTS,
@@ -24,42 +29,36 @@ int main (int argc, char **argv) {
2429
2530 if (mb.open ()) { // open a connection
2631 // success, do what you want here
27-
32+ int ret;
33+
2834 // the bytes in the registers are arranged in big endian.
29- // the solarpi calibration registers are arranged in little endian.
35+ // the solarpi calibration registers are arranged in little endian.
3036 Data<float , EndianBigLittle> registers[4 ];
3137
3238 mb.setSlave (33 ); // to the slave at address 33
33-
34- // reads and print previous values
35- if (mb.readRegisters (1 , registers, 4 ) > 0 ) {
3639
37- cout << " R0=" << registers[0 ].value () << endl;
38- cout << " R1=" << registers[1 ].value () << endl;
39- cout << " R2=" << registers[2 ].value () << endl;
40- cout << " R3=" << registers[3 ].value () << endl;
41- }
42- else {
43- cerr << " Unable to read input registers !" << endl;
44- exit (EXIT_FAILURE);
45- }
46-
47- // modify to new values
40+ // set values ...
4841 registers[0 ] = 152.3 ;
4942 registers[1 ] = 1010.7 ;
5043 registers[2 ] = 45 ;
5144 registers[3 ] = 901 ;
45+
5246 // then writing to registers
53- if (mb.writeRegisters (1 , registers, 4 ) < 0 ) {
47+ ret = mb.writeRegisters (1 , registers, 4 );
48+
49+ if (ret < 0 ) {
5450
55- cerr << " Unable to write input registers !" << endl;
51+ cerr << " Unable to write input registers ! " << mb. lastError () << endl;
5652 exit (EXIT_FAILURE);
5753 }
58-
54+ else {
55+ cout << ret << " registers written (16-bit)." << endl;
56+ }
57+
5958 mb.close ();
6059 }
6160 else {
62- cerr << " Unable to open MODBUS connection to " << port << endl;
61+ cerr << " Unable to open MODBUS connection to " << port << " : " << mb. lastError () << endl;
6362 exit (EXIT_FAILURE);
6463 }
6564
0 commit comments