Repository navigation
Expand file tree
/
Copy pathtest-write.cpp
More file actions
85 lines (70 loc) · 2.45 KB
/
Copy pathtest-write.cpp
File metadata and controls
85 lines (70 loc) · 2.45 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//
// Created by qianchengyi on 2025/1/4.
//
#include <iostream>
#include <string>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <cstring>
#include <cmath>
#include <pthread.h>
using namespace std;
int serial_port;
int setupSerialPort(const char* serialPortPath) {
// 打开串口
int serial_port = open(serialPortPath, O_RDWR);
// 检查串口是否打开成功
if (serial_port < 0) {
std::cerr << "Error " << errno << " from open: " << strerror(errno) << std::endl;
return -1;
}
// 配置串口参数
struct termios tty;
if(tcgetattr(serial_port, &tty) != 0) {
std::cerr << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl;
return -1;
}
// 设置波特率为9600 bps
cfsetospeed(&tty, B9600);
cfsetispeed(&tty, B9600);
// 无校验位
tty.c_cflag &= ~PARENB; // 清除奇偶校验位
// 设置其他串口参数
tty.c_cflag &= -CSTOPB; // 1位停止位
tty.c_cflag &= ~CSIZE; // 清除所有位大小掩码
tty.c_cflag |= CS8; // 设置8个数据位
tty.c_cflag &= ~CRTSCTS; // 关闭RTS/CTS流控制
tty.c_cflag |= CREAD | CLOCAL; // 打开接收器,忽略调制解调器控制线
tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHONL | ISIG); // 关闭规范模式、回显等
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // 关闭软件流控制
tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL); // 关闭特殊处理
tty.c_oflag &= ~OPOST; // 关闭输出处理
tty.c_oflag &= ~ONLCR; // 关闭换行转回车换行
// 保存tty设置,将改变应用于串口
if (tcsetattr(serial_port, TCSANOW, &tty) != 0) {
std::cerr << "Error " << errno << " from tcsetattr: " << strerror(errno) << std::endl;
return -1;
}
return serial_port;
}
void writeSerialPort(const void *w_data) {
ssize_t bytes_written = write(serial_port, w_data, 1);
if (bytes_written < 0) {
std::cerr << "Error writing to serial port: " << strerror(errno) << std::endl;
}
else cout << "Message sent.\n";
}
int main() {
const char* serialPortPath = "/dev/ttyAMA0"; // 串口设备路径
serial_port = setupSerialPort(serialPortPath);
if(serial_port < 0) {
return 1;
}
// 发送数据
int Data[4] = {1, 2, 114514, 0x5A};
// writeSerialPort(Data);
for(int i = 0; i < 4; i++) writeSerialPort(&Data[i]);
return 0;
}