MRPT  1.9.9
test.cpp
Go to the documentation of this file.
1 /* +------------------------------------------------------------------------+
2  | Mobile Robot Programming Toolkit (MRPT) |
3  | https://www.mrpt.org/ |
4  | |
5  | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |
6  | See: https://www.mrpt.org/Authors - All rights reserved. |
7  | Released under BSD License. See: https://www.mrpt.org/License |
8  +------------------------------------------------------------------------+ */
9 
10 #include <mrpt/comms/CSerialPort.h>
11 #include <iostream>
12 
13 using namespace mrpt::comms;
14 using namespace std;
15 
16 int main()
17 {
18  try
19  {
20  CSerialPort* serPort;
21 
22  string serName;
23 
24  cout << "Serial port test application: Use it with a loopback serial "
25  "port (pins 2-3 connected)"
26  << endl;
27 
28  cout << "Enter the serial port name (e.g. COM1, ttyS0, ttyUSB0): ";
29  getline(cin, serName);
30 
31  cout << endl;
32  cout << "Opening serial port...";
33  serPort = new CSerialPort(serName);
34  cout << "OK" << endl;
35 
36  cout << "Setting timeouts...";
37  serPort->setTimeouts(100, 1, 100, 1, 100);
38  cout << "OK" << endl;
39 
40  cout << "Setting baud rate...";
41  serPort->setConfig(500000);
42  cout << "OK" << endl;
43 
44  for (int i = 0; i < 10; i++)
45  {
46  // Test write:
47  cout << "Writing test data...";
48  const char buf1[] = "Hello world!";
49  size_t written = serPort->Write(buf1, sizeof(buf1));
50  cout << written << " bytes written." << endl;
51 
52  // Read:
53  cout << "Reading data...";
54  char buf2[100];
55  size_t nRead = serPort->Read(buf2, sizeof(buf2));
56  cout << nRead << " bytes read: '";
57 
58  buf2[nRead] = 0;
59  cout << buf2 << "'" << endl;
60  }
61 
62  delete serPort;
63  }
64  catch (const std::exception& e)
65  {
66  cerr << e.what() << endl;
67  return -1;
68  }
69 
70  return 0;
71 }
size_t Read(void *Buffer, size_t Count) override
Implements the virtual method responsible for reading from the stream - Unlike CStream::ReadBuffer, this method will not raise an exception on zero bytes read, as long as there is not any fatal error in the communications.
A communications serial port built as an implementation of a utils::CStream.
Definition: CSerialPort.h:41
STL namespace.
void setConfig(int baudRate, int parity=0, int bits=8, int nStopBits=1, bool enableFlowControl=false)
Changes the configuration of the port.
size_t Write(const void *Buffer, size_t Count) override
Introduces a pure virtual method responsible for writing to the stream.
void setTimeouts(int ReadIntervalTimeout, int ReadTotalTimeoutMultiplier, int ReadTotalTimeoutConstant, int WriteTotalTimeoutMultiplier, int WriteTotalTimeoutConstant)
Changes the timeouts of the port, in milliseconds.
Serial and networking devices and utilities.



Page generated by Doxygen 1.8.14 for MRPT 1.9.9 Git: 8fe78517f Sun Jul 14 19:43:28 2019 +0200 at lun oct 28 02:10:00 CET 2019