-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
66 lines (54 loc) · 1.56 KB
/
Copy pathmain.cpp
File metadata and controls
66 lines (54 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <serial/serial.h>
#include <iostream>
/// 原生的serial串口通信示例程序
int main()
{
// List all available serial ports
std::vector<serial::PortInfo> ports = serial::list_ports();
if (ports.empty())
{
std::cout << "No serial ports found.\n";
return 0;
}
std::cout << "Available serial ports:\n";
for (const auto &port : ports)
{
// Print port name, description, and hardware ID
std::cout << "Port: " << port.port << " | Description: " << port.description
<< " | Hardware ID: " << port.hardware_id << "\n";
}
try
{
// Specify the port to open
std::string port = "COM3"; // Windows example, Linux: "/dev/ttyUSB0"
uint32_t baud = 115200; // Baud rate
// Open the serial port with a 1-second timeout
serial::Serial ser(port, baud, serial::Timeout::simpleTimeout(1000));
// Check if the port is successfully opened
if (ser.isOpen())
{
std::cout << "Port opened: " << port << " @ " << baud << "bps\n";
}
else
{
std::cerr << "Failed to open port: " << port << "\n";
return 1;
}
// Send a simple message
std::string msg = "Hello Serial!\n";
ser.write(msg);
std::cout << "Sent: " << msg;
// Read up to 100 bytes from the serial port
std::string result = ser.read(100);
std::cout << "Received: " << result << '\n';
// Close the port
ser.close();
}
catch (std::exception &e)
{
// Catch any exception and print the error message
std::cerr << "Exception: " << e.what() << '\n';
return 1;
}
return 0;
}