我需要做一個.C以tty進行溝通,我發現這個代碼,但是當我嘗試arm-none-linux-gnueabi-c++
編譯我有這樣的錯誤:我有錯誤,但我不能確定
example2.c:73: error: expected unqualified-id before 'if'
example2.c:78: error: expected unqualified-id before '{' token
這是代碼
1 #include <errno.h>
2 #include <termios.h>
3 #include <unistd.h>
4 #include <string.h>
5 #include <stdio.h>
6 #include <iostream>
7 #include <fcntl.h>
8
9 using namespace std;
10
11 int set_interface_attribs (int fd, int speed, int parity)
12 {
13 struct termios tty;
14 memset (&tty, 0, sizeof tty);
15 if (tcgetattr (fd, &tty) != 0)
16 {
17 cout<< "error" << endl;
18 return -1;
19 }
20
21 cfsetospeed (&tty, speed);
22 cfsetispeed (&tty, speed);
23
24 tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars
25 // disable IGNBRK for mismatched speed tests; otherwise receive break
26 // as \000 chars
27 tty.c_iflag &= ~IGNBRK; // ignore break signal
28 tty.c_lflag = 0; // no signaling chars, no echo,
29 // no canonical processing
30 tty.c_oflag = 0; // no remapping, no delays
31 tty.c_cc[VMIN] = 0; // read doesn't block
32 tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
33
34 tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl
35
36 tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
37 // enable reading
38 tty.c_cflag &= ~(PARENB | PARODD); // shut off parity
39 tty.c_cflag |= parity;
40 tty.c_cflag &= ~CSTOPB;
41 tty.c_cflag &= ~CRTSCTS;
42
43 if (tcsetattr (fd, TCSANOW, &tty) != 0)
44 {
45 cout<< "error" << endl;
46 return -1;
47 }
48 return 0;
49 }
50
51 void
52 set_blocking (int fd, int should_block)
53 {
54 struct termios tty;
55 memset (&tty, 0, sizeof tty);
56 if (tcgetattr (fd, &tty) != 0)
57 {
58 cout<< "error" << endl;
59 return;
60 }
61
62 tty.c_cc[VMIN] = should_block ? 1 : 0;
63 tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
64
65 if (tcsetattr (fd, TCSANOW, &tty) != 0)
66 cout<< "error" << endl;
67 }
68
69 const char *portname = "/dev/ttyUSB1";
70
71 int fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC);
72
73 if (fd < 0)
74 {
75 cout<< "error" << endl;
76 return;
77 }
78 {
79 set_interface_attribs (fd, B115200, 0); // set speed to 115,200 bps, 8n1 (no parity)
80 set_blocking (fd, 0); // set no blocking
81
82 write (fd, "hello!\n", 7); // send 7 character greeting
83 char buf [100];
84 int n = read (fd, buf, sizeof buf);
85 }
你在函數末尾缺少'}'。請不要發佈行號。 –
您需要正確縮進。看起來你在函數外有一個'if'。 – tadman
從第69行開始的所有代碼都不在函數內部。 (他不會錯過任何括號。)當你盲目地從互聯網上獲取代碼,把它扔到你的項目中,並且不注意發生了什麼的時候,會發生什麼。 –