下面的代码是打开第二个串口,我正在尝试读取和写入它。现在我在第一个端口(Tera Term Console)上使用控制台功能来查看那里的日志(printf或dmesg)。 / p>
但是我无法从端口读取。控制台挂起。
int fd; /* File descriptor for the port */
#define BUFF_SIZE 1024
struct termios options;
char to_write[1024];
char to_read[1024];
int bytes_written;
int init_uart()
{
tcgetattr(fd, &options);
/* Set Baud Rate */
cfsetispeed( &options, B115200 );
cfsetospeed( &options, B115200 );
// Set the Charactor size
options.c_cflag &= ~CSIZE; /* Mask the character size bits */
options.c_cflag |= CS8; /* Select 8 data bits */
// Set parity - No Parity (8N1)
options.c_cflag &= ~PARENB;/*no parity bit*/
options.c_cflag &= ~CSTOPB;/* One bit stop bit*/
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;/* 8 Bits Character length*/
// Disable Hardware flowcontrol
options.c_cflag &= ~CRTSCTS;
// Enable Raw Input
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
// Disable Software Flow control
options.c_iflag &= ~(IXON | IXOFF | IXANY);
// Chose raw (not processed) output
options.c_oflag &= ~OPOST;
if ( tcsetattr( fd, TCSANOW, &options ) == -1 ){
printf ("Error with tcsetattr = %s\n", strerror ( errno ) );
return -1;
}
return 0;
}
int write_uart()
{
int i=0;
while (i < BUFF_SIZE-2){
to_write[i]='a';
i++;
}
to_write[i]='\n';
to_write[i+1]='\r';
// Write to the port
bytes_written = write(fd, to_write, BUFF_SIZE);
if(bytes_written < BUFF_SIZE){
fputs("write() of 1024 bytes failed!\n", stderr);
return -1;
}
return 0;
}
int
read_port(void)
{
int n = read(fd, to_read, sizeof(BUFF_SIZE));
if (n < 1024){
fputs("read failed!\n", stderr);
return -1;
}
return 0;
}
int main()
{
int i=0;
fd = open("/dev/ttyS1",O_RDWR | O_NOCTTY);
if(fd == -1)
perror("open_port: Unable to open /dev/ttyS1\n");
else
printf("ttyS0 Opened successfully\n");
if(init_uart())
perror("open_port: Unable to initialize /dev/ttyS0 Port\n");
else
printf("Port Initialization is done successfuly\n");
if(write_uart())
perror("write_port: Unable to write to /dev/ttyS0 Port\n");
else
printf("Write to the port happened successfully\n");
if(read_port())
perror("read_port: Unable to read from /dev/ttyS0 Port\n");
else
printf("Read to the port happened successfully\n");
close(fd);
return 0;
}
答案 0 :(得分:0)
@randomization,我认为你必须配置控制字符,即 c_cc [VTIME]和c_cc [VMIN] 。 VTIME:调用read时启动计时器。当至少有一个字节的数据可用时,或者当计时器到期时,read返回。如果计时器到期而没有任何输入变为可用,则读取返回0。 VMIN:读取块,直到较小的MIN字节或请求的字节数可用,并返回这两个值中较小的一个。 尝试配置VMIN和VTIME并测试您的应用程序。您可以配置其中任何一个。将在手册页中找到关于这些内容的良好描述,即 #man termios 。