diff options
Diffstat (limited to 'serial/wheel.c')
-rw-r--r-- | serial/wheel.c | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/serial/wheel.c b/serial/wheel.c new file mode 100644 index 0000000..936f55c --- /dev/null +++ b/serial/wheel.c | |||
@@ -0,0 +1,70 @@ | |||
1 | #include "serial.h" | ||
2 | |||
3 | int fd; // 轮子的串口文件描述符 | ||
4 | char portname[50] = "/dev/ttyUSB0"; // 串口设备名 | ||
5 | struct termios tty; | ||
6 | |||
7 | bool whellInit() { | ||
8 | // 打开串口 | ||
9 | fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC); | ||
10 | if (fd < 0) { | ||
11 | fprintf(stderr, "Error opening %s: %s\n", portname, strerror(errno)); | ||
12 | return false; | ||
13 | } | ||
14 | |||
15 | // 设置串口参数 | ||
16 | memset(&tty, 0, sizeof tty); | ||
17 | if (tcgetattr(fd, &tty) != 0) { | ||
18 | fprintf(stderr, "Error from tcgetattr: %s\n", strerror(errno)); | ||
19 | return false; | ||
20 | } | ||
21 | |||
22 | cfsetospeed(&tty, B115200); // 设置输出波特率为115200 | ||
23 | cfsetispeed(&tty, B115200); // 设置输入波特率为115200 | ||
24 | |||
25 | tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars | ||
26 | tty.c_iflag &= ~IGNBRK; // ignore break signal | ||
27 | tty.c_lflag = 0; // no signaling chars, no echo, | ||
28 | // no canonical processing | ||
29 | tty.c_oflag = 0; // no remapping, no delays | ||
30 | tty.c_cc[VMIN] = 0; // read doesn't block | ||
31 | tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout | ||
32 | |||
33 | tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl | ||
34 | tty.c_cflag |= (CLOCAL | CREAD); // ignore modem controls, | ||
35 | // enable reading | ||
36 | tty.c_cflag &= ~(PARENB | PARODD); // shut off parity | ||
37 | tty.c_cflag |= 0; | ||
38 | tty.c_cflag &= ~CSTOPB; | ||
39 | tty.c_cflag &= ~CRTSCTS; | ||
40 | |||
41 | if (tcsetattr(fd, TCSANOW, &tty) != 0) { | ||
42 | fprintf(stderr, "Error from tcsetattr: %s\n", strerror(errno)); | ||
43 | return false; | ||
44 | } | ||
45 | return true; | ||
46 | } | ||
47 | |||
48 | bool wheelSend(byte a, byte a_v, byte b, byte b_v) { | ||
49 | unsigned char data[7] = {0x53, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00}; | ||
50 | byte checksum = 0; | ||
51 | data[2] = a; | ||
52 | data[3] = a_v; | ||
53 | data[4] = b; | ||
54 | data[5] = b_v; | ||
55 | |||
56 | for (int i = 0; i < 6; i++) { | ||
57 | checksum ^= data[i]; | ||
58 | } | ||
59 | data[6] = checksum; | ||
60 | |||
61 | // 发送数据 | ||
62 | if (write(fd, data, 7) != 7) { | ||
63 | fprintf(stderr, "Failed to write to the serial port\n"); | ||
64 | return false; | ||
65 | } | ||
66 | |||
67 | printf("Data %02X %02X %02X %02X %02X %02X %02X wheelSend successfully!\n", | ||
68 | data[0], data[1], data[2], data[3], data[4], data[5], data[6]); | ||
69 | return true; | ||
70 | } \ No newline at end of file | ||